答:
The switch is a statement, so this is just putting a statement in the else.

It's no different from

```<code>else
  a = 0;
</code>```

or

```<code>else
{
  switch(a)
  {
  case 1:
  ...
  }
}
</code>```

It's not a very common way of writing it, but it's fine.

Title: If ... else switch ... statement

Body:
The switch is a statement, so this is just putting a statement in the else.

It's no different from

else
  a = 0;

or

else
{
  switch(a)
  {
  case 1:
  ...
  }
}

It's not a very common way of writing it, but it's fine.


来源: stackexchange

问:
Scala: it is possible to use generic type at runtime?
i wonder if i can change the implementation of such a method:

```<code>def foo() {
   val json : String = ; // get json from somewhere
   val jsonAst = new String(json).parseJson // or JsonParser(source)
   val msg = jsonAst.convertTo[UserDetails]
</code>```

}

so i can provide the "UserDetails" as parameter

so calling foo will be something like:

```<code>foo[UserDetails]()....
</code>```

by the way:

convertTo signature is:

```<code>def convertTo[T :JsonReader]: T = jsonReader[T].read(this)

trait JsonReader[T] {
   def read(json: JsValue): T
}
</code>```

答:
Dima's solution should be working, but your implementation of convertTo seems strange. I think it should be something like :

def convertTo[T :JsonReader]: T = implicitly[JsonReader[T]].read(this)

ContentLicense: CC BY-SA 3.0

Body:
i wonder if i can change the implementation of such a method:

def foo() {
   val json : String = ; // get json from somewhere
   val jsonAst = new String(json).parseJson // or JsonParser(source)
   val msg = jsonAst.convertTo[UserDetails]

}

so i can provide the "UserDetails" as parameter

so calling foo will be something like:

foo[UserDetails]()....

by the way:

convertTo signature is:

def convertTo[T :JsonReader]: T = jsonReader[T].read(this)

trait JsonReader[T] {
   def read(json: JsValue): T
}


问:
If ... else switch ... statement
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:

```<code>if (a == 0) {
    puts("0");
} else switch (a) {
    case 1: puts("1"); break;
    case 2: puts("2"); break;
    default: puts("default"); break;
}
</code>```

Is if ... else switch ... correct statement?

答:
Syntax of if is:

```<code>if ( condition ) statement-true  else statement-false
condition is an expression convertible to a boolean (true/false)
statement-true is a statement which is executed if condition is true
statement-false is a statement which is executed if condition is false
</code>```

And switch block is a statement.

So yes, your code exhibit correct statement.

Title: If ... else switch ... statement

Body:
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:

if (a == 0) {
    puts("0");
} else switch (a) {
    case 1: puts("1"); break;
    case 2: puts("2"); break;
    default: puts("default"); break;
}

Is if ... else switch ... correct statement?

Body:
Syntax of if is:

if ( condition ) statement-true  else statement-false
condition is an expression convertible to a boolean (true/false)
statement-true is a statement which is executed if condition is true
statement-false is a statement which is executed if condition is false

And switch block is a statement.

So yes, your code exhibit correct statement.


问:
Deserializing a dynamic returns Newtonsoft.Json.Linq.JValue does not contain a definition for 'info'
I have RESTful endpoint that returns the following:

```<code>{"error_msg": "{'status': 1, 'info': \"Operation is not allowed on 'XXX, ['YYY']'\", 'key': 'ZZZZ', 'extra': 'None', 'data': {}, 'EEEE': False}"}
</code>```

Some text was replaced above (XXX, ZZZ etc.).

My code is as follows:

```<code>dynamic response = JsonConvert.DeserializeObject(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
Console.Error.WriteLine(response.error_msg.info);
</code>```

After building running the code I get the following error:

Newtonsoft.Json.Linq.JValue' does not contain a definition for 'info'

Any idea how to solve this?

Thanks

答: That's because error_msg here is a string, not an object. Either make it not a string, or deserialize twice, i.e. get the string error_msg out, and then deserialize that string.

Body:
I have RESTful endpoint that returns the following:

{"error_msg": "{'status': 1, 'info': \"Operation is not allowed on 'XXX, ['YYY']'\", 'key': 'ZZZZ', 'extra': 'None', 'data': {}, 'EEEE': False}"}

Some text was replaced above (XXX, ZZZ etc.).

My code is as follows:

