问:
EJB 3.0 lookup in Weblogic 10.3.0
1: Our application runs on Weblogic Application Server,version 10.3.0

2: In our system,we need to deploy an EJB conforming to the EJB 3.0 specification.

Please find the sample code for our UAT environment as below :

```<code>/*The remote interface*/

package com.serverside.ejb.session;
import javax.ejb.Remote;

@Remote
public interface ASimpleSessionBeanRemote {

 public void printThis(String print);

}

/*The bean class*/

package com.serverside.ejb.session;

import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class ASimpleSessionBean
 */
@Stateless(name="ASimpleSessionBean", **mappedName = "ASimpleSessionEJB"**)
@Remote(ASimpleSessionBeanRemote.class)
public class ASimpleSessionBean implements ASimpleSessionBeanRemote {

    /**
     * Default constructor.
     */
    public ASimpleSessionBean() {
        // TODO Auto-generated constructor stub
    }

 @Override
 public void printThis(String print) {
  // TODO Auto-generated method stub
  System.out.println("ASimpleSessionBean : "+print);
 }

}
</code>```

3: The above files when packaged in jar get deployed on the server successfully.

4: As per EJB 3.0 specification,the deployement descriptors are not mandatory.Hence,the jar doesn't include ejb-jar.xml and weblogic-ejb-jar.xml

5: Please find below,the EJB3.0 annotations reference as per the Weblogic Application Server Documentation :

```<code>Annotation : @Stateless

Package: javax.ejb.Stateless

Attribute : mappedName

Description :

Specifies the product-specific name to which the stateless session bean should be mapped.
You can also use this attribute to specify the JNDI name of this stateless session bean. WebLogic Server uses the value of the mappedName attribute when creating the bean’s global JNDI name. In particular, the JNDI name will be:
mappedName#name_of_businessInterface
where name_of_businessInterface is the fully qualified name of the business interface of this session bean.
For example, if you specify mappedName="bank" and the fully qualified name of the business interface is com.CheckingAccount, then the JNDI of the business interface is bank#com.CheckingAccount.
</code>```

6: Conforming to the above specification, the sample EJB deployed on our application server has the binding name(as reflected in the jndi tree) as follows :

ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSessionBeanRemote

A jndi lookup using this name succeeds :

```<code>InitialContext.doLookup("ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSesionBeanRemote");
</code>```

7: Now,we want the binding name to be a simple string i.e the lookup must be something like :

InitialContext.doLookup("ASimpleSessionEJB");

8: To implement point-7,we tried using the ejb-jar.xml and weblogic-ejb-jar.xml as follows(Sorry,couldn't figure out how to attach/render xml files):

9: Inspite of the point-8,the binding name remains as follows :

```<code>ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSessionBeanRemote
</code>```

10: Please guide us about the solution and implementation to attend point-7.

Thanks !

答:
Can you somehow paste your weblogic-ejb.xml? Atleast name element.

Can you also specify where you running this lookup code?
I hope it's running inside the web container else you won't see the weblogic-ejb.xml. :)

If nothing helps why don't you just create a properties file where you can specify your key and a long remote name and then just use that key to lookup?

Cheers.

JS

Title: EJB 3.0 lookup in Weblogic 10.3.0

Body:
1: Our application runs on Weblogic Application Server,version 10.3.0

2: In our system,we need to deploy an EJB conforming to the EJB 3.0 specification.

Please find the sample code for our UAT environment as below :

/*The remote interface*/

package com.serverside.ejb.session;
import javax.ejb.Remote;

@Remote
public interface ASimpleSessionBeanRemote {

 public void printThis(String print);

}

/*The bean class*/

package com.serverside.ejb.session;

import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class ASimpleSessionBean
 */
@Stateless(name="ASimpleSessionBean", **mappedName = "ASimpleSessionEJB"**)
@Remote(ASimpleSessionBeanRemote.class)
public class ASimpleSessionBean implements ASimpleSessionBeanRemote {

    /**
     * Default constructor.
     */
    public ASimpleSessionBean() {
        // TODO Auto-generated constructor stub
    }

 @Override
 public void printThis(String print) {
  // TODO Auto-generated method stub
  System.out.println("ASimpleSessionBean : "+print);
 }

}

3: The above files when packaged in jar get deployed on the server successfully.

4: As per EJB 3.0 specification,the deployement descriptors are not mandatory.Hence,the jar doesn't include ejb-jar.xml and weblogic-ejb-jar.xml

5: Please find below,the EJB3.0 annotations reference as per the Weblogic Application Server Documentation :

Annotation : @Stateless

Package: javax.ejb.Stateless

Attribute : mappedName

Description :

Specifies the product-specific name to which the stateless session bean should be mapped.
You can also use this attribute to specify the JNDI name of this stateless session bean. WebLogic Server uses the value of the mappedName attribute when creating the bean’s global JNDI name. In particular, the JNDI name will be:
mappedName#name_of_businessInterface
where name_of_businessInterface is the fully qualified name of the business interface of this session bean.
For example, if you specify mappedName="bank" and the fully qualified name of the business interface is com.CheckingAccount, then the JNDI of the business interface is bank#com.CheckingAccount.

6: Conforming to the above specification, the sample EJB deployed on our application server has the binding name(as reflected in the jndi tree) as follows :

ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSessionBeanRemote

A jndi lookup using this name succeeds :

InitialContext.doLookup("ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSesionBeanRemote");

7: Now,we want the binding name to be a simple string i.e the lookup must be something like :

InitialContext.doLookup("ASimpleSessionEJB");