dynamic response = JsonConvert.DeserializeObject(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
Console.Error.WriteLine(response.error_msg.info);

After building running the code I get the following error:

Newtonsoft.Json.Linq.JValue' does not contain a definition for 'info'

Any idea how to solve this?

Thanks


问:
jQuery slider - slide: function (event, ui) in for loop
I have a simple code with 2 (or more) jQuery sliders:

HTML:

```<code><label for="ST">ST:</label>
<input type="text" id="ST" value="10">
<div id="slider-ST"></div>

<label for="DX">DX:</label>
<input type="text" id="DX" value="10">
<div id="slider-DX"></div>
</code>```

and JS:

```<code>$function(){
$( "#slider-ST" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#ST");}
});

$( "#slider-DX" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#DX");}
});

function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}
</code>```

It works perfectly well.

Now, I want to make it nicer and I would like to call these functions in a for loop:

```<code>$function(){
var ID_Inp = ["#slider-ST", "#slider-DX"];
var ID_Sli = ["#ST", "#DX"];
var i;
for (i=0;i<ID_Inp.length;i++)
{
  $(ID_Inp[i]).slider({
  orientation: "horizontal",
  range: "min",
  min: 1,
  max: 18,
  value: 10,

  slide: function (event, ui) {sliderChange(ui,ID_Sli[i]);}
  });
};
function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}
</code>```

Simplified code also available at jsfiddle:

working

not working (using for loop)

And what happens is, that i is set to 2 after changing the slider's value and obviously function sliderChange doesn't work properly (ID_Sli[i] is undefined).

Any ideas?

答:
Dear Ramakanth,

Thank you for your answers. Thanks to those, I compiled the code that works well (and kind-of uses for, so I don't have to manually type in IDs in initialization phase):

```<code><div class="params">
<div id="STSection">
<label for="ST">Strength:</label>
<input type="text" id="ST" value="10">
<div id="slider-ST" style="width:300px;"></div>
</div>
<div id="DXSection">
<label for="DX">Dexterity:</label>
<input type="text" id="DX" value="11">
<div id="slider-DX" style="width:300px;"></div>
</div>
</code>```

and JS:

```<code>$('.params div').each(function() {
        $(this).find("div").slider({
        value: $(this).find("input").val(),
        orientation: "horizontal",
        slide: function( event, ui ) {
            $(this).parent().find("input").val(ui.value);
           }
        });
    });
</code>```

The most important part for me to understand was how to work with .each() that are embedded into div sections. Then obviously to use parent() and find(). Those are really helpful!

Thank you!

Body:
I have a simple code with 2 (or more) jQuery sliders:

HTML:

ST:
<input type="text" id="ST" value="10">

DX:
<input type="text" id="DX" value="10">

and JS:

$function(){
$( "#slider-ST" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#ST");}
});

$( "#slider-DX" ).slider({
  orientation: "horizontal",
  range: "min",
  value: 10,

  slide: function (event, ui) {sliderChange(ui,"#DX");}
});

function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}

It works perfectly well.

Now, I want to make it nicer and I would like to call these functions in a for loop:

$function(){
var ID_Inp = ["#slider-ST", "#slider-DX"];
var ID_Sli = ["#ST", "#DX"];
var i;
for (i=0;i<ID_Inp.length;i++)
{
  $(ID_Inp[i]).slider({
  orientation: "horizontal",
  range: "min",
  min: 1,
  max: 18,
  value: 10,

  slide: function (event, ui) {sliderChange(ui,ID_Sli[i]);}
  });
};
function sliderChange(t, disp)
{
   $(disp).val(t.value);
};
}

Simplified code also available at jsfiddle:

working

not working (using for loop)

And what happens is, that i is set to 2 after changing the slider's value and obviously function sliderChange doesn't work properly (ID_Sli[i] is undefined).

Any ideas?

Body:
Dear Ramakanth,

Thank you for your answers. Thanks to those, I compiled the code that works well (and kind-of uses for, so I don't have to manually type in IDs in initialization phase):

<div class="params">
<div id="STSection">
<label for="ST">Strength:</label>
<input type="text" id="ST" value="10">
<div id="slider-ST" style="width:300px;"></div>
</div>
<div id="DXSection">
<label for="DX">Dexterity:</label>
<input type="text" id="DX" value="11">
<div id="slider-DX" style="width:300px;"></div>
</div>

and JS:

$('.params div').each(function() {
        $(this).find("div").slider({
        value: $(this).find("input").val(),
        orientation: "horizontal",
        slide: function( event, ui ) {
            $(this).parent().find("input").val(ui.value);
           }
        });
    });

The most important part for me to understand was how to work with .each() that are embedded into div sections. Then obviously to use parent() and find(). Those are really helpful!

Thank you!


问:
finding date before 30 days in hive-0.10.0
I have 2 hadoop clusters, One has hive-0.10.0 installed and another has hive-1.1.0 version installed.

I am able to run below query in hive-1.1.0 which gives date before 30 days from present date

```<code>select date_sub(from_unixtime(floor(unix_timestamp()/(60*24*24))*60*24*24), 30)
</code>```

But, the Same query is giving syntax error in hive-0.10.0

```<code>ok failed: parseexception line 1:79 mismatched input '' expecting from near ')' in from clause
</code>```

答:
1.

Way too complected.

This will get you the same result:

```<code>select date_sub(from_unixtime(unix_timestamp()),30)
</code>```

2.

Queries without FROM clause are only supported from hive 0.13
https://issues.apache.org/jira/browse/HIVE-178

Create s table with a single row (similar to Oracle dual) and use it as source

Body:
I have 2 hadoop clusters, One has hive-0.10.0 installed and another has hive-1.1.0 version installed.

I am able to run below query in hive-1.1.0 which gives date before 30 days from present date

select date_sub(from_unixtime(floor(unix_timestamp()/(60*24*24))*60*24*24), 30)

But, the Same query is giving syntax error in hive-0.10.0

ok failed: parseexception line 1:79 mismatched input '' expecting from near ')' in from clause

Body:
1.

Way too complected.

This will get you the same result:

select date_sub(from_unixtime(unix_timestamp()),30)

2.

Queries without FROM clause are only supported from hive 0.13
https://issues.apache.org/jira/browse/HIVE-178

Create s table with a single row (similar to Oracle dual) and use it as source


问:
Take screenshot of multiple URLs using selenium (python)
I am trying to take a screenshot of multiple websites using python selenium library.

Here I have an array of website like

```<code>data = array of website [ 'google.com', 'youtube.com'... ]
</code>```

If a website takes too long to load, I want the program starts open next websites.

But this code doesn't do what I expected...

```<code>browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')

for index, url in enumerate(data):
    browser.set_page_load_timeout(30)
    try:
        browser.get('http://'+data[index])
    except:
        print("takes too long")
        browser.quit()
        browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')
    else:
        browser.maximize_window()
        browser.implicitly_wait(20)
        # where images saved
        browser.save_screenshot('/.../'+str(index)+'.png')

browser.quit()
</code>```

I think I should use browser.close(), but I don't know exactly how.

答:
You should spend some time reading the docs for the different statements that you are using. You are using several incorrectly.

I think this will work. One issue may be that if the page loads long, the browser will not be allowed to navigate to a new page with browser.get(). You might try sending an ESC key or one of the many other options you can find by googling.

I added the site to the "took too long" message so you would know which ones didn't finish loading in time.

```<code>browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')
browser.set_page_load_timeout(30)
browser.maximize_window()

for index, url in enumerate(data):
    try:
        browser.get('http://' + data[index])
    except:
        print(data[index] + ' took too long')
    else:
        # where images saved
        browser.save_screenshot('/.../' + str(index) + '.png')

browser.quit()
</code>```

Body:
I am trying to take a screenshot of multiple websites using python selenium library.

Here I have an array of website like

data = array of website [ 'google.com', 'youtube.com'... ]

If a website takes too long to load, I want the program starts open next websites.

But this code doesn't do what I expected...

browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')

for index, url in enumerate(data):
    browser.set_page_load_timeout(30)
    try:
        browser.get('http://'+data[index])
    except:
        print("takes too long")
        browser.quit()
        browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')
    else:
        browser.maximize_window()
        browser.implicitly_wait(20)
        # where images saved
        browser.save_screenshot('/.../'+str(index)+'.png')

browser.quit()

I think I should use browser.close(), but I don't know exactly how.

Body:
You should spend some time reading the docs for the different statements that you are using. You are using several incorrectly.

I think this will work. One issue may be that if the page loads long, the browser will not be allowed to navigate to a new page with browser.get(). You might try sending an ESC key or one of the many other options you can find by googling.

I added the site to the "took too long" message so you would know which ones didn't finish loading in time.

browser = webdriver.Chrome('/Users/wk/Desktop/checkSafeContent/chromedriver')
browser.set_page_load_timeout(30)
browser.maximize_window()

for index, url in enumerate(data):
    try:
        browser.get('http://' + data[index])
    except:
        print(data[index] + ' took too long')
    else:
        # where images saved
        browser.save_screenshot('/.../' + str(index) + '.png')

browser.quit()


问:
Using the $ selector in Chrome Console with on jQuery
I'm wondering why I can use $('.myelement') in Google Chrome console? I thought that was only a jQuery thing.

Is this part of JavaScript?

答:
The $ function is provided by the Chrome Dev Tools API although it will be overwritten if the page provides a global $ variable (e.g. by loading jQuery).

It is not part of JavaScript (nor are any DOM manipulation functions).


问:
Retrieve current server's provider URL at runtime on weblogic (non-deprecated way)
I have an Singleton Service deployed to a Weblogic cluster, i'd like to know the provider url (listen address and port) of the server on which the singleton service is deployed from the singleton itself (server side, not logs).

I found this (old) article from Oracle, and wrote this method to construct the provider url.

```<code>private static String getCurrentServerUrl() throws NamingException {
    weblogic.management.MBeanHome home =
        (weblogic.management.MBeanHome) new Environment().getInitialContext().lookup(weblogic.management.MBeanHome.LOCAL_JNDI_NAME);

    Set mbeanSet = home.getMBeansByType("ServerRuntime");
    Iterator mbeanIterator = mbeanSet.iterator();

    while (mbeanIterator.hasNext()) {
        ServerRuntimeMBean serverRuntime = (ServerRuntimeMBean) mbeanIterator.next();
        if (serverRuntime.getState().equals(ServerStates.RUNNING)) {
            return serverRuntime.getURL("t3");
        }
    }

    return null;
}
</code>```

The problem is that this code is deprecated (see MBeanHome, MBeanHome#getMBeansByType(String) and MBeanHome#LOCAL_JNDI_NAME).

What is the non-deprecated way to do this?

PS : I don't want to enter any address (whether it is the address for the server or the address for a JMX service since the application is designed to be migratable from server to server withtout recompile or reconfigure of the app it self).

Thanks for your help.

答:
You can lookup the runtime JMX which is the same for all application. No need to enter address, user or password.

1) Lookup the MBeanServer

```<code>InitialContext ctx = new InitialContext();
MBeanServer mBeanServer = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
</code>```

2) Then you need to retrieve the name of the server running the application. Here there is two ways (maybe more).

The simplest

```<code>String serverName = System.getProperty("weblogic.Name");
</code>```

But I don't know if it's a reliable way.

The other way to get the server name is to look for it in the runtime service attributes.

```<code>ObjectName serviceObjectName = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
String serverName = (String) mBeanServer.getAttribute(serviceObjectName, "ServerName");
</code>```

3) Now we can create the runtime server ObjectName ...

```<code>ObjectName serverRuntime = new ObjectName("com.bea:Name="+serverName+",Type=ServerRuntime");
</code>```

4) ... and get the attributes we need

```<code>String listenAddress = mBeanServer.getAttribute(serverRuntime, "ListenAddress");
Integer listenPort = mBeanServer.getAttribute(serverRuntime, "ListenPort");
</code>```

rem: listenAddress is formatted as hostname/IP, you have to manipulate it to only get IP or host

From there you can access to a lot of information; like the address of the admin server that manage the runtime server, the runtime cluster, ... .

Here is a list I get from the WLST console (WL12.2.1), didn't test if we have access to all attributes/MBean's.

```<code>dr--   ApplicationRuntimes
dr--   AsyncReplicationRuntime
dr--   BatchJobRepositoryRuntime
dr--   ClassLoaderRuntime
dr--   ClusterRuntime
dr--   ConcurrentManagedObjectsRuntime
dr--   ConnectorServiceRuntime
dr--   DefaultExecuteQueueRuntime
dr--   EntityCacheCumulativeRuntime
dr--   EntityCacheCurrentStateRuntime
dr--   EntityCacheHistoricalRuntime
dr--   ExecuteQueueRuntimes
dr--   JDBCServiceRuntime
dr--   JMSRuntime
dr--   JTARuntime
dr--   JVMRuntime
dr--   JoltRuntime
dr--   LibraryRuntimes
dr--   LogBroadcasterRuntime
dr--   LogRuntime
dr--   MANAsyncReplicationRuntime
dr--   MANReplicationRuntime
dr--   MailSessionRuntimes
dr--   MaxThreadsConstraintRuntimes
dr--   MessagingBridgeRuntime
dr--   MessagingBridgeRuntimes
dr--   MinThreadsConstraintRuntimes
dr--   PartitionRuntimes
dr--   PathServiceRuntime
dr--   PathServiceRuntimes
dr--   PersistentStoreRuntimes
dr--   RequestClassRuntimes
dr--   SAFRuntime
dr--   SNMPAgentRuntime
dr--   ServerChannelRuntimes
dr--   ServerLogRuntime
dr--   ServerSecurityRuntime
dr--   ServerServices
dr--   SingleSignOnServicesRuntime
dr--   ThreadPoolRuntime
dr--   TimerRuntime
dr--   WANReplicationRuntime
dr--   WLDFRuntime
dr--   WTCRuntime
dr--   WebServerRuntimes
dr--   WorkManagerRuntimes
dr--   WseeClusterFrontEndRuntime
dr--   WseeWsrmRuntime

-r--   ActivationTime
-r--   AdminServer
-r--   AdminServerHost
-r--   AdminServerListenPort
-r--   AdminServerListenPortSecure
-r--   AdministrationPort
-r--   AdministrationPortEnabled
-r--   AdministrationURL
-r--   AsyncReplicationRuntime
-r--   ClusterRuntime
-r--   CurrentDirectory
-rw-   CurrentMachine
-r--   DefaultExecuteQueueRuntime
-r--   DefaultURL
-r--   EntityCacheCumulativeRuntime
-r--   EntityCacheCurrentStateRuntime
-r--   EntityCacheHistoricalRuntime
-r--   HealthState
-r--   HealthStateJMX
-r--   JoltRuntime
-r--   ListenAddress
-r--   ListenPort
-r--   ListenPortEnabled
-r--   MANAsyncReplicationRuntime
-r--   MANReplicationRuntime
-r--   MessagingBridgeRuntime
-r--   MiddlewareHome
-r--   Name
-r--   OpenSocketsCurrentCount
-r--   OracleHome
-r--   OverallHealthState
-r--   OverallHealthStateJMX
-rw-   Parent
-r--   PathServiceRuntime
-r--   RestartRequired
-r--   RestartsTotalCount
-r--   SSLListenAddress
-r--   SSLListenPort
-r--   SSLListenPortEnabled
-r--   ServerClasspath
-r--   SocketsOpenedTotalCount
-r--   State
-r--   StateVal
-r--   Type
-r--   WANReplicationRuntime
-r--   WeblogicHome
-r--   WeblogicVersion
-r--   WseeClusterFrontEndRuntime
</code>```

Body:
I have an Singleton Service deployed to a Weblogic cluster, i'd like to know the provider url (listen address and port) of the server on which the singleton service is deployed from the singleton itself (server side, not logs).

I found this (old) article from Oracle, and wrote this method to construct the provider url.

private static String getCurrentServerUrl() throws NamingException {
    weblogic.management.MBeanHome home =
        (weblogic.management.MBeanHome) new Environment().getInitialContext().lookup(weblogic.management.MBeanHome.LOCAL_JNDI_NAME);

    Set mbeanSet = home.getMBeansByType("ServerRuntime");
    Iterator mbeanIterator = mbeanSet.iterator();

    while (mbeanIterator.hasNext()) {
        ServerRuntimeMBean serverRuntime = (ServerRuntimeMBean) mbeanIterator.next();
        if (serverRuntime.getState().equals(ServerStates.RUNNING)) {
            return serverRuntime.getURL("t3");
        }
    }

    return null;
}

The problem is that this code is deprecated (see MBeanHome, MBeanHome#getMBeansByType(String) and MBeanHome#LOCAL_JNDI_NAME).

What is the non-deprecated way to do this?

PS : I don't want to enter any address (whether it is the address for the server or the address for a JMX service since the application is designed to be migratable from server to server withtout recompile or reconfigure of the app it self).

Thanks for your help.

Body:
You can lookup the runtime JMX which is the same for all application. No need to enter address, user or password.

1) Lookup the MBeanServer

InitialContext ctx = new InitialContext();
MBeanServer mBeanServer = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");

2) Then you need to retrieve the name of the server running the application. Here there is two ways (maybe more).

The simplest

String serverName = System.getProperty("weblogic.Name");

But I don't know if it's a reliable way.

The other way to get the server name is to look for it in the runtime service attributes.

ObjectName serviceObjectName = new ObjectName("com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
String serverName = (String) mBeanServer.getAttribute(serviceObjectName, "ServerName");

3) Now we can create the runtime server ObjectName ...

ObjectName serverRuntime = new ObjectName("com.bea:Name="+serverName+",Type=ServerRuntime");

4) ... and get the attributes we need

String listenAddress = mBeanServer.getAttribute(serverRuntime, "ListenAddress");
Integer listenPort = mBeanServer.getAttribute(serverRuntime, "ListenPort");

rem: listenAddress is formatted as hostname/IP, you have to manipulate it to only get IP or host

From there you can access to a lot of information; like the address of the admin server that manage the runtime server, the runtime cluster, ... .

Here is a list I get from the WLST console (WL12.2.1), didn't test if we have access to all attributes/MBean's.

dr--   ApplicationRuntimes
dr--   AsyncReplicationRuntime
dr--   BatchJobRepositoryRuntime
dr--   ClassLoaderRuntime
dr--   ClusterRuntime
dr--   ConcurrentManagedObjectsRuntime
dr--   ConnectorServiceRuntime
dr--   DefaultExecuteQueueRuntime
dr--   EntityCacheCumulativeRuntime
dr--   EntityCacheCurrentStateRuntime
dr--   EntityCacheHistoricalRuntime
dr--   ExecuteQueueRuntimes
dr--   JDBCServiceRuntime
dr--   JMSRuntime
dr--   JTARuntime
dr--   JVMRuntime
dr--   JoltRuntime
dr--   LibraryRuntimes
dr--   LogBroadcasterRuntime
dr--   LogRuntime
dr--   MANAsyncReplicationRuntime
dr--   MANReplicationRuntime
dr--   MailSessionRuntimes
dr--   MaxThreadsConstraintRuntimes
dr--   MessagingBridgeRuntime
dr--   MessagingBridgeRuntimes
dr--   MinThreadsConstraintRuntimes
dr--   PartitionRuntimes
dr--   PathServiceRuntime
dr--   PathServiceRuntimes
dr--   PersistentStoreRuntimes
dr--   RequestClassRuntimes
dr--   SAFRuntime
dr--   SNMPAgentRuntime
dr--   ServerChannelRuntimes
dr--   ServerLogRuntime
dr--   ServerSecurityRuntime
dr--   ServerServices
dr--   SingleSignOnServicesRuntime
dr--   ThreadPoolRuntime
dr--   TimerRuntime
dr--   WANReplicationRuntime
dr--   WLDFRuntime
dr--   WTCRuntime
dr--   WebServerRuntimes
dr--   WorkManagerRuntimes
dr--   WseeClusterFrontEndRuntime
dr--   WseeWsrmRuntime

-r--   ActivationTime
-r--   AdminServer
-r--   AdminServerHost
-r--   AdminServerListenPort
-r--   AdminServerListenPortSecure
-r--   AdministrationPort
-r--   AdministrationPortEnabled
-r--   AdministrationURL
-r--   AsyncReplicationRuntime
-r--   ClusterRuntime
-r--   CurrentDirectory
-rw-   CurrentMachine
-r--   DefaultExecuteQueueRuntime
-r--   DefaultURL
-r--   EntityCacheCumulativeRuntime
-r--   EntityCacheCurrentStateRuntime
-r--   EntityCacheHistoricalRuntime
-r--   HealthState
-r--   HealthStateJMX
-r--   JoltRuntime
-r--   ListenAddress
-r--   ListenPort
-r--   ListenPortEnabled
-r--   MANAsyncReplicationRuntime
-r--   MANReplicationRuntime
-r--   MessagingBridgeRuntime
-r--   MiddlewareHome
-r--   Name
-r--   OpenSocketsCurrentCount
-r--   OracleHome
-r--   OverallHealthState
-r--   OverallHealthStateJMX
-rw-   Parent
-r--   PathServiceRuntime
-r--   RestartRequired
-r--   RestartsTotalCount
-r--   SSLListenAddress
-r--   SSLListenPort
-r--   SSLListenPortEnabled
-r--   ServerClasspath
-r--   SocketsOpenedTotalCount
-r--   State
-r--   StateVal
-r--   Type
-r--   WANReplicationRuntime
-r--   WeblogicHome
-r--   WeblogicVersion
-r--   WseeClusterFrontEndRuntime


问:
Why //= (defined-or) does not work in same way for array as for scalar?
I have the following code:

```<code>$var //= 1;
@arr //= qw/ 1 2 3 /;
</code>```

But I get error:

Can't modify array dereference in defined or assignment (//=) at ...

Even this @arr ||= qw/ 1 2 3 /; does not work:

Can't modify array dereference in logical or assignment (||=) at ...

But this works as expected:

```<code>@arr = @arr || qw/ 1 2 3 /;

print "@arr"; # 1 2 3
</code>```

答:
Array and hash variables can never be undefined, only empty. If I write @arr = undef then @arr becomes a one-element array containing a single undefined scalar. That isn't an undefined array

This expression

```<code>@arr //= qw/ 1 2 3 /
</code>```

imposes scalar context on both operands. scalar(qw/ 1 2 3 /) is 3, while scalar @arr is the number of elements in @arr which cannot be assigned to and can never be undefined anyway

To set an empty array use this

```<code>@arr = qw/ 1 2 3 / unless @arr
</code>```

You could also use a conditional expression

```<code>@arr = @arr ? @arr : qw/ 1 2 3 /
</code>```

Body:
I have the following code:

$var //= 1;
@arr //= qw/ 1 2 3 /;

But I get error:

Can't modify array dereference in defined or assignment (//=) at ...

Even this @arr ||= qw/ 1 2 3 /; does not work:

Can't modify array dereference in logical or assignment (||=) at ...

But this works as expected:

@arr = @arr || qw/ 1 2 3 /;

print "@arr"; # 1 2 3

Body:
Array and hash variables can never be undefined, only empty. If I write @arr = undef then @arr becomes a one-element array containing a single undefined scalar. That isn't an undefined array

This expression

@arr //= qw/ 1 2 3 /

imposes scalar context on both operands. scalar(qw/ 1 2 3 /) is 3, while scalar @arr is the number of elements in @arr which cannot be assigned to and can never be undefined anyway

To set an empty array use this

@arr = qw/ 1 2 3 / unless @arr