8: To implement point-7,we tried using the ejb-jar.xml and weblogic-ejb-jar.xml as follows(Sorry,couldn't figure out how to attach/render xml files):

9: Inspite of the point-8,the binding name remains as follows :

ASimpleSessionEJB#com.serverside.ejb.session.ASimpleSessionBeanRemote

10: Please guide us about the solution and implementation to attend point-7.

Thanks !


来源: stackexchange

问:
Nightwatch not navigating to url
I have the following code and whats happening is that once the promise is resolved the browser doesn't navigate to the url it just stay on the default page defined on the nightwatch.conf.js. So the test fails.  </p>

```<code>Given(/^I make a post request and retreive the Id i got the page + id$/, () => {
      //I make the post request
      var transactionIdPromise = utils.getTransactionId(1);

      return transactionIdPromise.getBody('utf8').then(JSON.parse).done(function (result) {
          var id = result.transaction_id;
          var url = "https://mywebpage.com:8443/" + id;
          client.url(url)
      });
    });
</code>```

答: My solution was changing the done for a then on the promise, even though I´'m still unsure on why this worked.</p>

ContentLicense: CC BY-SA 3.0

Title: Nightwatch not navigating to url

Body:
I have the following code and whats happening is that once the promise is resolved the browser doesn't navigate to the url it just stay on the default page defined on the nightwatch.conf.js. So the test fails.

Given(/^I make a post request and retreive the Id i got the page + id$/, () => {
      //I make the post request
      var transactionIdPromise = utils.getTransactionId(1);

      return transactionIdPromise.getBody('utf8').then(JSON.parse).done(function (result) {
          var id = result.transaction_id;
          var url = "https://mywebpage.com:8443/" + id;
          client.url(url)
      });
    });


问:
Spyder :An error ocurred while starting the kernel
I am still getting this error: An error occurred while starting the kernel

Things I tried:

setuptools command

updating spyder

Uninstalled everything that had word python in it from Uninstall or change progam panel

Uninstalling and reinstalling anaconda

Reading people's response on how they tried to fix it

Tried not to get frustrated.

This started occurring after I updated the spyder which I shouldn't have, but now I am stuck with the issue. I will share the complete message that's coming up on my IPhython Console screen.

Traceback (most recent call last):
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 245, in
main()
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 213, in main
from ipykernel.kernelapp import IPKernelApp
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\__init__.py", line 2, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\connect.py", line 18, in
import jupyter_client
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\__init__.py", line 4, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\connect.py", line 22, in
import zmq
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\__init__.py", line 34, in
from zmq import backend
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 40, in
reraise(*exc_info)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\utils\sixcerpt.py", line 34, in reraise
raise value
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 27, in
_ns = select_backend(first)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\cython\__init__.py", line 6, in
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'
Traceback (most recent call last):
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 245, in
main()
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 213, in main
from ipykernel.kernelapp import IPKernelApp
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\__init__.py", line 2, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\connect.py", line 18, in
import jupyter_client
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\__init__.py", line 4, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\connect.py", line 22, in
import zmq
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\__init__.py", line 34, in
from zmq import backend
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 40, in
reraise(*exc_info)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\utils\sixcerpt.py", line 34, in reraise
raise value
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 27, in
_ns = select_backend(first)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\cython\__init__.py", line 6, in
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'
Traceback (most recent call last):
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 245, in
main()
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 213, in main
from ipykernel.kernelapp import IPKernelApp
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\__init__.py", line 2, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\connect.py", line 18, in
import jupyter_client
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\__init__.py", line 4, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\connect.py", line 22, in
import zmq
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\__init__.py", line 34, in
from zmq import backend
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 40, in
reraise(*exc_info)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\utils\sixcerpt.py", line 34, in reraise
raise value
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 27, in
_ns = select_backend(first)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\cython\__init__.py", line 6, in
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'
Traceback (most recent call last):
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 245, in
main()
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 213, in main
from ipykernel.kernelapp import IPKernelApp
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\__init__.py", line 2, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\connect.py", line 18, in
import jupyter_client
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\__init__.py", line 4, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\connect.py", line 22, in
import zmq
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\__init__.py", line 34, in
from zmq import backend
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 40, in
reraise(*exc_info)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\utils\sixcerpt.py", line 34, in reraise
raise value
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 27, in
_ns = select_backend(first)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\cython\__init__.py", line 6, in
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'
Traceback (most recent call last):
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 245, in
main()
File "C:\Users\afsan\Anaconda3\lib\site‑packages\spyder\utils\ipython\start_kernel.py", line 213, in main
from ipykernel.kernelapp import IPKernelApp
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\__init__.py", line 2, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\ipykernel\connect.py", line 18, in
import jupyter_client
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\__init__.py", line 4, in
from .connect import *
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\jupyter_client\connect.py", line 22, in
import zmq
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\__init__.py", line 34, in
from zmq import backend
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 40, in
reraise(*exc_info)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\utils\sixcerpt.py", line 34, in reraise
raise value
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\__init__.py", line 27, in
_ns = select_backend(first)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "C:\Users\afsan\AppData\Local\Programs\Python\Python36\Lib\site‑packages\zmq\backend\cython\__init__.py", line 6, in
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'

答:
The problem is that you have two Python versions installed:

C:\Users\afsan\Anaconda3\

C:\Users\afsan\AppData\Local\Programs\Python\Python36

Given that it seems you want to use Spyder with Anaconda, please remove your second Python version (manually, if necessary). That should fix your problem.


问:
parameterize testing with django settings
Am working on a django reusable package that am planning to use with multiple project. I've used pytest to build test suite, I've used parametrized helped in pytest to run a single test with multiple configuration.

Yet, I would like to run all my tests using different settings combinations

```<code>available_backends = [
    'django_profile.auth_backends.drf.RestFramework',
    'django_profile.auth_backends.kong.Kong',
]

def pytest_generate_tests(metafunc):
    # if 'stringinput' in metafunc.fixturenames:
    if 'auth_backend' in metafunc.fixturenames:
        metafunc.parametrize(
            'auth_backend',
            available_backends
        )

@pytest.fixture(params=['auth_backend', ])
def auth_backend(request, settings):
    settings.DJANGO_PROFILE_AUTH_BACKEND = request.auth_backend
    return settings
</code>```

I experimented with the above approach, but this also means I have to add auth_backend to each test case, I don't believe this is ideal. Any one can recommend a way for me to run all my tests using different setting combinations?

Regards

答:
Eventually, I found a way to pass different settings to all tests without having to specify the fixture in each test. Below is a working example </p>

```<code># conftest.py
@pytest.yield_fixture(params=available_backends)
def settings(request, settings):
    if request.param not in available_backends:
        raise ValueError('auth_backend {} not implemented.'.format(request.param))
    wrapper = SettingsWrapper()
    settings.DJANGO_PROFILE_AUTH_BACKEND = request.param
    yield wrapper
    wrapper.finalize()

# setup.cfg
usefixtures = settings
</code>```

Body:
Am working on a django reusable package that am planning to use with multiple project. I've used pytest to build test suite, I've used parametrized helped in pytest to run a single test with multiple configuration.

Yet, I would like to run all my tests using different settings combinations

available_backends = [
    'django_profile.auth_backends.drf.RestFramework',
    'django_profile.auth_backends.kong.Kong',
]

def pytest_generate_tests(metafunc):
    # if 'stringinput' in metafunc.fixturenames:
    if 'auth_backend' in metafunc.fixturenames:
        metafunc.parametrize(
            'auth_backend',
            available_backends
        )

@pytest.fixture(params=['auth_backend', ])
def auth_backend(request, settings):
    settings.DJANGO_PROFILE_AUTH_BACKEND = request.auth_backend
    return settings

I experimented with the above approach, but this also means I have to add auth_backend to each test case, I don't believe this is ideal. Any one can recommend a way for me to run all my tests using different setting combinations?

Regards

Body:
Eventually, I found a way to pass different settings to all tests without having to specify the fixture in each test. Below is a working example

# conftest.py
@pytest.yield_fixture(params=available_backends)
def settings(request, settings):
    if request.param not in available_backends:
        raise ValueError('auth_backend {} not implemented.'.format(request.param))
    wrapper = SettingsWrapper()
    settings.DJANGO_PROFILE_AUTH_BACKEND = request.param
    yield wrapper
    wrapper.finalize()

# setup.cfg
usefixtures = settings


问:
Avoid __init__ and super boilerplate when inheriting
Say I have the following classes:

```<code>class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    # the method I would like to avoid
    def __init__(self, **kwargs):
        super(Child, self).__init__(**kwargs)
</code>```

Is there a way to avoid the boilerplate of calling __init__ and super in the Child class? In this package, users would inherit from the base class very often, but I would like to avoid them using __init__ with super each time, especially since the pattern would never change. it still needs to take in keyword arguments however.

I imagine this is possible using __new__ or a metaclass, but there has to be a simpler method using something like @classmethod in the base class?

EDIT: Using python3

答:
If you don't need specific initialization in the child class, you can omit the __init__:

```<code>class Base:

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):
    pass
</code>```

Otherwise, you should use it this way:

```<code>class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        #...additional specific initialization
</code>```

Body:
Say I have the following classes:

class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    # the method I would like to avoid
    def __init__(self, **kwargs):
        super(Child, self).__init__(**kwargs)

Is there a way to avoid the boilerplate of calling __init__ and super in the Child class? In this package, users would inherit from the base class very often, but I would like to avoid them using __init__ with super each time, especially since the pattern would never change. it still needs to take in keyword arguments however.

I imagine this is possible using __new__ or a metaclass, but there has to be a simpler method using something like @classmethod in the base class?

EDIT: Using python3

Body:
If you don't need specific initialization in the child class, you can omit the __init__:

class Base:

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):
    pass

Otherwise, you should use it this way:

class Base(object):

    def __init__(self, **kwargs):
        # some constructor based on the kwargs
        pass

class Child(Base):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        #...additional specific initialization


问:
JQuery .html() not working
I'm using Onsen UI + JQuery and .html() function is not working, see: https://jsfiddle.net/w8904ztc/1/

```<code><body>
  <ons-page>
    <ons-toolbar>
      <div class="center">Clone</div>
    </ons-toolbar>

    <ons-tabbar swipeable position="auto">
      <ons-tab page="tab1.html" label="Home" icon="ion-home, material:md-home" active>
      </ons-tab>
      <ons-tab page="tab2.html" label="Settings" icon="md-settings">
      </ons-tab>
    </ons-tabbar>
  </ons-page>

  <template id="tab1.html">
    <ons-page id="Tab1">
      <p style="text-align: center;">
        This is the first page.
      </p>
    </ons-page>
  </template>

  <template id="tab2.html">
    <ons-page id="Tab2">
      <div class="center" id="usernamespan"></div>
      <p style="text-align: center;">
        <ons-button id="logout" name="logout" onclick="logout();">Logout</ons-button>
      </p>
    </ons-page>
  </template>
  <script type="text/javascript" src="cordova.js"></script>
  <script>
    function logout() {
      window.localStorage.clear();
      window.location.href = "index.html";
    }
    var username = localStorage.username;
    ons.notification.toast({
      message: 'Willkommen ' + username,
      timeout: 4000
    });

    $('usernamespan').html("Hallo Welt" + username);

  </script>
</body>
</code>```

Also simple JavaScript is not working, tried already .getElementById()

window.document.getElementById("#usernamespan").innerHTML = "Something";

returns => Uncaught TypeError: Cannot set property 'innerHTML' of null

Any Ideas?

答:
You need to specify the target ID as #IDOFDIV or if its a class .CLASSOFID. You also need to tell jquery to wait for the page to finish loading before it tries to find it and add html to it as it may not be on the page yet.

This is done using the $(document).ready() call which is then passed a function with the code you would like to execute after the page has finished loading in.

```<code>  $(document).ready(function(){
   function logout() {
      window.localStorage.clear();
      window.location.href = "index.html";
    }
    var username = localStorage.username;
    ons.notification.toast({
      message: 'Willkommen ' + username,
      timeout: 4000
    });

    $('#usernamespan').html("Hallo Welt" + username);
  })
</code>```

Title: JQuery .html() not working

Body:
I'm using Onsen UI + JQuery and .html() function is not working, see: https://jsfiddle.net/w8904ztc/1/

  <ons-page>
    <ons-toolbar>

Clone

    </ons-toolbar>

    <ons-tabbar swipeable position="auto">
      <ons-tab page="tab1.html" label="Home" icon="ion-home, material:md-home" active>
      </ons-tab>
      <ons-tab page="tab2.html" label="Settings" icon="md-settings">
      </ons-tab>
    </ons-tabbar>
  </ons-page>

  <template id="tab1.html">
    <ons-page id="Tab1">

        This is the first page.

    </ons-page>
  </template>

  <template id="tab2.html">
    <ons-page id="Tab2">

        <ons-button id="logout" name="logout" onclick="logout();">Logout</ons-button>

    </ons-page>
  </template>

Also simple JavaScript is not working, tried already .getElementById()

window.document.getElementById("#usernamespan").innerHTML = "Something";

returns => Uncaught TypeError: Cannot set property 'innerHTML' of null

Any Ideas?