You could also use a conditional expression

@arr = @arr ? @arr : qw/ 1 2 3 /


问:
php running calendar within two weeks
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

```<code><!DOCTYPE html>
<html>
<head>
<title>Running calendar</title>
</head>
<body>
<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "<div id=container>";
echo "<table width=100% class=calendar>";
echo "<tr><th colspan=32 id=title>$title $year</th></tr>";
echo "<tr><th>Employee</th>";
$day_num=1;
while($day_num <= $days_in_month){
echo "<th align=center ";
if($day == $day_num){echo "id=day";}
echo ">$day_num</th>";
$day_num++;
}
echo "</tr>";
echo "</table>";
echo "</div>";
?>
</body>
</html>
</code>```

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

答:
I used for loop and DateTime and came up with this:

```<code><?php
for ($i = 14; $i > 0; $i--) {
  echo ' '. DateTime::createFromFormat('U', time())
    ->modify('-' . $i . ' days')
    ->format('d');
}

echo PHP_EOL;
$now = new DateTime();
echo $now->format('d');
echo PHP_EOL;

for ($i = 1; $i <= 14; $i++) {
  echo ' '. DateTime::createFromFormat('U', time())
    ->modify('+' . $i . ' days')
    ->format('d');
}
</code>```

Output:

```<code> 21 22 23 24 25 26 27 28 29 30 01 02 03 04
05
 06 07 08 09 10 11 12 13 14 15 16 17 18 19
</code>```

Demo: https://eval.in/828059

You can change the values in the DateTime::format to give more info, e.g. ->format('d/m') could also print the month.

Hope this helps.

Title: php running calendar within two weeks

Body:
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

<!DOCTYPE html>

<title>Running calendar</title>

<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "
";
echo "
";
echo "
$title $year
";
echo "
Employee	";
$day_num=1;
while($day_num <= $days_in_month){
echo "$day_num	";
$day_num++;
}
echo "
";
echo "
";
echo "
";
?>

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

Body:
I used for loop and DateTime and came up with this:

<?php
for ($i = 14; $i > 0; $i--) {
  echo ' '. DateTime::createFromFormat('U', time())
    ->modify('-' . $i . ' days')
    ->format('d');
}

echo PHP_EOL;
$now = new DateTime();
echo $now->format('d');
echo PHP_EOL;

for ($i = 1; $i <= 14; $i++) {
  echo ' '. DateTime::createFromFormat('U', time())
    ->modify('+' . $i . ' days')
    ->format('d');
}

Output:

 21 22 23 24 25 26 27 28 29 30 01 02 03 04
05
 06 07 08 09 10 11 12 13 14 15 16 17 18 19

Demo: https://eval.in/828059

You can change the values in the DateTime::format to give more info, e.g. ->format('d/m') could also print the month.

Hope this helps.


问:
PHP silex Formbuilder and object with array of object
I am using PHP with the Silex framework and after some hours trying to find a satisfying solution I am still blocked with the following problem regarding forms and objects containing array of Objects. The hours spent permitted me to find a working solution but I hope there is a better way to do that with Silex.

In my application I have a User class that is defined like :

```<code>class User implements UserInterface
{
    private $id;
    private $username;
    private $displayname;
    private $capacities;
    //...
}
</code>```

$capacities variable contains an array of objects from another class (Capacity). A Capacity is a specific role in my app with various information (label, place of the capacity ...) and I have added, in that Capacity class a boolean telling if the Capacity is active for a specific user, when attached to a user via the $capacities array.

At the moment I am able to create the form that looks as I want with the following code :

```<code>use Planning\Domain\User;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($builder->getData()->getCapacities() as $id => $capacity) {
            $choices[$capacity->getLabel()] = $capacity->getId();
            if ($capacity->getActive()) {
                $choicesActive[] = $capacity->getId();
            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,

        ));
    }

    public function getName()
    {
        return 'capacity';
    }
}
</code>```

but the User object I am getting after the form is validated contains for capacities :

```<code>[capacities:Planning\Domain\User:private] => Array
    (
        [0] => 2
        [1] => 4
        [2] => 1
    )
</code>```

capacities variable contains the list of values for checkboxes that have been checked in the form. The issue is that my User object is not consistant with its definition which says that the capacities property should be an array of Capacity objects. What I am doing at the moment is that I have added the following code to my controller when $userForm->isSubmitted() and $userForm->isValid() :

```<code>// Getting the array from the returned user, should contain Capacity object but just contains the IDs.
$capacitiesChecked = $userForm->getData()->getCapacities();
// We regenerate the full array of capacities for this user
$user->setCapacities($app["dao.capacity"]->findAll());

// Then we will activate capacities that have been checked, one by one
foreach ($capacitiesChecked as $capacityChecked) {
    $user->getCapacityById($capacityChecked)->setActive(True);
}
</code>```

This is working and I am happy with it but being new to Silex and the framework world, I am surprized that I have not been able to find an easier way to answer my problem which I believe should be quite common.

I might be missing something from the Silex/Symfony philosophy and I hope someone there will be able to point me to the correct place to get more information or find a solution!

Edit following @dbrumann answer

As it might not be clear how my data is organized, here are the tables in my database :

user

id

username

displayname

capacity

id

label

place

user_capacity

id_user

id_capacity

There might be an issue with the modeling of my project but I have a Capacity class and a User class and User has an attribute with an array containing all the Capacity available in the database and each one of this Capacity object has an active attribute that is set to True if there is an entry in the table user_capacity that links user and capacity. What I would like is ONE form that allows me to properly update data into tables user and user_capacity.

答:
If I understand correctly Capacity is another entity that you want to link. In that case you could use the more specific EntityType and then filter the number of values by using the query_builder attribute as described in the documentation:

```<code>$builder->add('users', EntityType::class, array(
    'class' => Capacity::class,
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('capacity')
            ->where('capacity.active = 1')
            ->orderBy('capacity.id', 'ASC');
    },
    'choice_label' => 'id',
));
</code>```

Body:
I am using PHP with the Silex framework and after some hours trying to find a satisfying solution I am still blocked with the following problem regarding forms and objects containing array of Objects. The hours spent permitted me to find a working solution but I hope there is a better way to do that with Silex.

In my application I have a User class that is defined like :

class User implements UserInterface
{
    private $id;
    private $username;
    private $displayname;
    private $capacities;
    //...
}

$capacities variable contains an array of objects from another class (Capacity). A Capacity is a specific role in my app with various information (label, place of the capacity ...) and I have added, in that Capacity class a boolean telling if the Capacity is active for a specific user, when attached to a user via the $capacities array.

At the moment I am able to create the form that looks as I want with the following code :

use Planning\Domain\User;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class, array(
                    'required'    => true,
                    'label' => "Login (pour Jean Durant → jdurant)"
                    ))
            ->add('displayname', TextType::class, array(
                    'label' => "Nom à afficher"
                ));

        $choices = array();
        $choicesActive = array();
        foreach ($builder->getData()->getCapacities() as $id => $capacity) {
            $choices[$capacity->getLabel()] = $capacity->getId();
            if ($capacity->getActive()) {
                $choicesActive[] = $capacity->getId();
            }
        }

        $builder->add('capacities', ChoiceType::class, array(
            'choices' => $choices,
            'data' => $choicesActive,
            'label' => "Groupes",
            'multiple' => True,
            'expanded' => True
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,

        ));
    }

    public function getName()
    {
        return 'capacity';
    }
}

but the User object I am getting after the form is validated contains for capacities :

[capacities:Planning\Domain\User:private] => Array
    (
        [0] => 2
        [1] => 4
        [2] => 1
    )

capacities variable contains the list of values for checkboxes that have been checked in the form. The issue is that my User object is not consistant with its definition which says that the capacities property should be an array of Capacity objects. What I am doing at the moment is that I have added the following code to my controller when $userForm->isSubmitted() and $userForm->isValid() :

// Getting the array from the returned user, should contain Capacity object but just contains the IDs.
$capacitiesChecked = $userForm->getData()->getCapacities();
// We regenerate the full array of capacities for this user
$user->setCapacities($app["dao.capacity"]->findAll());

// Then we will activate capacities that have been checked, one by one
foreach ($capacitiesChecked as $capacityChecked) {
    $user->getCapacityById($capacityChecked)->setActive(True);
}

This is working and I am happy with it but being new to Silex and the framework world, I am surprized that I have not been able to find an easier way to answer my problem which I believe should be quite common.

I might be missing something from the Silex/Symfony philosophy and I hope someone there will be able to point me to the correct place to get more information or find a solution!

Edit following @dbrumann answer

As it might not be clear how my data is organized, here are the tables in my database :

user

id

username

displayname

capacity

id

label

place

user_capacity

id_user

id_capacity

There might be an issue with the modeling of my project but I have a Capacity class and a User class and User has an attribute with an array containing all the Capacity available in the database and each one of this Capacity object has an active attribute that is set to True if there is an entry in the table user_capacity that links user and capacity. What I would like is ONE form that allows me to properly update data into tables user and user_capacity.

Body:
If I understand correctly Capacity is another entity that you want to link. In that case you could use the more specific EntityType and then filter the number of values by using the query_builder attribute as described in the documentation:

$builder->add('users', EntityType::class, array(
    'class' => Capacity::class,
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('capacity')
            ->where('capacity.active = 1')
            ->orderBy('capacity.id', 'ASC');
    },
    'choice_label' => 'id',
));


答:
Nothing wrong with your code, that is the same of writing this:

```<code>if (a == 0) {
    puts("0");
} else {
    switch (a) {
        case 1: puts("1"); break;
        case 2: puts("2"); break;
        default: puts("default"); break;
    }
}
</code>```

That is perfectly legit. else switch is not a real statement.

Your statement is

```<code>if(condition){code block} else {code block}
</code>```

code block can contain any statement, such as your switch statement.

Title: If ... else switch ... statement

Body:
Following code compiles on my gcc 5.4.0, doesn't generate any warnings and works fine:

if (a == 0) {
    puts("0");
} else switch (a) {
    case 1: puts("1"); break;
    case 2: puts("2"); break;
    default: puts("default"); break;
}

Is if ... else switch ... correct statement?

Body:
Nothing wrong with your code, that is the same of writing this:

if (a == 0) {
    puts("0");
} else {
    switch (a) {
        case 1: puts("1"); break;
        case 2: puts("2"); break;
        default: puts("default"); break;
    }
}

That is perfectly legit. else switch is not a real statement.

Your statement is

if(condition){code block} else {code block}

code block can contain any statement, such as your switch statement.


问:
How to send data from Arduino-uno using Bluetooth module HC-05 and read it in Android?
I am able to send data from my Android phone to my Arduino Uno using the HC-05 module. I also want to send data from the Arduino to my Android phone and I'm unable to do that.

Question: I will send a number from 0-9 using my android app to my Arduino Uno, the Arduino will send back the same number to my app, in words. For now, I am able to send numbers/letters to my Arduino from my app. I want help with the second part of the problem.

This is, in fact, a perfect duplicate of this question Android - receive bluetooth data from Arduino, but, unfortunately, this remains unanswered.

答:
for receiving data from the arduino

```<code>UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
     //Defining a Callback which triggers whenever data is read.
        @Override
        public void onReceivedData(byte[] arg0) {
            String data = null;
            try {
                data = new String(arg0, "UTF-8");
                data.concat("/n");
                tvAppend(textView, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    };
</code>```

and to send data from the arduino

```<code>serialPort.write(string.getBytes());
</code>```

check the full tutorial

Body:
for receiving data from the arduino

UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
     //Defining a Callback which triggers whenever data is read.
        @Override
        public void onReceivedData(byte[] arg0) {
            String data = null;
            try {
                data = new String(arg0, "UTF-8");
                data.concat("/n");
                tvAppend(textView, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    };

and to send data from the arduino

serialPort.write(string.getBytes());

check the full tutorial


问:
Playing sound on BlackBerry gives an error
I'm having trouble getting a short MP3 file to play in a very small app I'm writing to learn how to develop for the BlackBerry.

Because I'm a newbie at BlackBerry development, I've uploaded my Eclipse project for the app to http://stroke.sampablokuper.com/stroke.zip because I don't know if the problem's with my Java programming, or the way I've laid out the resources in my project, or something else.

It's a very small project - only one Java file & three media files - so please help me by seeing if you can run it without errors in the Curve 8520 simulator on your computer. (It's designed for the 8520, because that's the phone a friend of mine has; I don't have a BB myself - yet!)

The idea is that when the user presses/scrolls "down" on the trackball/pad, a sound will be played, but currently instead of the sound, I just get an error message: javax.microedition.media.MediaException .

I've tried to debug this, but as I say, I'm a total newbie to BB development, so I don't really know how to make sense of the information I get from the breakpoints I've set.

Please can you tell me where I've gone wrong?

I really want to finish this before Christmas; please help!

Thanks in advance :)

EDIT: here's the relevant portion of the code, stripped down as much as possible:

```<code>public boolean navigationMovement(int dx, int dy, int status, int time) {
    if (dx == 0 && dy == 1)// DOWN
    {
        makeNoise("growl");
    }
    return true;
}

private void makeNoise(String action) {
    if (action == "growl") {
        Dialog.alert("GROWL");
        try
        {
            Player p = javax.microedition.media.Manager.createPlayer("growl.mp3");
            p.realize();
            VolumeControl volume = (VolumeControl)p.getControl("VolumeControl");
            volume.setLevel(30);
            p.prefetch();
            p.start();

        }
        catch(MediaException me)
        {
            Dialog.alert(me.toString());
        }
        catch(IOException ioe)
        {
            Dialog.alert(ioe.toString());
        }
    }
    invalidate();
}
</code>```

Further edit I've removed the link to download the project, since the problem did indeed appear to be with the code, and is now solved anyway.

答:
The problem turned out to be that the string passed to the .createPlayer method needs to be a URI.

I tried many variations along the lines file:///growl.mp3 before eventually giving up (if anyone knows the correct URI syntax for pointing to a file within a BlackBerry App, please comment!) and settling on this:

```<code>InputStream is = getClass().getResourceAsStream("growl.mp3");
Player p = javax.microedition.media.Manager.createPlayer(is,"audio/mp3");
</code>```

It's a bit crufty by comparison, but at least it works!

ContentLicense: CC BY-SA 2.5

Body:
I'm having trouble getting a short MP3 file to play in a very small app I'm writing to learn how to develop for the BlackBerry.

Because I'm a newbie at BlackBerry development, I've uploaded my Eclipse project for the app to http://stroke.sampablokuper.com/stroke.zip because I don't know if the problem's with my Java programming, or the way I've laid out the resources in my project, or something else.

It's a very small project - only one Java file & three media files - so please help me by seeing if you can run it without errors in the Curve 8520 simulator on your computer. (It's designed for the 8520, because that's the phone a friend of mine has; I don't have a BB myself - yet!)

The idea is that when the user presses/scrolls "down" on the trackball/pad, a sound will be played, but currently instead of the sound, I just get an error message: javax.microedition.media.MediaException .

I've tried to debug this, but as I say, I'm a total newbie to BB development, so I don't really know how to make sense of the information I get from the breakpoints I've set.

Please can you tell me where I've gone wrong?

I really want to finish this before Christmas; please help!

Thanks in advance :)

EDIT: here's the relevant portion of the code, stripped down as much as possible:

public boolean navigationMovement(int dx, int dy, int status, int time) {
    if (dx == 0 && dy == 1)// DOWN
    {
        makeNoise("growl");
    }
    return true;
}

private void makeNoise(String action) {
    if (action == "growl") {
        Dialog.alert("GROWL");
        try
        {
            Player p = javax.microedition.media.Manager.createPlayer("growl.mp3");
            p.realize();
            VolumeControl volume = (VolumeControl)p.getControl("VolumeControl");
            volume.setLevel(30);
            p.prefetch();
            p.start();

        }
        catch(MediaException me)
        {
            Dialog.alert(me.toString());
        }
        catch(IOException ioe)
        {
            Dialog.alert(ioe.toString());
        }
    }
    invalidate();
}

Further edit I've removed the link to download the project, since the problem did indeed appear to be with the code, and is now solved anyway.

Body:
The problem turned out to be that the string passed to the .createPlayer method needs to be a URI.

I tried many variations along the lines file:///growl.mp3 before eventually giving up (if anyone knows the correct URI syntax for pointing to a file within a BlackBerry App, please comment!) and settling on this:

InputStream is = getClass().getResourceAsStream("growl.mp3");
Player p = javax.microedition.media.Manager.createPlayer(is,"audio/mp3");

It's a bit crufty by comparison, but at least it works!


答:
What you have is syntactically correct... but it does not make easy reading.

You will likely be pulled up on it if your code is being reviewed - because you're making use of an "un-braced, multi-line statement as part of a conditional".

Prefer to be explicit and write it like so:

```<code>if (a == 0) {
    puts("0");
} else {
    switch (a) {
        case 1: puts("1"); break;
        case 2: puts("2"); break;
        default: puts("default"); break;
    }
}
</code>```

It is legal in the same way that the following is legal:

```<code>if (a == 0)
    puts("0");
else
    puts("not0");
</code>```

Such constructs can lead to mistakes when re-visiting the code... I seem to remember that one of the recent "popular" vulnerabilities was implemented (by mistake... hopefully) in part due to this "un-braced" use of if.

Title: If ... else switch ... statement

Body:
What you have is syntactically correct... but it does not make easy reading.

You will likely be pulled up on it if your code is being reviewed - because you're making use of an "un-braced, multi-line statement as part of a conditional".

Prefer to be explicit and write it like so:

if (a == 0) {
    puts("0");
} else {
    switch (a) {
        case 1: puts("1"); break;
        case 2: puts("2"); break;
        default: puts("default"); break;
    }
}

It is legal in the same way that the following is legal:

if (a == 0)
    puts("0");
else
    puts("not0");

Such constructs can lead to mistakes when re-visiting the code... I seem to remember that one of the recent "popular" vulnerabilities was implemented (by mistake... hopefully) in part due to this "un-braced" use of if.


问:
Get Common values in an single array
I want to get common values in an single array. Below I have shared my code for your reference

```<code>    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $pack = array();
    foreach($itemsVisible as $key => $item) {
       $productid = $item->getProductId();
       $select = "SELECT `pay4later_package` FROM `pay4later_payment` where `product_id`=".$productid;
       $query = $connection->fetchall($select);
       $pack[] = array_column($query, 'pay4later_package');
    }
    $paypack = call_user_func_array('array_merge', $pack);
</code>```

Output:

```<code>$paypack = {ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%),ONIF12: 12 Months Interest Free Credit (0%)}
</code>```

Above output have two common values (i.e) ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%).

How to get those two common values in an array?

答:
You can get duplicate value from array please check bellow example code..
   php array function array_unique and array_diff_assoc use for this

```<code>$main_arr = array('test','none','abc','test','none'); //here duplicate value
$unique_arr = array_unique($main_arr);
$duplicate_record = array_diff_assoc($main_arr, $unique_arr);//get difference
print_r($duplicate_record);
</code>```

check output like this:

```<code>Array
(
    [1] => test
    [5] => none
)
</code>```

Title: Get Common values in an single array

Body:
I want to get common values in an single array. Below I have shared my code for your reference

    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $pack = array();
    foreach($itemsVisible as $key => $item) {
       $productid = $item->getProductId();
       $select = "SELECT `pay4later_package` FROM `pay4later_payment` where `product_id`=".$productid;
       $query = $connection->fetchall($select);
       $pack[] = array_column($query, 'pay4later_package');
    }
    $paypack = call_user_func_array('array_merge', $pack);

Output:

$paypack = {ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%),ONIF12: 12 Months Interest Free Credit (0%)}

Above output have two common values (i.e) ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%).

How to get those two common values in an array?

Body:
You can get duplicate value from array please check bellow example code..
   php array function array_unique and array_diff_assoc use for this

$main_arr = array('test','none','abc','test','none'); //here duplicate value
$unique_arr = array_unique($main_arr);
$duplicate_record = array_diff_assoc($main_arr, $unique_arr);//get difference
print_r($duplicate_record);

check output like this:

Array
(
    [1] => test
    [5] => none
)


问:
create a lzma file in python
i need to create a lzma file with the existing .tar file and another metadata file to further create a zip file.</p>

答: if you can use python 3.3 and later, you could use the built-in lzma module</p>

Title: create a lzma file in python


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
Switch can be optimized by compiler - you will get faster code.

Also I find it to be more elegant when dealing with enumerable types.

To sum up switch statement gives you performance + code elegance :)

Here are some useful links:

speed comparison of switch vs if/else in C#

Feedback-Guided Switch Statement
Optimization (pdf describing switch statement optimization)

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

OwnerDisplayName: aku

LastEditorDisplayName: aku


问:
How to check a clicked button's second class?
If I have two button, one with an apple class and the other with an apple and and orange class:

```<code><button class="apple"/>
<button class="apple orange"/>
</code>```

In my button click event for an apple button, how can I tell if the clicked button also has an orange class?

```<code>$("button.apple").click(function(event)
{
 var hasOrange = // ???
}
</code>```

答:
jQuery provides .hasClass() just for this purpose:

```<code>$("button.apple").click(function(event)
{
 var hasOrange = $(this).hasClass('orange');
}
</code>```

Body:
If I have two button, one with an apple class and the other with an apple and and orange class:

<button class="apple"/>
<button class="apple orange"/>

In my button click event for an apple button, how can I tell if the clicked button also has an orange class?