Body:
You need to specify the target ID as #IDOFDIV or if its a class .CLASSOFID. You also need to tell jquery to wait for the page to finish loading before it tries to find it and add html to it as it may not be on the page yet.

This is done using the $(document).ready() call which is then passed a function with the code you would like to execute after the page has finished loading in.

  $(document).ready(function(){
   function logout() {
      window.localStorage.clear();
      window.location.href = "index.html";
    }
    var username = localStorage.username;
    ons.notification.toast({
      message: 'Willkommen ' + username,
      timeout: 4000
    });

    $('#usernamespan').html("Hallo Welt" + username);
  })

ContentLicense: CC BY-SA 4.0


问:
Visual studio equivalent of java System.out
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

```<code>var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);
</code>```

答:
Try:  Console.WriteLine (type out for a Visual Studio or Rider snippet)

```<code>Console.WriteLine(stuff);
</code>```

Another way is to use System.Diagnostics.Debug.WriteLine:

```<code>System.Diagnostics.Debug.WriteLine(stuff);
</code>```

Debug.WriteLine may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine won't be rendered in Output window but only in the Console itself in case of Console Application type.

Another difference is that Debug.WriteLine will not print anything in Release configuration.

Body:
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);

Body:
Try:  Console.WriteLine (type out for a Visual Studio or Rider snippet)

Console.WriteLine(stuff);

Another way is to use System.Diagnostics.Debug.WriteLine:

System.Diagnostics.Debug.WriteLine(stuff);

Debug.WriteLine may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine won't be rendered in Output window but only in the Console itself in case of Console Application type.

Another difference is that Debug.WriteLine will not print anything in Release configuration.


问:
Angular 2 Primeng Datatable- single (exclusive) row selection on click
I am using a Primeng datatable to display editable entries from a database. When a row is clicked, a new component is displayed to allow editing of the associated data for the row. When a new row is clicked, the component will show the data for that row instead, and so on.

Obviously, this is exclusive- only one row can be selected at a time. I want to highlight the currently 'active' row in a different color, so when a new row is selected any previously hightlighted row should be reset to its default color.

At present I have the following in my template:

```<code>  <p-dataTable [value]="rowData" [rowStyleClass]="highlightSelectedRow" [rowHover]="true" (onRowClick)="rowClick($event)">

    <ng-template ngFor let-col [ngForOf]="cols">
        <p-column [field]="col.field" [header]="col.header"></p-column>
    </ng-template>

  </p-dataTable>
</code>```

...and in my component:

```<code>  rowClick($event){
     const rowData = $event.data;
     rowData.selected = !rowData.selected;
  // and do some other stuff...
  }

  highlightSelectedRow(rowData: any, rowIndex: number){
    return (rowData.selected) ? 'selected' : '';
  }
</code>```

...CSS to style selected row:

```<code>.row.selected {
   background-color: red;
}
</code>```

This works insofar as highlighting the clicked row, but highlighted rows remain highlighted, and I'm wondering about the best way to reset them.

I guess I could loop through all the rows of data and find the row with selected property set to true and set it to false, but this seems a rather inefficient way of doing it, especially if I am dealing with many thousands of rows of data.

Am I missing a better, built-in way of doing this with Primeng?

答:
This works insofar as highlighting the clicked row, but highlighted rows remain highlighted, and I'm wondering about the best way to reset them.

Create a class for unselected row such as

```<code>.row.unselected {
   background-color: white;
}
</code>```

and affect this class whenever you unselect a row

```<code>highlightSelectedRow(rowData: any, rowIndex: number){
    return (rowData.selected) ? 'selected' : 'unselected';
}
</code>```

See this simular SO question or Plunker for more details.

Body:
I am using a Primeng datatable to display editable entries from a database. When a row is clicked, a new component is displayed to allow editing of the associated data for the row. When a new row is clicked, the component will show the data for that row instead, and so on.

Obviously, this is exclusive- only one row can be selected at a time. I want to highlight the currently 'active' row in a different color, so when a new row is selected any previously hightlighted row should be reset to its default color.

At present I have the following in my template:

    <ng-template ngFor let-col [ngForOf]="cols">

    </ng-template>

...and in my component:

  rowClick($event){
     const rowData = $event.data;
     rowData.selected = !rowData.selected;
  // and do some other stuff...
  }

  highlightSelectedRow(rowData: any, rowIndex: number){
    return (rowData.selected) ? 'selected' : '';
  }

...CSS to style selected row:

.row.selected {
   background-color: red;
}

This works insofar as highlighting the clicked row, but highlighted rows remain highlighted, and I'm wondering about the best way to reset them.

I guess I could loop through all the rows of data and find the row with selected property set to true and set it to false, but this seems a rather inefficient way of doing it, especially if I am dealing with many thousands of rows of data.

Am I missing a better, built-in way of doing this with Primeng?

Body:
This works insofar as highlighting the clicked row, but highlighted rows remain highlighted, and I'm wondering about the best way to reset them.

Create a class for unselected row such as

.row.unselected {
   background-color: white;
}

and affect this class whenever you unselect a row

highlightSelectedRow(rowData: any, rowIndex: number){
    return (rowData.selected) ? 'selected' : 'unselected';
}

See this simular SO question or Plunker for more details.


问:
Cannot access variable from one function to another function in same class
I have a class and I am defining a variable

```<code>namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //I am assigning a new value to clientinfo variable
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
}
</code>```

Now, in the same class, I want to use this new assigned value to $clientinfo variable, in another function complete()

```<code>namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //The value stored to clientinfo should be accessed from complete function
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
    //I want to retrieve the value stored to clientinfo in this function
    public function complete()
    {
        return $this->clientinfo;
    }
}
</code>```

When I call complete() function I get null value, while I am supposed to get $clientinfo value from the validateClient function.

I am calling the validateClient function in a separate class like this

```<code>class bookAppointment
{

    public function validate()
    {
        $business = new BoldSystem();
        $validate = $business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
    }

    public function book()
    {
        $business = new BoldSystem();
        //this returns null
        $book = $business->complete();
    }
}
</code>```

答:
Seems like you are creating 2 different instances (in validate and book method of bookAppointment class)! So it should be clear to you, why complete() returns null ;) Maybe you should use a class property for $business.

Not knowing much about your system, you could possibly inject an instance of BoldSystem into the constructor of bookAppointment like this:

```<code>class bookAppointment {

    public $business;

    public function __construct(BoldSystem $boldSystem)
    {
        $this->business = $boldSystem;
    }

    public function validate()
    {
        $validate = $this->business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
        // ... you further code
    }

    public function book()
    {
        // ...
        $book = $this->business->complete();
        // ...
    }
}
</code>```

It is just an example for holding an instance of BoldSystem in bookAppointment. Another option would be creating setter/getter methods in bookAppointment for the Boldsystem property.

Body:
I have a class and I am defining a variable

namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //I am assigning a new value to clientinfo variable
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
}

Now, in the same class, I want to use this new assigned value to $clientinfo variable, in another function complete()

namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //The value stored to clientinfo should be accessed from complete function
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
    //I want to retrieve the value stored to clientinfo in this function
    public function complete()
    {
        return $this->clientinfo;
    }
}

When I call complete() function I get null value, while I am supposed to get $clientinfo value from the validateClient function.

I am calling the validateClient function in a separate class like this

class bookAppointment
{

    public function validate()
    {
        $business = new BoldSystem();
        $validate = $business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
    }

    public function book()
    {
        $business = new BoldSystem();
        //this returns null
        $book = $business->complete();
    }
}

Body:
Seems like you are creating 2 different instances (in validate and book method of bookAppointment class)! So it should be clear to you, why complete() returns null ;) Maybe you should use a class property for $business.

Not knowing much about your system, you could possibly inject an instance of BoldSystem into the constructor of bookAppointment like this:

class bookAppointment {

    public $business;

    public function __construct(BoldSystem $boldSystem)
    {
        $this->business = $boldSystem;
    }

    public function validate()
    {
        $validate = $this->business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
        // ... you further code
    }

    public function book()
    {
        // ...
        $book = $this->business->complete();
        // ...
    }
}

It is just an example for holding an instance of BoldSystem in bookAppointment. Another option would be creating setter/getter methods in bookAppointment for the Boldsystem property.


问:
How come div block is moved down when there is enough space?
I have a rather simple problem. For some reason, div.actionBar is moved down even when there should be enough space in the parent div:

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div></code>```

If the widths are subtracted:

venueInfoSection is 960px wide

topVenueSection has 20px padding

mainIconWrapper is 88px wide + 20px margin

primaryInfo is 512px wide

actionBar is 285px wide + 15px margin

So 960-20-20-88-20-512-285-15=0

How come actionBar is moved down even when there should be enough space? It seems to be inlined with the other two blocks only if the width is set to 277px.

答:
When you set display to inline-block certain whitespace in your HTML becomes rendered as spacing between each element.  That whitespace is what is causing your layout to break.

The easiest alternative would be to replace every instance of display: inline-block with float: left though there are innumerable alternatives (ex: See 'Fighting the Space Between Inline Block Elements' https://css-tricks.com/fighting-the-space-between-inline-block-elements/ )

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 float: left;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 float: left;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div></code>```

You could also utilize a Flex grid depending on the level of browser support you need to accommodate.

Body:
I have a rather simple problem. For some reason, div.actionBar is moved down even when there should be enough space in the parent div:

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 display: inline-block;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 display: inline-block;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
}