$("button.apple").click(function(event)
{
 var hasOrange = // ???
}

Body:
jQuery provides .hasClass() just for this purpose:

$("button.apple").click(function(event)
{
 var hasOrange = $(this).hasClass('orange');
}


问:
wkhtmltopdf breaking line with negative values
I am using wkhtmltopdf on a Ubuntu server. The problem I have been facing is that negative big numbers break lines. I saw this thread: Prevent Breaking of Negative Numbers. My values are read directly from the database, and differently from this guy I don't add a hyphen.

Negative numbers:

Positive:

This is after I upgraded to version wkhtmltopdf 0.12.2.1 (with patched qt). On version 0.9.9, which I had been using I had no problem with PDF generation. I upgraded because in Django, Views which inherited the PDF class from django-wkhtmltopdf would give an error code 1, not generating PDF.

PDFs are generated through command line:

```<code>command = 'xvfb-run wkhtmltopdf --footer-right "[page]/[topage]" {s} {o}'.format(
            s=html_file.name,
            o=target.name
        )
</code>```

I tried to add --zoom 0.5 as a parameter to that command, but only made the PDF worse. Half of the text got cut out off the page and can't be read.

答:
Just create a CSS rule, that says, the text should not wrap.</p>

```<code>td.no-wrap {
  white-space: nowrap;
}
</code>```

Body:
I am using wkhtmltopdf on a Ubuntu server. The problem I have been facing is that negative big numbers break lines. I saw this thread: Prevent Breaking of Negative Numbers. My values are read directly from the database, and differently from this guy I don't add a hyphen.

Negative numbers:

Positive:

This is after I upgraded to version wkhtmltopdf 0.12.2.1 (with patched qt). On version 0.9.9, which I had been using I had no problem with PDF generation. I upgraded because in Django, Views which inherited the PDF class from django-wkhtmltopdf would give an error code 1, not generating PDF.

PDFs are generated through command line:

command = 'xvfb-run wkhtmltopdf --footer-right "[page]/[topage]" {s} {o}'.format(
            s=html_file.name,
            o=target.name
        )

I tried to add --zoom 0.5 as a parameter to that command, but only made the PDF worse. Half of the text got cut out off the page and can't be read.

Body:
Just create a CSS rule, that says, the text should not wrap.

td.no-wrap {
  white-space: nowrap;
}


问:
Make an array of my model with an auto-increment
I have a Model and I want make an array of this. The problem is I do it like this :

My code :

```<code>final WifiModel itemsData[] = {
                new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
        };
</code>```

And I would like to do a i++ form to i=4 for example.
How can I do that ?

My Model :

```<code>public class WifiModel {

    private String SSID;
    private String name;

    public String getName() {
        return name;
    }

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

    WifiModel(String SSID, String name) {
        this.SSID = SSID;
        this.name = name;
    }

    public String getSSID() {
        return SSID;
    }

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

答:
try this :</p>

```<code>List<WifiModel> list = new ArrayList<>();
WifiModel wifi=null;
int i;
for(i=0; i<4; i++){
    wifi = new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
    list.add(wifi);
}
</code>```

Body:
I have a Model and I want make an array of this. The problem is I do it like this :

My code :

final WifiModel itemsData[] = {
                new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
        };

And I would like to do a i++ form to i=4 for example.
How can I do that ?

My Model :

public class WifiModel {

    private String SSID;
    private String name;

    public String getName() {
        return name;
    }

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

    WifiModel(String SSID, String name) {
        this.SSID = SSID;
        this.name = name;
    }

    public String getSSID() {
        return SSID;
    }

    public void setSSID(String SSID) {
        this.SSID = SSID;
    }
}

Body:
try this :

List<WifiModel> list = new ArrayList<>();
WifiModel wifi=null;
int i;
for(i=0; i<4; i++){
    wifi = new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
    list.add(wifi);
}


问:
Deduplication of Dataframe returning empty object
I have 2 csv files with similar columns. I am reading and concatenating them with the following code:

```<code>One = pd.read_csv("/Users/xxx/Documents/Domains/Malaysia - MAR.csv" )
Two = pd.read_csv("/Users/xxx/Documents/Domains/Malaysia - CR.csv" )

links_webtrends_my = pd.concat([One,Two])

links_webtrends_my = links_webtrends_my['Page']

links_webtrends_my = links_webtrends_my.to_frame(name='Page')
</code>```

I then use this line to drop duplicates

```<code>links_webtrends_my = links_webtrends_my.drop_duplicates(keep='first', inplace=True)
</code>```

When I do this, it deletes everthing in it. When I call links_webtrends_my afterwards, it doesnt return anything. I will appreciate guidance on this.

答:
When using inplace=True the return object is NoneType.  Remove the assignment back to the variable when using inplace=True.

```<code>links_webtrends_my.drop_duplicates(keep='first', inplace=True)
</code>```

OR remove the inplace=True parameter.

```<code>links_webtrends_my = links_webtrends_my.drop_duplicates(keep='first')
</code>```

Body:
I have 2 csv files with similar columns. I am reading and concatenating them with the following code:

One = pd.read_csv("/Users/xxx/Documents/Domains/Malaysia - MAR.csv" )
Two = pd.read_csv("/Users/xxx/Documents/Domains/Malaysia - CR.csv" )

links_webtrends_my = pd.concat([One,Two])

links_webtrends_my = links_webtrends_my['Page']

links_webtrends_my = links_webtrends_my.to_frame(name='Page')

I then use this line to drop duplicates

links_webtrends_my = links_webtrends_my.drop_duplicates(keep='first', inplace=True)

When I do this, it deletes everthing in it. When I call links_webtrends_my afterwards, it doesnt return anything. I will appreciate guidance on this.

Body:
When using inplace=True the return object is NoneType.  Remove the assignment back to the variable when using inplace=True.

links_webtrends_my.drop_duplicates(keep='first', inplace=True)

OR remove the inplace=True parameter.

links_webtrends_my = links_webtrends_my.drop_duplicates(keep='first')


问:
how to ignore dir-prop-base in .svn folder?
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

```<code>Apps\.svn\dir-prop-base
Apps\.svn\entries
</code>```

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

```<code>syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*
</code>```

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.

答:
```<code>syntax: regexp
^.*\.svn/dir-prop-base$
</code>```

works for me.

Body:
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

Apps\.svn\dir-prop-base
Apps\.svn\entries

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.

Body:
syntax: regexp
^.*\.svn/dir-prop-base$

works for me.


问:
What's the difference in TWIG between using the attribute() function and using brackets
I'm trying to understand twigs attribute() function, because it seems to me that this

```<code>attribute(object, parameter)
</code>```

and this

```<code>object[ parameter ]
</code>```

Would do the same thing. They return the value of that parameter in the object. I realize that brackets can also be used to get a value from an array with an index, but if the parameter is a string it seems to get the value from the parameter just as well. What else does attribute() do that Im missing?

答:
The attribute function can also be used to call methods of objects and enables you to pass arguments towards it

```<code>{{ attribute(object, method, arguments) }}
</code>```

Body:
I'm trying to understand twigs attribute() function, because it seems to me that this

attribute(object, parameter)

and this

object[ parameter ]

Would do the same thing. They return the value of that parameter in the object. I realize that brackets can also be used to get a value from an array with an index, but if the parameter is a string it seems to get the value from the parameter just as well. What else does attribute() do that Im missing?

Body:
The attribute function can also be used to call methods of objects and enables you to pass arguments towards it

{{ attribute(object, method, arguments) }}


问:
Spring Integration - Error Channel - Getting the original message
Is there any way to get the original message in the error channel. All I am able to get the Message of Exception type. I need to get the original message and log it.

Highly appreciate your help. Thanks!

答:
The ErrorMessage payload is a MessagingException.

The exception has two properties cause and failedMessage which is the message at the time of the failure.


问:
Can't reach metadata in viewmodel in my view
I would like to use metadata in my view but my model(ToDoTable) is packed in viewmodel(ModelsViewList) and I don't know how to reach the model.The @foreach (var property in ViewData.ModelMetadata.Properties) doesn't work :(.

Model:

```<code>public partial class ToDoTable
        {
            [HiddenInput(DisplayValue = false)]
            public int ID { get; set; }

            [Required(ErrorMessage = "Please write name of event.")]
            public string EventName { get; set; }

            [MaxLength(50, ErrorMessage = "Description must be shorter than 50 characters ")]
            [Required(ErrorMessage = "Proszę podać opis.")]
            public string Description { get; set; }

            [Display(Name = "Tu wpisz format daty")]
            [DataType(DataType.Date, ErrorMessage = "Date mast be in format described")]
            public string Data { get; set; }
        }
</code>```

Controller:

```<code> using System.Web.Mvc;
        using ToDoLibrary.Abstract;
        using ToDoUI.ModelsViews;

        namespace ToDoUI.Controllers
        {
            public class HomeController : Controller
            {
                IToDoRepository repository;
               public HomeController(IToDoRepository rep)
               {
                    repository = rep;
               }
                public ViewResult List()
                {
                    ToDoLibrary.ToDoTable model = new ToDoLibrary.ToDoTable();
                    ModelsViewList modelView = new ModelsViewList()
                    {
                        FromRepository = repository.FromRepository,
                        ModelDB = model
                    };
                   return View(modelView);
                }

           }`
       }
</code>```

View:

```<code>@model ToDoUI.ModelsViews.ModelsViewList
    @{
        ViewBag.Title = "List";
    }
    <div class="row">
        <div class="col-lg-6 main tile1 col-lg-push-6">
            pierwsza kolumna

            @using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <div class="panel-body">

                    @foreach (var property in ViewData.ModelMetadata.Properties)
                    {
                        switch (property.PropertyName)
                        {
                            case "ID":

                                break;
                            default:
                                <div class="form-group">
                                    <label>@(property.DisplayName ?? property.PropertyName)</label>
                                    @if (property.PropertyName == "Description")
                                {
                                        @Html.TextArea(property.PropertyName, null, new { @class = "form-control", rows = 5 })
                                    }
                                    else
                                    {
                                        @Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
                                    }
                                    @Html.ValidationMessage(property.PropertyName)
                                </div>
                                break;
                        }
                    }
                </div>
                <div class="panel-footer">
                    <input type="submit" value="Zapisz" class="btn btn-primary" />
                    @Html.ActionLink("Anuluj i wróć do listy", "Index", null, new
               {
                   @class = "btn btn-default"
               })
                </div>
            }
         </div>
    </div>
</code>```

答: You can't. However, the problem is not one of how to get the metadata from the entity class, but rather instead, that the entity class should not have this metadata in the first place. These annotations belong on your view model. The entity class should only have things that matter to the database, not your view.</p>

Body:
I would like to use metadata in my view but my model(ToDoTable) is packed in viewmodel(ModelsViewList) and I don't know how to reach the model.The @foreach (var property in ViewData.ModelMetadata.Properties) doesn't work :(.

Model:

public partial class ToDoTable
        {
            [HiddenInput(DisplayValue = false)]
            public int ID { get; set; }

            [Required(ErrorMessage = "Please write name of event.")]
            public string EventName { get; set; }

            [MaxLength(50, ErrorMessage = "Description must be shorter than 50 characters ")]
            [Required(ErrorMessage = "Proszę podać opis.")]
            public string Description { get; set; }

            [Display(Name = "Tu wpisz format daty")]
            [DataType(DataType.Date, ErrorMessage = "Date mast be in format described")]
            public string Data { get; set; }
        }

Controller:

 using System.Web.Mvc;
        using ToDoLibrary.Abstract;
        using ToDoUI.ModelsViews;

        namespace ToDoUI.Controllers
        {
            public class HomeController : Controller
            {
                IToDoRepository repository;
               public HomeController(IToDoRepository rep)
               {
                    repository = rep;
               }
                public ViewResult List()
                {
                    ToDoLibrary.ToDoTable model = new ToDoLibrary.ToDoTable();
                    ModelsViewList modelView = new ModelsViewList()
                    {
                        FromRepository = repository.FromRepository,
                        ModelDB = model
                    };
                   return View(modelView);
                }

           }`
       }

View:

@model ToDoUI.ModelsViews.ModelsViewList
    @{
        ViewBag.Title = "List";
    }

            pierwsza kolumna

            @using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {

                    @foreach (var property in ViewData.ModelMetadata.Properties)
                    {
                        switch (property.PropertyName)
                        {
                            case "ID":

                                break;
                            default:

                                    @(property.DisplayName ?? property.PropertyName)
                                    @if (property.PropertyName == "Description")
                                {
                                        @Html.TextArea(property.PropertyName, null, new { @class = "form-control", rows = 5 })
                                    }
                                    else
                                    {
                                        @Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
                                    }
                                    @Html.ValidationMessage(property.PropertyName)

                                break;
                        }
                    }

                    <input type="submit" value="Zapisz" class="btn btn-primary" />
                    @Html.ActionLink("Anuluj i wróć do listy", "Index", null, new
               {
                   @class = "btn btn-default"
               })

            }


问:
c# ZFrame data extraction
I need help to understand ZFrames. Using ZeroMq with clrzmq4 binding for c#, I create a frame from a string. Then I get the string from frame and I get an empty string. Something so simple as

```<code>public Form1()
{
    InitializeComponent();

    ZMessage msg = new ZMessage();
    msg.Add(new ZFrame("AABBCCDD"));
    textBox1.Text = msg.PopString();
}
</code>```

what do I missed?

Thanks in advance

Edited:
I can get the content with

```<code>List<ZFrame> l = msg.ToList();
byte[] by = l[0].Read();
char[] cby = new char[by.Length + 1];
for (int a = 0; a < by.Length; a++)
    cby[a] = (char)by[a];
textBox1.Text = new string(cby);
</code>```

I cant understand why?

答:
I would say this is a bug in clrzmq4: https://github.com/zeromq/clrzmq4/issues/110

As a workaround, if you rewind the stream in between yourself using Position = 0, it works, i.e.

```<code>var frame = new ZFrame("AABBCCDD");
frame.Position = 0;
var msg = new ZMessage {frame};
Assert.AreEqual("AABBCCDD", msg.PopString());
</code>```

Title: c# ZFrame data extraction

Body:
I need help to understand ZFrames. Using ZeroMq with clrzmq4 binding for c#, I create a frame from a string. Then I get the string from frame and I get an empty string. Something so simple as

public Form1()
{
    InitializeComponent();

    ZMessage msg = new ZMessage();
    msg.Add(new ZFrame("AABBCCDD"));
    textBox1.Text = msg.PopString();
}

what do I missed?

Thanks in advance

Edited:
I can get the content with

List<ZFrame> l = msg.ToList();
byte[] by = l[0].Read();
char[] cby = new char[by.Length + 1];
for (int a = 0; a < by.Length; a++)
    cby[a] = (char)by[a];
textBox1.Text = new string(cby);

I cant understand why?

Body:
I would say this is a bug in clrzmq4: https://github.com/zeromq/clrzmq4/issues/110

As a workaround, if you rewind the stream in between yourself using Position = 0, it works, i.e.

var frame = new ZFrame("AABBCCDD");
frame.Position = 0;
var msg = new ZMessage {frame};
Assert.AreEqual("AABBCCDD", msg.PopString());


问:
How to render charts properly when using Bootstrap Carousel and Chartkick?
The idea is to use a carousel and instead of placing images as their content, to use charts (in this case using Chartkick). When the page loads for the first time, the chart that appears on the very first container renders without any issues. However, when I change containers on the Carousel, the other charts appear very small and not at the right position. I've noticed that when I manually resize the webpage, the chart loads correctly and the other ones inherit the problem, so I assume this is due to a rendering protocol of the Carousel that is not on track with what I was expecting. Is there any way to force a page resize when clicking a button on the Carousel? Or is it another way to solve that problem?
Thank you in advance. </p>

答:
I managed to solve the issue the way I was thinking of initially.
Here is the code in case someone has that same problem:

Javascript:

```<code><script>

      $(document).ready(function(){
          $("#myCarousel").carousel();

          // Enable Carousel Indicators
          $(".item1").click(function(){
              $("#myCarousel").carousel(0);

              // The next line of code triggers the listeners for the page-resizing
              // event, which includes the carousel and will display the chart
              // correctly.

              window.dispatchEvent(new Event('resize'));

          });
          $(".item2").click(function(){
              $("#myCarousel").carousel(1);
              window.dispatchEvent(new Event('resize'));
          });

      });

</script>
</code>```

HTML:

```<code><ol class="carousel-indicators carousel-indicators-numbers">
  <li class="item1 active">1</li>
  <li class="item2"       >2</li>
</ol>
</code>```

Body:
I managed to solve the issue the way I was thinking of initially.
Here is the code in case someone has that same problem:

Javascript:

<script>

      $(document).ready(function(){
          $("#myCarousel").carousel();

          // Enable Carousel Indicators
          $(".item1").click(function(){
              $("#myCarousel").carousel(0);

              // The next line of code triggers the listeners for the page-resizing
              // event, which includes the carousel and will display the chart
              // correctly.

              window.dispatchEvent(new Event('resize'));

          });
          $(".item2").click(function(){
              $("#myCarousel").carousel(1);
              window.dispatchEvent(new Event('resize'));
          });

      });

</script>

HTML:

<ol class="carousel-indicators carousel-indicators-numbers">
  <li class="item1 active">1</li>
  <li class="item2"       >2</li>
</ol>


问:
Reach field in invoice report
I need to extend invoice report with field note. but I'm getting error that field does not exist. I'm stuck and don't know how to reach that field. did tried with partner_id.note too but also getting error.

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <template id="report_invoice_document" inherit_id="account.report_invoice_document">
            <xpath expr="//div[@class='page']/*[last()]" position="after">

                            Note

        </xpath>
        </template>
    </data>
</openerp>
```

<pre class="lang-py prettyprint-override"><code>class AccountInvoiceTax(models.Model):
    _inherit = 'account.invoice.tax'

    note = fields.Text(related='tax_id.note', string='Note')
</code>```

QWebException: "'account.invoice' object has no attribute 'note'" while evaluating 'o.note'

答: You have extended the model account.invoice.tax and not account.invoice. The error message is correct. So either you extend invoice or you have to use note from the invoice tax lines (tax_line_ids).

Title: Reach field in invoice report

Body:
I need to extend invoice report with field note. but I'm getting error that field does not exist. I'm stuck and don't know how to reach that field. did tried with partner_id.note too but also getting error.

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <template id="report_invoice_document" inherit_id="account.report_invoice_document">
            <xpath expr="//div[@class='page']/*[last()]" position="after">

                            Note

        </xpath>
        </template>
    </data>
</openerp>

class AccountInvoiceTax(models.Model):
    _inherit = 'account.invoice.tax'

    note = fields.Text(related='tax_id.note', string='Note')

QWebException: "'account.invoice' object has no attribute 'note'" while evaluating 'o.note'


问:
how to override STL container function
It's possible, that override some function stl container with the same paremeters?
I want override exactly push_back with some if inside function.
I try but, always have error/information about that function is in vector.

答:
Inheritance for STL containers is bad approach. The vector is not supposed to have derived classes. There are no virtual method in the vector and virtual destructor ( the last one could make a lot of problems ).
You can create your own class and use vector as member. </p>

Title: how to override STL container function


问:
xml + xpath, print element
```<code>Notice: Undefined property: DOMNodeList::$id in D:\wamp\www\xml\index.php on line 15
id:

Notice: Undefined property: DOMNodeList::$name in D:\wamp\www\xml\index.php on line 16
name:

<?php
$xml = new DOMDocument();

$xml->load('test.xml');

$xpath = new DOMXPath($xml);

$query = '/people/person[id="33333"]';

$entries = $xpath->query($query);

echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';
?>
</code>```

xml file sample:

```<code><people>
...
    <person>
        <phone>33333</phone>
        <name>Aadgar</name>
        <last_name>Adas</last_name>
    </person>
...
</people>
</code>```

答:
you got the xpath wrong. 33333 is phone not id.

try

```<code>$query = '/people/person[phone="33333"]';
</code>```

Also

their is no id

```<code>echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';
</code>```

try removeing the id part

Title: xml + xpath, print element

Body:
Notice: Undefined property: DOMNodeList::$id in D:\wamp\www\xml\index.php on line 15
id:

Notice: Undefined property: DOMNodeList::$name in D:\wamp\www\xml\index.php on line 16
name:

<?php
$xml = new DOMDocument();

$xml->load('test.xml');

$xpath = new DOMXPath($xml);

$query = '/people/person[id="33333"]';

$entries = $xpath->query($query);

echo 'id:'. $entries->id.'
';
echo 'name:'.$entries->name.'
';
?>

xml file sample:

<people>
...
    <person>
        <phone>33333</phone>
        <name>Aadgar</name>
        <last_name>Adas</last_name>
    </person>
...
</people>

Body:
you got the xpath wrong. 33333 is phone not id.

try

$query = '/people/person[phone="33333"]';

Also

their is no id

echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';

try removeing the id part


问:
Dependency Mismatch: Solution won't use anything newer than 4.0.0.0
When I try to run the solution, I'll get an error: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

System.Net.Http version 4.0.0 is always in use. I have tried to update, downgrade and god knows what for hours now. Nothing I've tried works.

This is my project.json:

```<code>{
  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.2",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.2",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.2",
    "Microsoft.Extensions.Configuration.Json": "1.1.2",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.2",
    "Microsoft.Extensions.Logging": "1.1.2",
    "Microsoft.Extensions.Logging.Console": "1.1.2",
    "Microsoft.Extensions.Logging.Debug": "1.1.2",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.2",
    "Microsoft.ServiceFabric": "5.6.220",
    "Microsoft.ServiceFabric.AspNetCore.WebListener": "2.6.220",
    "Microsoft.ServiceFabric.Data": "2.6.220",
    "Microsoft.ServiceFabric.Services": "2.6.220",
    "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.1",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.1",
    "microsoft.aspnetcore.authentication.jwtbearer": "1.1.1",
    "System.Net.Http": "4.3.2"
  },

  "tools": {
  },

  "frameworks": {
    "net461": {}

  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
  }
}
</code>```

In there I have written "System.Net.Http": "4.3.2", but as you can see in this image, the reference version is 4.0.0:

What am I doing wrong and how can I fix it? I'm getting a bit confused. I declare 4.3.2, the reference is 4.0.0 and the error says 4.1.1? I have searched everywhere for version 4.1.1, but didn't find anything.

Edit:
I'm using VS 2015 on a windows 7 machine.

I have also tried to redirect to the correct assembly version in the config json file with no success.

答:
Reference the latest version of System.Net.Http and add to your app.config bindingRedirect like that:

```<code><runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.1.0" />
       </dependentAssembly>
       <!-- Other possible redirects... -->
    </assemblyBinding>
 </runtime>
</code>```

Please adjust the version and other values in my redirect if needed.

At least that's how it worked before, may be in .Net Core something changed, in that case, you at least have an idea of what to do now.

Body:
When I try to run the solution, I'll get an error: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

System.Net.Http version 4.0.0 is always in use. I have tried to update, downgrade and god knows what for hours now. Nothing I've tried works.

This is my project.json:

{
  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.2",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.2",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.2",
    "Microsoft.Extensions.Configuration.Json": "1.1.2",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.2",
    "Microsoft.Extensions.Logging": "1.1.2",
    "Microsoft.Extensions.Logging.Console": "1.1.2",
    "Microsoft.Extensions.Logging.Debug": "1.1.2",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.2",
    "Microsoft.ServiceFabric": "5.6.220",
    "Microsoft.ServiceFabric.AspNetCore.WebListener": "2.6.220",
    "Microsoft.ServiceFabric.Data": "2.6.220",
    "Microsoft.ServiceFabric.Services": "2.6.220",
    "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.1",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.1",
    "microsoft.aspnetcore.authentication.jwtbearer": "1.1.1",
    "System.Net.Http": "4.3.2"
  },

  "tools": {
  },

  "frameworks": {
    "net461": {}

  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
  }
}

In there I have written "System.Net.Http": "4.3.2", but as you can see in this image, the reference version is 4.0.0:

What am I doing wrong and how can I fix it? I'm getting a bit confused. I declare 4.3.2, the reference is 4.0.0 and the error says 4.1.1? I have searched everywhere for version 4.1.1, but didn't find anything.

Edit:
I'm using VS 2015 on a windows 7 machine.

I have also tried to redirect to the correct assembly version in the config json file with no success.

Body:
Reference the latest version of System.Net.Http and add to your app.config bindingRedirect like that:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.1.0" />
       </dependentAssembly>
       <!-- Other possible redirects... -->
    </assemblyBinding>
 </runtime>

Please adjust the version and other values in my redirect if needed.

At least that's how it worked before, may be in .Net Core something changed, in that case, you at least have an idea of what to do now.