Title

 Surf Spot

 38 Bourke St

 Save

 Share

If the widths are subtracted:

venueInfoSection is 960px wide

topVenueSection has 20px padding

mainIconWrapper is 88px wide + 20px margin

primaryInfo is 512px wide

actionBar is 285px wide + 15px margin

So 960-20-20-88-20-512-285-15=0

How come actionBar is moved down even when there should be enough space? It seems to be inlined with the other two blocks only if the width is set to 277px.

Body:
When you set display to inline-block certain whitespace in your HTML becomes rendered as spacing between each element.  That whitespace is what is causing your layout to break.

The easiest alternative would be to replace every instance of display: inline-block with float: left though there are innumerable alternatives (ex: See 'Fighting the Space Between Inline Block Elements' https://css-tricks.com/fighting-the-space-between-inline-block-elements/ )

.venueInfoSection {
 position: relative;
        width: 960px;
}

.venueInfoSection .topVenueSection {
 line-height: 0;
 padding: 20px;
}

.venueInfoSection .topVenueSection .mainIconWrapper {
 float: left;
 line-height: 0;
 margin-right: 20px;
 max-width: 88px;
 overflow: hidden;
}

.venueInfoSection .topVenueSection .primaryInfo {
 float: left;
 line-height: 20px;
 vertical-align: top;
 width: 512px;
}

.venueInfoSection .actionBar {
 display: inline-block;
 margin: 58px 0 0 15px;
 text-align: right;
 vertical-align: top;
 width: 285px;
  background: yellow;
}

<div class="venueInfoSection">
    <div class="topVenueSection">
        <div class="mainIconWrapper"><img src="images/surfspot_88.png" height="88" width="88">
        </div>
        <div class="primaryInfo">
            <div class="venueNameSection">
                <h1 class="venueName" itemprop="name">Title</h1> </div>
            <div class="categories"> <span class="unlinkedCategory">Surf Spot</span> </div>
            <div class="locationInfo"> <span class="venueCity">38 Bourke St</span> </div>
            <div class="bottomVenueSection"></div>
        </div>
        <div class="actionBar"> <span class="saveAction actionBtn"> <div class="saveButton saveToListAction inactive" title="Save to my saved places!"> <span class="saveAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c2ee53e7d96.png" height="16" width="16"></span><span class="buttonRight unsaved"><span class="label">Save</span></span>
            </span>
        </div>
        </span><span class="shareAction actionBtn"> <div class="doubleShareButton" title="Share this place with friends!"> <span class="shareAction actionBtn"><span class="buttonLeft"><img src="images/button_icon_saveribbon-9c5999c4703e7d96.png" height="16" width="16"></span><span class="buttonRight"><span class="label">Share</span></span>
        </span>
    </div>
    </span>
</div>
</div>
</div>

You could also utilize a Flex grid depending on the level of browser support you need to accommodate.


问:
Remove Empty Fields in Select Statement
I have a select statement as follows:

```<code>SELECT
    firstName,
    lastName,
    CASE
        WHEN primaryEmail <> 'name@example.com' THEN primaryEmail
        WHEN secondaryEmail <> 'name@example.com' THEN secondaryEmail
        ELSE ternaryEmail
    END AS email
FROM participant
WHERE
    primaryEmail <> 'name@example.com'
    OR secondaryEmail <> 'name@example.com'
    OR ternaryEmail <> 'name@example.com'
</code>```

The problem is that there are some records with empty fields, either firstName, lastName, or the resulting email. I added this to the WHERE clause:

```<code>firstName IS NOT NULL
AND lastName IS NOT NULL
AND primaryEmail <> // The already existing WHERE clause code.
</code>```

but those fields still show up. I haven't bothered trying to get rid of the email part yet, so there's no code for me to show there.

答:
This issue is a tricky one in T-SQL. I did find an answer to this question as well as learned exactly how the compiler looks at each "type" of Blank space or NULL.

http://weblogs.sqlteam.com/mladenp/archive/2007/09/06/How_does_SQL_Server_really_store_NULL-s.aspx

Title: Remove Empty Fields in Select Statement

Body:
I have a select statement as follows:

SELECT
    firstName,
    lastName,
    CASE
        WHEN primaryEmail <> 'name@example.com' THEN primaryEmail
        WHEN secondaryEmail <> 'name@example.com' THEN secondaryEmail
        ELSE ternaryEmail
    END AS email
FROM participant
WHERE
    primaryEmail <> 'name@example.com'
    OR secondaryEmail <> 'name@example.com'
    OR ternaryEmail <> 'name@example.com'

The problem is that there are some records with empty fields, either firstName, lastName, or the resulting email. I added this to the WHERE clause:

firstName IS NOT NULL
AND lastName IS NOT NULL
AND primaryEmail <> // The already existing WHERE clause code.

but those fields still show up. I haven't bothered trying to get rid of the email part yet, so there's no code for me to show there.


问:
Open a specific tree
How can I open a specific tree when I select a record of another tree ?

for example if I click on Sales department instead of openning its form I need to open the sales tree (just an example)

答:
You can do some thing like that by adding a button to the tree view. and when you show your data use only tree view without form to force the use to click on the button.

```<code>   <tree>
        <field....>
        <field....>
        <field....>
        <button name="open_other_view" ....>
   </tree>
</code>```

and in your model define a function to open another view :

  @api.mutli
  def open_other_view(self):
      ......
      ......
      ......
      tree_id = self.env.ref('module_name.tree_xml_id').id
      return {
         'type': 'ir.actions.act_window',
         'name': 'title',
         'views': [(tree_id, 'tree'), (False, 'form')],
         ....
         ....
         ....
      }
```

i think this technique is much simple.

Title: Open a specific tree

Body:
You can do some thing like that by adding a button to the tree view. and when you show your data use only tree view without form to force the use to click on the button.

   <tree>
        <field....>
        <field....>
        <field....>
        <button name="open_other_view" ....>
   </tree>

and in your model define a function to open another view :

  @api.mutli
  def open_other_view(self):
      ......
      ......
      ......
      tree_id = self.env.ref('module_name.tree_xml_id').id
      return {
         'type': 'ir.actions.act_window',
         'name': 'title',
         'views': [(tree_id, 'tree'), (False, 'form')],
         ....
         ....
         ....
      }

i think this technique is much simple.


问:
Time complexity for N insert operations in a sorted array
If we have a sorted array containing N elements and we wish to perform N insert operations then what should be the worst case time complexity of the best approach?

I think it should be O(N log(2N)) because we can insert N elements directly at the end of the sorted array. After all the insertions, we will have 2N elements and we can perform a stable sorting algorithm on the whole 2N array which would take O(2N log(2N)) ~ O(N log(2N))

So, in total = N insertions + sorting = O(N + 2N log(2N)) = O(N log(2N))

But everywhere I see related concept it is given as O(N^2) as they are keeping the array sorted after Each insertion by making space for each insertion in between the sorted array!

Is my approach wrong? Do we have to keep the sorted array sorted after each insertion? If yes, then does this "keep the data structure same after each operation rather than making it intact after a whole series of the same operation" Rule valid for all data structures?!

答:
Depends on what you need.

If you need to do some operations after each insert, then O(n^2) is standard (finding the right spot O(lgn) and shifting elements O(n)).

If you don't need to do anything in between insertions, insert all elements at the end and sort in O(nlgn) so that the entire operation takes O(nlgn) (assuming insertion at the end takes O(1) time).

BTW, it will be O(nlg(n)) because O(nlg(2n)) = O(nlgn + nlg(2)) = O(nlgn + n) = O(nlgn)


问:
PHP - define constant inside a class
How can I define a constant inside a class, and make it so it's visible only when called in a class context?

....something like Foo::app()->MYCONSTANT;

(and if called like MYCONSTANT to be ignored)

答:
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public, private or protected).

A work around would be to define your constant as private or protected and then make them readable via a static function. This function should only return the constant values if called from the static context.

You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.

Credits: http://dwellupper.io/post/48/defining-class-constants-in-php

Title: PHP - define constant inside a class


问:
Memory Game doesn't restart after winning
I'm trying to rebrand this cool Memory Game developed by Nate Wiley.

I'm having an issue with it though. When you win, it allows you to restart, but the game become unplayable when the cards re-appear for a second time.

The restart button code calls this function:

```<code>reset: function(){
    this.hideModal();
    this.shuffleCards(this.cardsArray);
    this.setup();
    this.$game.show();
},
</code>```

This correctly hides the modal, shuffles the card, runs the setup function, and shows the game again.

The Setup Function looks like this:

```<code>setup: function(){
    this.html = this.buildHTML();
    this.$game.html(this.html);
    this.$memoryCards = $(".card");
    this.paused = false;
    this.guess = null;
},
</code>```

I'm not getting any errors in the console. How would I go about diagnosing an error in this situation?

I've created a codepen with only 2 matching pairs to make testing a lot quicker but I'm at a loss for how to figure this out.

https://codepen.io/nolaandy/pen/wPeGgo

答:
When you don't have errors in the console you need to think about what you'd expect the code to do and work back from there. In you example, I'd expect the game to do something when I click on the card, but it doesn't so I added a console.log() in the click handler and I noticed that nothing was being logged in the console so I though "probably the card element get's rebuilt from scratch, so it looses it's event listener", so I tried delegating the event to the body, with

```<code>$('body').on("click", ".card", this.cardClicked);
</code>```

and I noticed that now the click event worked, so I knew I was getting somewhere. I still wanted to keep the click code the way it was so I noticed that in the setup function he doesn't call the binding function, which is the one that attaches click events to elements, so I tried calling this.binding(); inside the setup function and sure enough it works.

PS: In my opinion it would make sense to call the buinding() function inside the setup() function, because I probably want my click events to be attached to the buttons every time I set up a game, but I kept it the way it was to leave the code as similar as possible as the original one.

// Memory Game
// © 2014 Nate Wiley
// License -- MIT
// best in full screen, works on phones/tablets (min height for game is 500px..) enjoy ;)
// Follow me on Codepen

(function(){

 var Memory = {

  init: function(cards){
   this.$game = $(".game");
   this.$modal = $(".modal");
   this.$overlay = $(".modal-overlay");
   this.$restartButton = $("button.restart");
   this.cardsArray = $.merge(cards, cards);
   this.shuffleCards(this.cardsArray);
   this.setup();
   this.binding();
  },

  shuffleCards: function(cardsArray){
   this.$cards = $(this.shuffle(this.cardsArray));
  },

  setup: function(){
   this.html = this.buildHTML();
   this.$game.html(this.html);
   this.$memoryCards = $(".card");
   this.binding();
   this.paused = false;
      this.guess = null;
  },

  binding: function(){
   this.$memoryCards.on("click", this.cardClicked);
   $("button.restart").unbind().click( $.proxy(this.reset, this));
  },
  // kinda messy but hey
  cardClicked: function(){
   var _ = Memory;
   var $card = $(this);
   if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
    $card.find(".inside").addClass("picked");
    if(!_.guess){
     _.guess = $(this).attr("data-id");
    } else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
     $(".picked").addClass("matched");
     _.guess = null;
    } else {
     _.guess = null;
     _.paused = true;
     setTimeout(function(){
      $(".picked").removeClass("picked");
      Memory.paused = false;
     }, 600);
    }
    if($(".matched").length == $(".card").length){
     _.win();
    }
   }
  },

  win: function(){
   this.paused = true;
   setTimeout(function(){
    Memory.showModal();
    Memory.$game.fadeOut();
   }, 1000);
  },

  showModal: function(){
   this.$overlay.show();
   this.$modal.fadeIn("slow");
  },

  hideModal: function(){
   this.$overlay.hide();
   this.$modal.hide();
  },

  reset: function(){
   this.hideModal();
   this.shuffleCards(this.cardsArray);
   this.setup();
   this.$game.show();
  },

  // Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
  shuffle: function(array){
   var counter = array.length, temp, index;
     // While there are elements in the array
     while (counter > 0) {
         // Pick a random index
         index = Math.floor(Math.random() * counter);
         // Decrease counter by 1
         counter--;
         // And swap the last element with it
         temp = array[counter];
         array[counter] = array[index];
         array[index] = temp;
      }
      return array;
  },

  buildHTML: function(){
   var frag = '';
   this.$cards.each(function(k, v){
    frag += '

\

\

\

';
   });
   return frag;
  }
 };

 var cards = [
  {
   name: "php",
   img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/php-logo_1.png",
   id: 1,
  },
  {
   name: "css3",
   img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/css3-logo.png",
   id: 2
  },
 ];

 Memory.init(cards);

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
html, body {
  height: 100%;
}
body {
  background: black;
  min-height: 100%;
  font-family: "Arial", sans-serif;
}
.wrap {
  position: relative;
  height: 100%;
  min-height: 500px;
  padding-bottom: 20px;
}
.game {
  transform-style: preserve-3d;
  perspective: 500px;
  min-height: 100%;
  height: 100%;
}
@keyframes matchAnim {
  0% {
    background: #bcffcc;
  }
  100% {
    background: white;
  }
}
.card {
  float: left;
  width: 16.66666%;
  height: 25%;
  padding: 5px;
  text-align: center;
  display: block;
  perspective: 500px;
  position: relative;
  cursor: pointer;
  z-index: 50;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
@media (max-width: 800px) {
  .card {
    width: 25%;
    height: 16.666%;
  }
}
.card .inside {
  width: 100%;
  height: 100%;
  display: block;
  transform-style: preserve-3d;
  transition: 0.4s ease-in-out;
  background: white;
}
.card .inside.picked, .card .inside.matched {
  transform: rotateY(180deg);
}
.card .inside.matched {
  animation: 1s matchAnim ease-in-out;
  animation-delay: 0.4s;
}
.card .front, .card .back {
  border: 1px solid black;
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 20px;
}
.card .front img, .card .back img {
  max-width: 100%;
  display: block;
  margin: 0 auto;
  max-height: 100%;
}
.card .front {
  transform: rotateY(-180deg);
}
@media (max-width: 800px) {
  .card .front {
    padding: 5px;
  }
}
.card .back {
  transform: rotateX(0);
}
@media (max-width: 800px) {
  .card .back {
    padding: 10px;
  }
}
.modal-overlay {
  display: none;
  background: rgba(0, 0, 0, .8);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.modal {
  display: none;
  position: relative;
  width: 500px;
  height: 400px;
  max-height: 90%;
  max-width: 90%;
  min-height: 380px;
  margin: 0 auto;
  background: white;
  top: 50%;
  transform: translateY(-50%);
  padding: 30px 10px;
}
.modal .winner {
  font-size: 80px;
  text-align: center;
  font-family: "Anton", sans-serif;
  color: #4d4d4d;
  text-shadow: 0px 3px 0 black;
}
@media (max-width: 480px) {
  .modal .winner {
    font-size: 60px;
  }
}
.modal .restart {
  font-family: "Anton", sans-serif;
  margin: 30px auto;
  padding: 20px 30px;
  display: block;
  font-size: 30px;
  border: none;
  background: #4d4d4d;
  background: linear-gradient(#4d4d4d, #222);
  border: 1px solid #222;
  border-radius: 5px;
  color: white;
  text-shadow: 0px 1px 0 black;
  cursor: pointer;
}
.modal .restart:hover {
  background: linear-gradient(#222, black);
}
.modal .message {
  text-align: center;
}
.modal .message a {
  text-decoration: none;
  color: #28afe6;
  font-weight: bold;
}
.modal .message a:hover {
  color: #56c0eb;
  border-bottom: 1px dotted #56c0eb;
}
.modal .share-text {
  text-align: center;
  margin: 10px auto;
}
.modal .social {
  margin: 20px auto;
  text-align: center;
}
.modal .social li {
  display: inline-block;
  height: 50px;
  width: 50px;
  margin-right: 10px;
}
.modal .social li:last-child {
  margin-right: 0;
}
.modal .social li a {
  display: block;
  line-height: 50px;
  font-size: 20px;
  color: white;
  text-decoration: none;
  border-radius: 5px;
}
.modal .social li a.facebook {
  background: #3b5998;
}
.modal .social li a.facebook:hover {
  background: #4c70ba;
}
.modal .social li a.google {
  background: #d34836;
}
.modal .social li a.google:hover {
  background: #dc6e60;
}
.modal .social li a.twitter {
  background: #4099ff;
}
.modal .social li a.twitter:hover {
  background: #73b4ff;
}
footer {
  height: 20px;
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 0;
}
footer .disclaimer {
  line-height: 20px;
  font-size: 12px;
  color: #727272;
  text-align: center;
}
@media (max-width: 767px) {
  footer .disclaimer {
    font-size: 8px;
  }
}</code>```

You Rock!

   <button class="restart">Play Again?</button>

Developed on CodePen by Nate Wiley

Share it?

All logos are property of their respective owners, No Copyright infringement intended.

```

Body:
I'm trying to rebrand this cool Memory Game developed by Nate Wiley.

I'm having an issue with it though. When you win, it allows you to restart, but the game become unplayable when the cards re-appear for a second time.

The restart button code calls this function:

reset: function(){
    this.hideModal();
    this.shuffleCards(this.cardsArray);
    this.setup();
    this.$game.show();
},

This correctly hides the modal, shuffles the card, runs the setup function, and shows the game again.

The Setup Function looks like this:

setup: function(){
    this.html = this.buildHTML();
    this.$game.html(this.html);
    this.$memoryCards = $(".card");
    this.paused = false;
    this.guess = null;
},

I'm not getting any errors in the console. How would I go about diagnosing an error in this situation?

I've created a codepen with only 2 matching pairs to make testing a lot quicker but I'm at a loss for how to figure this out.

https://codepen.io/nolaandy/pen/wPeGgo

Body:
When you don't have errors in the console you need to think about what you'd expect the code to do and work back from there. In you example, I'd expect the game to do something when I click on the card, but it doesn't so I added a console.log() in the click handler and I noticed that nothing was being logged in the console so I though "probably the card element get's rebuilt from scratch, so it looses it's event listener", so I tried delegating the event to the body, with

$('body').on("click", ".card", this.cardClicked);

and I noticed that now the click event worked, so I knew I was getting somewhere. I still wanted to keep the click code the way it was so I noticed that in the setup function he doesn't call the binding function, which is the one that attaches click events to elements, so I tried calling this.binding(); inside the setup function and sure enough it works.

PS: In my opinion it would make sense to call the buinding() function inside the setup() function, because I probably want my click events to be attached to the buttons every time I set up a game, but I kept it the way it was to leave the code as similar as possible as the original one.

// Memory Game
// © 2014 Nate Wiley
// License -- MIT
// best in full screen, works on phones/tablets (min height for game is 500px..) enjoy ;)
// Follow me on Codepen

(function(){

 var Memory = {

  init: function(cards){
   this.$game = $(".game");
   this.$modal = $(".modal");
   this.$overlay = $(".modal-overlay");
   this.$restartButton = $("button.restart");
   this.cardsArray = $.merge(cards, cards);
   this.shuffleCards(this.cardsArray);
   this.setup();
   this.binding();
  },

  shuffleCards: function(cardsArray){
   this.$cards = $(this.shuffle(this.cardsArray));
  },

  setup: function(){
   this.html = this.buildHTML();
   this.$game.html(this.html);
   this.$memoryCards = $(".card");
   this.binding();
   this.paused = false;
      this.guess = null;
  },

  binding: function(){
   this.$memoryCards.on("click", this.cardClicked);
   $("button.restart").unbind().click( $.proxy(this.reset, this));
  },
  // kinda messy but hey
  cardClicked: function(){
   var _ = Memory;
   var $card = $(this);
   if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
    $card.find(".inside").addClass("picked");
    if(!_.guess){
     _.guess = $(this).attr("data-id");
    } else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
     $(".picked").addClass("matched");
     _.guess = null;
    } else {
     _.guess = null;
     _.paused = true;
     setTimeout(function(){
      $(".picked").removeClass("picked");
      Memory.paused = false;
     }, 600);
    }
    if($(".matched").length == $(".card").length){
     _.win();
    }
   }
  },

  win: function(){
   this.paused = true;
   setTimeout(function(){
    Memory.showModal();
    Memory.$game.fadeOut();
   }, 1000);
  },

  showModal: function(){
   this.$overlay.show();
   this.$modal.fadeIn("slow");
  },

  hideModal: function(){
   this.$overlay.hide();
   this.$modal.hide();
  },

  reset: function(){
   this.hideModal();
   this.shuffleCards(this.cardsArray);
   this.setup();
   this.$game.show();
  },

  // Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
  shuffle: function(array){
   var counter = array.length, temp, index;
     // While there are elements in the array
     while (counter > 0) {
         // Pick a random index
         index = Math.floor(Math.random() * counter);
         // Decrease counter by 1
         counter--;
         // And swap the last element with it
         temp = array[counter];
         array[counter] = array[index];
         array[index] = temp;
      }
      return array;
  },

  buildHTML: function(){
   var frag = '';
   this.$cards.each(function(k, v){
    frag += '<div class="card" data-id="'+ v.id +'"><div class="inside">\
    <div class="front"><img src="'+ v.img +'"\
    alt="'+ v.name +'" /></div>\
    <div class="back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/codepen-logo.png"\
    alt="Codepen" /></div></div>\
    </div>';
   });
   return frag;
  }
 };

 var cards = [
  {
   name: "php",
   img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/php-logo_1.png",
   id: 1,
  },
  {
   name: "css3",
   img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/css3-logo.png",
   id: 2
  },
 ];

 Memory.init(cards);

})();

* {
  box-sizing: border-box;
}
html, body {
  height: 100%;
}
body {
  background: black;
  min-height: 100%;
  font-family: "Arial", sans-serif;
}
.wrap {
  position: relative;
  height: 100%;
  min-height: 500px;
  padding-bottom: 20px;
}
.game {
  transform-style: preserve-3d;
  perspective: 500px;
  min-height: 100%;
  height: 100%;
}
@keyframes matchAnim {
  0% {
    background: #bcffcc;
  }
  100% {
    background: white;
  }
}
.card {
  float: left;
  width: 16.66666%;
  height: 25%;
  padding: 5px;
  text-align: center;
  display: block;
  perspective: 500px;
  position: relative;
  cursor: pointer;
  z-index: 50;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
@media (max-width: 800px) {
  .card {
    width: 25%;
    height: 16.666%;
  }
}
.card .inside {
  width: 100%;
  height: 100%;
  display: block;
  transform-style: preserve-3d;
  transition: 0.4s ease-in-out;
  background: white;
}
.card .inside.picked, .card .inside.matched {
  transform: rotateY(180deg);
}
.card .inside.matched {
  animation: 1s matchAnim ease-in-out;
  animation-delay: 0.4s;
}
.card .front, .card .back {
  border: 1px solid black;
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 20px;
}
.card .front img, .card .back img {
  max-width: 100%;
  display: block;
  margin: 0 auto;
  max-height: 100%;
}
.card .front {
  transform: rotateY(-180deg);
}
@media (max-width: 800px) {
  .card .front {
    padding: 5px;
  }
}
.card .back {
  transform: rotateX(0);
}
@media (max-width: 800px) {
  .card .back {
    padding: 10px;
  }
}
.modal-overlay {
  display: none;
  background: rgba(0, 0, 0, .8);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.modal {
  display: none;
  position: relative;
  width: 500px;
  height: 400px;
  max-height: 90%;
  max-width: 90%;
  min-height: 380px;
  margin: 0 auto;
  background: white;
  top: 50%;
  transform: translateY(-50%);
  padding: 30px 10px;
}
.modal .winner {
  font-size: 80px;
  text-align: center;
  font-family: "Anton", sans-serif;
  color: #4d4d4d;
  text-shadow: 0px 3px 0 black;
}
@media (max-width: 480px) {
  .modal .winner {
    font-size: 60px;
  }
}
.modal .restart {
  font-family: "Anton", sans-serif;
  margin: 30px auto;
  padding: 20px 30px;
  display: block;
  font-size: 30px;
  border: none;
  background: #4d4d4d;
  background: linear-gradient(#4d4d4d, #222);
  border: 1px solid #222;
  border-radius: 5px;
  color: white;
  text-shadow: 0px 1px 0 black;
  cursor: pointer;
}
.modal .restart:hover {
  background: linear-gradient(#222, black);
}
.modal .message {
  text-align: center;
}
.modal .message a {
  text-decoration: none;
  color: #28afe6;
  font-weight: bold;
}
.modal .message a:hover {
  color: #56c0eb;
  border-bottom: 1px dotted #56c0eb;
}
.modal .share-text {
  text-align: center;
  margin: 10px auto;
}
.modal .social {
  margin: 20px auto;
  text-align: center;
}
.modal .social li {
  display: inline-block;
  height: 50px;
  width: 50px;
  margin-right: 10px;
}
.modal .social li:last-child {
  margin-right: 0;
}
.modal .social li a {
  display: block;
  line-height: 50px;
  font-size: 20px;
  color: white;
  text-decoration: none;
  border-radius: 5px;
}
.modal .social li a.facebook {
  background: #3b5998;
}
.modal .social li a.facebook:hover {
  background: #4c70ba;
}
.modal .social li a.google {
  background: #d34836;
}
.modal .social li a.google:hover {
  background: #dc6e60;
}
.modal .social li a.twitter {
  background: #4099ff;
}
.modal .social li a.twitter:hover {
  background: #73b4ff;
}
footer {
  height: 20px;
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 0;
}
footer .disclaimer {
  line-height: 20px;
  font-size: 12px;
  color: #727272;
  text-align: center;
}
@media (max-width: 767px) {
  footer .disclaimer {
    font-size: 8px;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="game"></div>

 <div class="modal-overlay">
  <div class="modal">
   <h2 class="winner">You Rock!</h2>
   <button class="restart">Play Again?</button>
   <p class="message">Developed on <a href="https://codepen.io">CodePen</a> by <a href="https://codepen.io/natewiley">Nate Wiley</a></p>
   <p class="share-text">Share it?</p>
   <ul class="social">
    <li><a target="_blank" class="twitter" href="https://twitter.com/share?url=https://codepen.io/natewiley/pen/HBrbL"><span class="fa fa-twitter"></span></a></li>
    <li><a target="_blank" class="facebook" href="https://www.facebook.com/sharer.php?u=https://codepen.io/natewiley/pen/HBrbL"><span class="fa fa-facebook"></span></a></li>
    <li><a target="_blank" class="google" href="https://plus.google.com/share?url=https://codepen.io/natewiley/pen/HBrbL"><span class="fa fa-google"></span></a></li>
   </ul>
  </div>
 </div>
  <footer>
  <p class="disclaimer">All logos are property of their respective owners, No Copyright infringement intended.</p>
 </footer>
  </div><!-- End Wrap -->


问:
Linked Lists: Iterator vs List Iterator
I'm reviewing linked lists in Java, learned them in C, and I noticed that I can use an iterator class to go through the linked list. But what I found strange is that they used a ListIterator to iterate forwards on the list (it can also be used to iterate backwards depending on where the pointer is), and Iterator to iterate backwards on the list. My question is, why can't we just use Iterator to iterate both forwards and backwards? What is the difference between the two?</p>

答:
Iterator

Iterator is a very general solution which should fit all data-structures, in fact you can iterate every class in Collection (documentation). But not every class there can ensure backwards-iterating simply due to their internal data-structure. For example a TreeSet which only knows its root element:

So Iterator tries to fit the common ability of all data structures to be at least iterable in one direction (documentation)

ListIterator

ListIterator is a special, not general, solution only useable for special List since they can, due to their internal structure, be iterated in both directions (and also allow adding and removing elements in between). This is not possible with other structures like TreeSet, so Collection doesn't offer ListIterator for all Collections, just List has it. From its documentation:

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

To wrap it up, if Collection would offer a special Iterator like ListIterator then all implementing classes, also TreeSet and co. would need to implement this method. However those classes may not be able to meet that requirement (without heavy extra overhead).

Title: Linked Lists: Iterator vs List Iterator


问:
Symfony create new service as a new instance
I have a service defined with several dependency injections in the constructor. At some point I want to get the service as a new instance instead of the same instance already created. Note that normally I want the service to be shared, but on an edge case I want to create a new instance, so the shared option in the service definition is not aplicable.

I can create a new object, but I then I would have to inject the dependencies manually, and I would prefer to let symfony to deal with it.

So how can I tell Symfony to return a service as a new instance?

Thank you.

答:
As far as I know, there is no way to tell the Symfony Dependency Injection Container to return some times the shared instance, and other times a new instance of a service.

By default, the services are shared, as you already found out. You can tell the container to create a not-shared service by setting the shared setting to false in your service definition:

```<code># app/config/services.yml
services:
    AppBundle\SomeNonSharedService:
        shared: false
</code>```

Armed with this knowledge, I think the solution for your issue is to create a duplicate of the shared service with a different name and mark it as not-shared as explained above. When you ask the container to get the duplicate, it will create a new instance every time.

Do not attempt to create the duplicate as an alias of the original service, it doesn't work. The first thing the implementation of Contaner::get() does is to search for the service ID provided as argument into the list of aliases and use the ID of the original service instead if it finds it there.

Body:
As far as I know, there is no way to tell the Symfony Dependency Injection Container to return some times the shared instance, and other times a new instance of a service.

By default, the services are shared, as you already found out. You can tell the container to create a not-shared service by setting the shared setting to false in your service definition:

# app/config/services.yml
services:
    AppBundle\SomeNonSharedService:
        shared: false

Armed with this knowledge, I think the solution for your issue is to create a duplicate of the shared service with a different name and mark it as not-shared as explained above. When you ask the container to get the duplicate, it will create a new instance every time.

Do not attempt to create the duplicate as an alias of the original service, it doesn't work. The first thing the implementation of Contaner::get() does is to search for the service ID provided as argument into the list of aliases and use the ID of the original service instead if it finds it there.


问:
Math needed for Sql Server
I've been working in Sql server jobs since 2 years now. Although I like it, sometimes I get the feeling that at certain times, I stall too much on some tasks, and I seem to be discouraged easily from things that involve relatively simple logic. It's like, at some point I must repeat a logical condition inside my head more than 2 or 3 times in order to understand it completely.

I have the feeling that this might be of my lack of math knowledge. Can anyone please let me know what area of mathematics I can study, that would improve my Sql server coding skills?

Thank you.

答:
I'd suggest reading up on Set based Math.

See this link: http://weblogs.sqlteam.com/jeffs/archive/2007/04/30/thinking-set-based-or-not.aspx

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Math needed for Sql Server

ContentLicense: CC BY-SA 2.5


问:
Disable compass on MKMapView
I am using a MapView in my app to show some annotations. In iOS 7 a compass appears randomly on the map. I can't reproduce the error because it appears randomly but I want to disable it.
Any ideas how to disable it?

Update: I found out is not appears randomly but on a specific gesture. When you use 2 fingers and slide one right and the other left.

答:
Here is solution for Swift 4:</p>

```<code>mapView.compassView.isHidden = true
</code>```

Title: Disable compass on MKMapView

Body:
Here is solution for Swift 4:

mapView.compassView.isHidden = true


问:
Update observations in dataframe according to other dataframe?
I have a dataframe say prod_score:

```<code>product score
a       1
d       2
ff      2
e       3
fvf     1
</code>```

I have another dataframe prod_rank with same products + their rank prod_rank:

```<code>product   rank
a         11
d         4
ff        1
e         5
fvf       9
</code>```

Just to clarify I have a lot of observations that's why I show sample data.

Filtering all the products with score 2:

```<code>library(dplyr)
prod_scr_2 <- prod_score %>% filter(score == 2)
</code>```

Now I want to take prod_scr_2 products and update the score according to the prod_rank df:

I have used join:

```<code>decision_tbl <- inner_join(prod_scr_2, prod_rank, by = "product") %>%
                                                top_n(2,desc(rank))
</code>```

Now I am taking decision_tbl$product and want to update the score of only the products that get top rank.

I have used match to do this:

```<code>prods2update_idx <- match(decision_tbl$product, prod_score$product)
</code>```

Given match indexes I am trying to update the prod_score dataframe, please advise how can I do this?

答:
Assume that the score of interest is 2 (as you mentioned in your example) and the updated score for the products with top rank is 100. Those can be changed.

Here's a dplyr solution, because I saw you started working using this package:

```<code>library(dplyr)

prod_score = read.table(text = "
product score
a       1
d       2
ff      2
e       3
fvf     1
", header = T, stringsAsFactors = F)

prod_rank = read.table(text = "
product   rank
a         11
d         4
ff        1
e         5
fvf       9
", header = T, stringsAsFactors = F)

prod_score %>%
  filter(score == 2) %>%                                 # select products with score = 2
  inner_join(prod_rank, by = "product") %>%              # join to get ranks
  filter(rank == max(rank)) %>%                          # keep product(s) with maximum ranks
  rename(given_score = score) %>%                        # change column name (for the next join)
  right_join(prod_score, by = "product") %>%             # join to get scores
  mutate(score = ifelse(!is.na(rank), 100, score)) %>%   # update score when there's a rank value
  select(-given_score, -rank)                            # remove unnecessary columns

#   product score
# 1       a     1
# 2       d   100
# 3      ff     2
# 4       e     3
# 5     fvf     1
</code>```

And an alternative approach in base R. Remember to re-build initial example datasets:

```<code># get products with score = 2
prod_score$product[prod_score$score == 2] -> prds_score_2

# get ranks for those products
prod_rank[prod_rank$product %in% prds_score_2,] -> prds_score_2_ranks

# keep products with maximum rank to update
prds_score_2_ranks$product[prds_score_2_ranks$rank == max(prds_score_2_ranks$rank)] -> prds_to_update

# update values for those products in your initial table
prod_score$score[prod_score$product %in% prds_to_update] = 100

# see the updates
prod_score

#   product score
# 1       a     1
# 2       d   100
# 3      ff     2
# 4       e     3
# 5     fvf     1
</code>```

Body:
I have a dataframe say prod_score:

product score
a       1
d       2
ff      2
e       3
fvf     1

I have another dataframe prod_rank with same products + their rank prod_rank:

product   rank
a         11
d         4
ff        1
e         5
fvf       9

Just to clarify I have a lot of observations that's why I show sample data.

Filtering all the products with score 2:

library(dplyr)
prod_scr_2 <- prod_score %>% filter(score == 2)

Now I want to take prod_scr_2 products and update the score according to the prod_rank df:

I have used join:

decision_tbl <- inner_join(prod_scr_2, prod_rank, by = "product") %>%
                                                top_n(2,desc(rank))

Now I am taking decision_tbl$product and want to update the score of only the products that get top rank.

I have used match to do this:

prods2update_idx <- match(decision_tbl$product, prod_score$product)

Given match indexes I am trying to update the prod_score dataframe, please advise how can I do this?

Body:
Assume that the score of interest is 2 (as you mentioned in your example) and the updated score for the products with top rank is 100. Those can be changed.

Here's a dplyr solution, because I saw you started working using this package:

library(dplyr)

prod_score = read.table(text = "
product score
a       1
d       2
ff      2
e       3
fvf     1
", header = T, stringsAsFactors = F)

prod_rank = read.table(text = "
product   rank
a         11
d         4
ff        1
e         5
fvf       9
", header = T, stringsAsFactors = F)

prod_score %>%
  filter(score == 2) %>%                                 # select products with score = 2
  inner_join(prod_rank, by = "product") %>%              # join to get ranks
  filter(rank == max(rank)) %>%                          # keep product(s) with maximum ranks
  rename(given_score = score) %>%                        # change column name (for the next join)
  right_join(prod_score, by = "product") %>%             # join to get scores
  mutate(score = ifelse(!is.na(rank), 100, score)) %>%   # update score when there's a rank value
  select(-given_score, -rank)                            # remove unnecessary columns

#   product score
# 1       a     1
# 2       d   100
# 3      ff     2
# 4       e     3
# 5     fvf     1

And an alternative approach in base R. Remember to re-build initial example datasets:

# get products with score = 2
prod_score$product[prod_score$score == 2] -> prds_score_2

# get ranks for those products
prod_rank[prod_rank$product %in% prds_score_2,] -> prds_score_2_ranks

# keep products with maximum rank to update
prds_score_2_ranks$product[prds_score_2_ranks$rank == max(prds_score_2_ranks$rank)] -> prds_to_update

# update values for those products in your initial table
prod_score$score[prod_score$product %in% prds_to_update] = 100

# see the updates
prod_score

#   product score
# 1       a     1
# 2       d   100
# 3      ff     2
# 4       e     3
# 5     fvf     1


问:
Finding elements by class in Selenium
Okay, so I'm trying to find the 179 in:

```<code><span class="totalcount">179</span>
</code>```

However, for some reason:

```<code>maxpage = driver.find_element_by_class_name('totalcount')
</code>```

results in maxpage being set equal to:

```<code><selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>
</code>```

But I want to get value equal to 179. Do you have any advice?

答:
The command driver.find_element_by_class_name('totalcount') returns a WebElement.

Such instance includes a number of things, like the position of the element, if it is visible/clickable etc. You must use .text to find the "value" of you element. Try the following:

maxpage = driver.find_element_by_class_name('totalcount').text
or maxpage.text and assign it to a string.

Title: Finding elements by class in Selenium

Body:
Okay, so I'm trying to find the 179 in:

179

However, for some reason:

maxpage = driver.find_element_by_class_name('totalcount')

results in maxpage being set equal to:

<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>

But I want to get value equal to 179. Do you have any advice?


问:
How to change the field background color in Crystal Reports using HTML?
I have a cross-tab in the report. I need to change background color of the summary field based on the database field HEX value. For this I'm interpreting field as HTML. So I created the formula fields and trying to use HTML tags to format it. I can change the font color OK, like this:

But I cannot figure out how to change the background color. I have a database field for this - {Report_SELECT_TagLayouts.BackgroundColorHex}, but even if I just use regular HEX values it doesn't work. I've tried different tags - div, span etc. - no luck.

I understand that Crystal reports support only limited number of HTML tags, but whatever I try is not working. Font color is fine.

I would appreciate your suggestions.

答:
Unfortunately, you will need to convert your hex to rgb.

I would then go to then go to the border tab, click on the background X-2 in the Color box.
You would then place the your criteria (if x then color(r,g,b) else crNoColor
You will probably need to create a variable formula for the rgb conversion
i.g.

```<code>local numberVar R;
local numberVar B;
local numberVar G;
local stringVar convert;
convert =: R & "," & "," & B & "," & G;

if x then color(convert) else crNoColor
</code>```

good news though is that someone has already done conversion math.
http://www.rapidtables.com/convert/color/hex-to-rgb.htm

Body:
Unfortunately, you will need to convert your hex to rgb.

I would then go to then go to the border tab, click on the background X-2 in the Color box.
You would then place the your criteria (if x then color(r,g,b) else crNoColor
You will probably need to create a variable formula for the rgb conversion
i.g.

local numberVar R;
local numberVar B;
local numberVar G;
local stringVar convert;
convert =: R & "," & "," & B & "," & G;

if x then color(convert) else crNoColor

good news though is that someone has already done conversion math.
http://www.rapidtables.com/convert/color/hex-to-rgb.htm


问:
Create dense matrix from sparse matrix efficently (numpy/scipy but NO sklearn)
I have a sparse.txt that looks like this:

```<code># first column is label 0 or 1
# rest of the data is sparse data
# maximum value in the data is 4, so the future dense matrix will
# have 1+4 = 5 elements in a row
# file: sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 2:1 3:1 4:1
</code>```

The required dense.txt is this:

```<code># required file: dense.txt
1 1 1 1 0
0 1 0 0 1
1 0 1 1 1
</code>```

Without using scipy coo_matrix it did it in a simple way like this:

```<code>def create_dense(fsparse, fdense,fvocab):
    # number of lines in vocab
    lvocab = sum(1 for line in open(fvocab))

    # create dense file
    with open(fsparse) as fi, open(fdense,'w') as fo:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]

            l = " ".join(map(str,row)) + "\n"
            fo.write(l)

            print('Writing dense matrix line: ', i+1)
</code>```

Question
How can we directly get label and data from sparse data without first creating dense matrix and using NUMPY /Scipy preferably??

Question:
How can we read the sparse data using numpy.fromregex ?

My attempt is:

```<code>def read_file(fsparse):
    regex = r'([0-1]\s)([0-9]):(1\s)*([0-9]:1)' + r'\s*\n'
    data = np.fromregex(fsparse,regex,dtype=str)

    print(data,file=open('dense.txt','w'))
</code>```

It did not work!

Related links:

Parsing colon separated sparse data with pandas and numpy

答:
(Answered before explicitly disallowing sklearn)

This is basically the svmlight / libsvm format.

Just use scikit-learn's load_svmlight_file or the more efficient svmlight-loader. No need to reinvent the wheel here!

```<code>from sklearn.datasets import load_svmlight_file

X, y = load_svmlight_file('C:/TEMP/sparse.txt')
print(X)
print(y)
print(X.todense())
</code>```

Output:

```<code>(0, 0)        1.0
(0, 1)        1.0
(0, 2)        1.0
(1, 0)        1.0
(1, 3)        1.0
(2, 1)        1.0
(2, 2)        1.0
(2, 3)        1.0
[ 1.  0.  1.]
[[ 1.  1.  1.  0.]
[ 1.  0.  0.  1.]
[ 0.  1.  1.  1.]]
</code>```

Body:
I have a sparse.txt that looks like this:

# first column is label 0 or 1
# rest of the data is sparse data
# maximum value in the data is 4, so the future dense matrix will
# have 1+4 = 5 elements in a row
# file: sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 2:1 3:1 4:1

The required dense.txt is this:

# required file: dense.txt
1 1 1 1 0
0 1 0 0 1
1 0 1 1 1

Without using scipy coo_matrix it did it in a simple way like this:

def create_dense(fsparse, fdense,fvocab):
    # number of lines in vocab
    lvocab = sum(1 for line in open(fvocab))

    # create dense file
    with open(fsparse) as fi, open(fdense,'w') as fo:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]

            l = " ".join(map(str,row)) + "\n"
            fo.write(l)

            print('Writing dense matrix line: ', i+1)

Question
How can we directly get label and data from sparse data without first creating dense matrix and using NUMPY /Scipy preferably??

Question:
How can we read the sparse data using numpy.fromregex ?

My attempt is:

def read_file(fsparse):
    regex = r'([0-1]\s)([0-9]):(1\s)*([0-9]:1)' + r'\s*\n'
    data = np.fromregex(fsparse,regex,dtype=str)

    print(data,file=open('dense.txt','w'))

It did not work!

Related links:

Parsing colon separated sparse data with pandas and numpy

Body:
(Answered before explicitly disallowing sklearn)

This is basically the svmlight / libsvm format.

Just use scikit-learn's load_svmlight_file or the more efficient svmlight-loader. No need to reinvent the wheel here!

from sklearn.datasets import load_svmlight_file

X, y = load_svmlight_file('C:/TEMP/sparse.txt')
print(X)
print(y)
print(X.todense())

Output:

(0, 0)        1.0
(0, 1)        1.0
(0, 2)        1.0
(1, 0)        1.0
(1, 3)        1.0
(2, 1)        1.0
(2, 2)        1.0
(2, 3)        1.0
[ 1.  0.  1.]
[[ 1.  1.  1.  0.]
[ 1.  0.  0.  1.]
[ 0.  1.  1.  1.]]


问:
Blur effect on view background
I have this extension, and I was hoping for a blur background, where I can see blur through the view:

```<code>import Foundation
import UIKit

extension UIView
{
    func addBlurEffect()
    {
        if !UIAccessibilityIsReduceTransparencyEnabled() {
            self.backgroundColor = UIColor.clear

            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            blurEffectView.frame = self.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.addSubview(blurEffectView)
        } else {
            self.backgroundColor = UIColor.white
        }

    }
}
</code>```

Then I use it like this:

```<code>let v = UIView(frame: self.view.frame)

v.addBlurEffect()

self.view.addSubview(v)
</code>```

But I can not see anything under the view?

答:
Add this framework to your project.

Add transparent view over your background and setup blur (view Readme on github)

Preview

Title: Blur effect on view background

Body:
I have this extension, and I was hoping for a blur background, where I can see blur through the view:

import Foundation
import UIKit

extension UIView
{
    func addBlurEffect()
    {
        if !UIAccessibilityIsReduceTransparencyEnabled() {
            self.backgroundColor = UIColor.clear

            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            blurEffectView.frame = self.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.addSubview(blurEffectView)
        } else {
            self.backgroundColor = UIColor.white
        }

    }
}

Then I use it like this:

let v = UIView(frame: self.view.frame)

v.addBlurEffect()

self.view.addSubview(v)

But I can not see anything under the view?


问:
Full page images on click
I am sorry for not trying anything yet but I can't seem to find what I am looking for. I have this menu:

```<code><div class="overlay-navigation">
    <nav role="navigation">
        <ul class="test">
            <li>
                <a href="#" data-content=""></a>
            </li>
            <li><a href="#three" class="scrollTo" data-content="">tutorials</li>
            <li><a href="" target="_blank" data-content="">my creations</a>
            </li>
            <li><a href="#four" class="scroll" data-content="">contact</a>
            </li>
            <li>
                <a href="#" data-content=""></a>
            </li>
        </ul>
    </nav>
</div>
</code>```

When I click on my creations, I want a simple full screen image caroussel, gallery or flexbox to appear (whatever looks better, the menu opens at full screen) that's easy to close. I would appreciate any code examples so I can style it to my liking, I will only have about 4 images.

答: You can use the boostrap carousel. https://www.w3schools.com/bootstrap/bootstrap_carousel.asp</p>

Title: Full page images on click

Body:
I am sorry for not trying anything yet but I can't seem to find what I am looking for. I have this menu:

tutorials

my creations

contact

When I click on my creations, I want a simple full screen image caroussel, gallery or flexbox to appear (whatever looks better, the menu opens at full screen) that's easy to close. I would appreciate any code examples so I can style it to my liking, I will only have about 4 images.