问:
zf3 zend navigation helper
I'm trying to implement my zend navigation from a container in ZF3. I have successfully created navigation with this quick start tutorial introducing navigation directly in config/autoload/global.php or config/module.config.php files:

https://docs.zendframework.com/zend-navigation/quick-start/

But now I need to make it work these with the helpers to allow navigation modifications from the controller, using the "Navigation setup used in examples" section:

https://docs.zendframework.com/zend-navigation/helpers/intro/

This is my Module.php

```<code>namespace Application;

use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\View\HelperPluginManager;

class Module implements ConfigProviderInterface
{
    public function getViewHelperConfig()
    {
        return [
            'factories' => [
                // This will overwrite the native navigation helper
                'navigation' => function(HelperPluginManager $pm) {
                    // Get an instance of the proxy helper
                    $navigation = $pm->get('Zend\View\Helper\Navigation');
                    // Return the new navigation helper instance
                    return $navigation;
                }
            ]
        ];
    }

    public function getControllerConfig()
    {
        return [
            'factories' => [
                        $this->getViewHelperConfig()
                    );
                },
            ],
        ];
    }
}
</code>```

And this is my IndexController.php

```<code>namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Navigation\Navigation;
use Zend\Navigation\Page\AbstractPage;

class IndexController extends AbstractActionController
{

    private $navigationHelper;

    public function __construct(
        $navigationHelper
    ){
        $this->navigationHelper = $navigationHelper;
    }

    public function indexAction()
    {

        $container = new Navigation();
        $container->addPage(AbstractPage::factory([
            'uri' => 'http://www.example.com/',
        ]));

        $this->navigationHelper->plugin('navigation')->setContainer($container);

        return new ViewModel([
        ]);
    }

}
</code>```

But then I get the following error:

```<code>Fatal error: Call to a member function plugin() on array in /var/www/html/zf3/module/Application/src/Controller/IndexController.php on line 50
</code>```

In the tutorial they use the following statement:

```<code>// Store the container in the proxy helper:
$view->plugin('navigation')->setContainer($container);

// ...or simply:
$view->navigation($container);
</code>```

But I don´t know what this $view is, so I assume is my $navigation from my Module.php. The problem is that, because is an array, it throws the error. The questions are:

What am I doing wrong?

Where this $view of the tutorial come from?

What I should pass from my Module.php to get it work?

Thanks in advance!

答:
Add into module.config.php

```<code>'service_manager' => [
   'factories' => [
      Service\NavManager::class => Service\Factory\NavManagerFactory::class,
    ],
],

'view_helpers' => [
   'factories' => [
      View\Helper\Menu::class => View\Helper\Factory\MenuFactory::class,
    ],
    'aliases' => [
        'mainMenu' => View\Helper\Menu::class,
    ],
],
</code>```

Create Factory in Service Directory:

```<code>namespace Application\Service\Factory;

use Interop\Container\ContainerInterface;
use Application\Service\NavManager;

class NavManagerFactory {
/**
 * This method creates the NavManager service and returns its instance.
 */
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
    $authService = $container->get(\Zend\Authentication\AuthenticationService::class);
    $viewHelperManager = $container->get('ViewHelperManager');
    $urlHelper = $viewHelperManager->get('url');

    return new NavManager($authService, $urlHelper);
   }
}
</code>```

Create NavManager file :

```<code>namespace Application\Service;

class NavManager {
/**
 * Auth service.
 * @var Zend\Authentication\Authentication
 */
private $authService;

/**
 * Url view helper.
 * @var Zend\View\Helper\Url
 */
private $urlHelper;

/**
 * Constructs the service.
 */
public function __construct($authService, $urlHelper) {
    $this->authService = $authService;
    $this->urlHelper = $urlHelper;
}

/**
 * Menu render based on user role
 *
 * @return array
 */
public function getMenuItems() {
    $navItem = array();
    $url = $this->urlHelper;
    $items = [];

    $items[] = [
        'label' => 'Dashboard',
        'icon' => 'dashboard',
        'link'  => $url('home'),
        'route' => ['home'],
    ];

    $items[] = [
        'label' => 'About Us',
        'icon' => 'business',
        'link' => $url('about', ['action'=>'index']),
        'route' => ['about'],
    ];

    $items[] = [
        'label' => 'Service',
        'icon' => 'service',
        'link' => $url('service', ['action'=>'index']),
        'route' => ['service'],
    ];

    return $items;
}
</code>```

Create Helper Factory

```<code>namespace Application\View\Helper\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\View\Helper\Menu;
use Application\Service\NavManager;

/**
* This is the factory for Menu view helper. Its purpose is to
 instantiate the helper and init menu items. */
class MenuFactory implements FactoryInterface {

public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
    $navManager = $container->get(NavManager::class);
    // Get menu items.
    $items = $navManager->getMenuItems();
    // Instantiate the helper.
    return new Menu($items);
  }

}
</code>```

Create Helper :

```<code>namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

/**
* This view helper class displays a menu bar.
*/
class Menu extends AbstractHelper {
/**
 * Menu items array.
 * @var array
 */
protected $items = [];

/**
 * Active item's ID.
 * @var string
 */
protected $activeItemId = '';

/**
 * Constructor.
 * @param array $items Menu items.
 */
public function __construct($items=[]) {
    $this->items = $items;
}

/**
 * Sets menu items.
 * @param array $items Menu items.
 */
public function setItems($items) {
    $this->items = $items;
}

/**
 * Sets ID of the active items.
 * @param string $activeItemId
 */
public function setActiveItemId($activeItemId) {
    $this->activeItemId = $activeItemId;
}

/**
 * Renders the menu.
 * @return string HTML code of the menu.
 */
public function render() {
    if (count($this->items)==0) {
        return ''; // Do nothing if there are no items.
    }

    // Render items
    foreach ($this->items as $item) {
        $result .= $this->renderItem($item);
    }

    return $result;

}
protected function renderItem($item) {
   // here you can integrate with HTML
   return $item;
}
}
</code>```

After add above codes,just add below code in your layout file :

```<code>echo $this->mainMenu()->render();
</code>```

Title: zf3 zend navigation helper

Body:
I'm trying to implement my zend navigation from a container in ZF3. I have successfully created navigation with this quick start tutorial introducing navigation directly in config/autoload/global.php or config/module.config.php files:

https://docs.zendframework.com/zend-navigation/quick-start/

But now I need to make it work these with the helpers to allow navigation modifications from the controller, using the "Navigation setup used in examples" section:

https://docs.zendframework.com/zend-navigation/helpers/intro/

This is my Module.php

namespace Application;

use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\View\HelperPluginManager;

class Module implements ConfigProviderInterface
{
    public function getViewHelperConfig()
    {
        return [
            'factories' => [
                // This will overwrite the native navigation helper
                'navigation' => function(HelperPluginManager $pm) {
                    // Get an instance of the proxy helper
                    $navigation = $pm->get('Zend\View\Helper\Navigation');
                    // Return the new navigation helper instance
                    return $navigation;
                }
            ]
        ];
    }

    public function getControllerConfig()
    {
        return [
            'factories' => [
                        $this->getViewHelperConfig()
                    );
                },
            ],
        ];
    }
}

And this is my IndexController.php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Navigation\Navigation;
use Zend\Navigation\Page\AbstractPage;

class IndexController extends AbstractActionController
{

    private $navigationHelper;

    public function __construct(
        $navigationHelper
    ){
        $this->navigationHelper = $navigationHelper;
    }

    public function indexAction()
    {

        $container = new Navigation();
        $container->addPage(AbstractPage::factory([
            'uri' => 'http://www.example.com/',
        ]));

        $this->navigationHelper->plugin('navigation')->setContainer($container);

        return new ViewModel([
        ]);
    }

}

But then I get the following error:

Fatal error: Call to a member function plugin() on array in /var/www/html/zf3/module/Application/src/Controller/IndexController.php on line 50

In the tutorial they use the following statement:

// Store the container in the proxy helper:
$view->plugin('navigation')->setContainer($container);

// ...or simply:
$view->navigation($container);

But I don´t know what this $view is, so I assume is my $navigation from my Module.php. The problem is that, because is an array, it throws the error. The questions are:

What am I doing wrong?

Where this $view of the tutorial come from?

What I should pass from my Module.php to get it work?

Thanks in advance!

Body:
Add into module.config.php

'service_manager' => [
   'factories' => [
      Service\NavManager::class => Service\Factory\NavManagerFactory::class,
    ],
],

'view_helpers' => [
   'factories' => [
      View\Helper\Menu::class => View\Helper\Factory\MenuFactory::class,
    ],
    'aliases' => [
        'mainMenu' => View\Helper\Menu::class,
    ],
],

Create Factory in Service Directory:

namespace Application\Service\Factory;

use Interop\Container\ContainerInterface;
use Application\Service\NavManager;

class NavManagerFactory {
/**
 * This method creates the NavManager service and returns its instance.
 */
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
    $authService = $container->get(\Zend\Authentication\AuthenticationService::class);
    $viewHelperManager = $container->get('ViewHelperManager');
    $urlHelper = $viewHelperManager->get('url');

    return new NavManager($authService, $urlHelper);
   }
}

Create NavManager file :

namespace Application\Service;

class NavManager {
/**
 * Auth service.
 * @var Zend\Authentication\Authentication
 */
private $authService;

/**
 * Url view helper.
 * @var Zend\View\Helper\Url
 */
private $urlHelper;

/**
 * Constructs the service.
 */
public function __construct($authService, $urlHelper) {
    $this->authService = $authService;
    $this->urlHelper = $urlHelper;
}

/**
 * Menu render based on user role
 *
 * @return array
 */
public function getMenuItems() {
    $navItem = array();
    $url = $this->urlHelper;
    $items = [];

    $items[] = [
        'label' => 'Dashboard',
        'icon' => 'dashboard',
        'link'  => $url('home'),
        'route' => ['home'],
    ];

    $items[] = [
        'label' => 'About Us',
        'icon' => 'business',
        'link' => $url('about', ['action'=>'index']),
        'route' => ['about'],
    ];

    $items[] = [
        'label' => 'Service',
        'icon' => 'service',
        'link' => $url('service', ['action'=>'index']),
        'route' => ['service'],
    ];

    return $items;
}

Create Helper Factory

namespace Application\View\Helper\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\View\Helper\Menu;
use Application\Service\NavManager;

/**
* This is the factory for Menu view helper. Its purpose is to
 instantiate the helper and init menu items. */
class MenuFactory implements FactoryInterface {

public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
    $navManager = $container->get(NavManager::class);
    // Get menu items.
    $items = $navManager->getMenuItems();
    // Instantiate the helper.
    return new Menu($items);
  }

}

Create Helper :

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

/**
* This view helper class displays a menu bar.
*/
class Menu extends AbstractHelper {
/**
 * Menu items array.
 * @var array
 */
protected $items = [];

/**
 * Active item's ID.
 * @var string
 */
protected $activeItemId = '';

/**
 * Constructor.
 * @param array $items Menu items.
 */
public function __construct($items=[]) {
    $this->items = $items;
}

/**
 * Sets menu items.
 * @param array $items Menu items.
 */
public function setItems($items) {
    $this->items = $items;
}

/**
 * Sets ID of the active items.
 * @param string $activeItemId
 */
public function setActiveItemId($activeItemId) {
    $this->activeItemId = $activeItemId;
}

/**
 * Renders the menu.
 * @return string HTML code of the menu.
 */
public function render() {
    if (count($this->items)==0) {
        return ''; // Do nothing if there are no items.
    }

    // Render items
    foreach ($this->items as $item) {
        $result .= $this->renderItem($item);
    }

    return $result;

}
protected function renderItem($item) {
   // here you can integrate with HTML
   return $item;
}
}

After add above codes,just add below code in your layout file :

echo $this->mainMenu()->render();


来源: stackexchange

问:
JavaScript classList not working while clicking a button
I am currently creating a dropdown menu so I want the menu to be displayed when clicked by adding class via Javascript but classList is not working at all. I tried lots of time but couldn't. Also if i add style.display = "block", then it works! I am unable to figure out! Please Help me!

document.getElementById('dbtn').addEventListener('click', function() {
  document.getElementById('d-content').classList.toggle('show');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
  position: relative;
  display: inline-block;
}

#dbtn {
  background-color: #F44336;
  font-size: 27px;
  font-family: 'Droid Sans', sans-serif;
  border: none;
  padding: 0.3em 0.6em;
  color: #FFFFFF;
  cursor: pointer;
  outline: none;
}

#d-content {
  position: absolute;
  display: none;
  background-color: #F44336;
  font-family: 'Droid Sans', sans-serif;
  font-size: 22px;
  border-top: 2px solid #FFFFFF;
  z-index: 1;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#d-content a {
  color: #FFFFFF;
  text-decoration: none;
  display: block;
  padding: 0.3em 5em 0.3em 0.3em;
}

#d-content a:hover {
  background-color: darkorchid;
}

.show {
  display: block;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dropdown Menu</title>

    <input type="button" id="dbtn" value="Select..." />

      USA
      Canada
      Europe

```

答:
In CSS, the id selector has far more weight over the class selector.

You need to add !important; to your .show display rule.

ContentLicense: CC BY-SA 3.0

Body:
I am currently creating a dropdown menu so I want the menu to be displayed when clicked by adding class via Javascript but classList is not working at all. I tried lots of time but couldn't. Also if i add style.display = "block", then it works! I am unable to figure out! Please Help me!

document.getElementById('dbtn').addEventListener('click', function() {
  document.getElementById('d-content').classList.toggle('show');
});

#wrapper {
  position: relative;
  display: inline-block;
}

#dbtn {
  background-color: #F44336;
  font-size: 27px;
  font-family: 'Droid Sans', sans-serif;
  border: none;
  padding: 0.3em 0.6em;
  color: #FFFFFF;
  cursor: pointer;
  outline: none;
}

#d-content {
  position: absolute;
  display: none;
  background-color: #F44336;
  font-family: 'Droid Sans', sans-serif;
  font-size: 22px;
  border-top: 2px solid #FFFFFF;
  z-index: 1;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#d-content a {
  color: #FFFFFF;
  text-decoration: none;
  display: block;
  padding: 0.3em 5em 0.3em 0.3em;
}

#d-content a:hover {
  background-color: darkorchid;
}

.show {
  display: block;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dropdown Menu</title>

    <input type="button" id="dbtn" value="Select..." />

      USA
      Canada
      Europe


问:
Toggle arrows at the end of the first line of text
How to add arrows at the end of the first line text? And I want it point down when collapse and point up when expand. Like shown as images below. Appreciate your help, thanks!

$(".expander").click(function() {
    if ($(this).hasClass("expander")) {
        $(this).removeClass("expander");
    }
    else {
         $(this).addClass("expander");
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expander {
    height: 1em;
    overflow: hidden;
    cursor: pointer;
}</code>```

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

```

Code taken from here

答:
You can use . tag. The  tag specifies additional details that the user can view or hide on demand.

details summary::-webkit-details-marker {
  background: #fff;
  color: green;
  font-size: 200%;
  float: right;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><details>
  <summary> Contrary to popular belief , Lorem Ipsum is not..</summary>

  <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.  </p>
</details></code>```

Body:
How to add arrows at the end of the first line text? And I want it point down when collapse and point up when expand. Like shown as images below. Appreciate your help, thanks!

$(".expander").click(function() {
    if ($(this).hasClass("expander")) {
        $(this).removeClass("expander");
    }
    else {
         $(this).addClass("expander");
    }
});

.expander {
    height: 1em;
    overflow: hidden;
    cursor: pointer;
}

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

Code taken from here

Body:
You can use <details>. tag. The  tag specifies additional details that the user can view or hide on demand.

details summary::-webkit-details-marker {
  background: #fff;
  color: green;
  font-size: 200%;
  float: right;

}

<details>
  <summary> Contrary to popular belief , Lorem Ipsum is not..</summary>

  <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.  </p>
</details>


问:
Practical advice on using Jersey and Guice for RESTful service
From what I can find online, the state of the art for Guice + Jersey integration has stagnated since 2008 when it appears both teams reached an impasse. The crux of the issue is that JAX-RS annotations perform field and method injection and this doesn't play nicely with Guice's own dependency injection.

A few examples which I've found don't go far enough to elucidate:

Iqbalyusuf's post on Jersey + Guice on Google App Engine Java suffers from a lot of boilerplate (manually getting and calling the injector). I want binding and injection should happen behind the scenes via Guice annotations.

Jonathan Curran's article Creating a RESTful service with Jersey, Guice, and JSR-250 gave me hope because it's much more current (2010), but went no further than showing how to start up a Jersey service inside of a Guice ServletModule. However, there are no examples of doing any real dependency injection. I suppose that was left as an exercise for the reader. Curran's post may in fact be the correct first step towards wiring up Guice and Jersey and so I plan on starting with that.

tantalizingly James Strachan writes:

JAX-RS works well with dependency
  injection frameworks such as Spring,
  Guice, GuiceyFruit or JBossMC - you
  can basically pick whichever one you
  prefer.

But I see no evidence that is true from a practitioner's point of view.

What I find lacking are practical examples and explanations on how to combine JAX-RS and Guice annotations. For instance:

I believe I cannot use constructor injection with any resource as Jersey wants to control this

I'm uncertain whether I can combine @Inject with @PathParam, @QueryParam, et al.

How to use injection in a MessageBodyWriter implementation

Does anyone have examples, preferably with source, of non-trivial application which combines Jersey and Guice without sacrificing one or the other in the process? I'm keeping on this road regardless, but the bits and pieces on the Jersey and Guice lists makes me think I'm repeating the work of others who came before me.

答:
Inspired by Sunnys sample application I've created a similar sample project that uses standard WAR files for deployment, e.g. in Apache Tomcat. You can find the project here:

https://github.com/danbim/template-guice-jersey-tomcat

Have fun!
Daniel

ContentLicense: CC BY-SA 2.5


问:
Create new list from list created from api response
I have some api request, I get response and parse some data in new list. List which I print is:

```<code>[u'2.40', u'2.35', u'2.67']
</code>```

I need clear list as value:

```<code>[2.40, 2.35, 2.67]
</code>```

How to do that ?

答:
In order to cast it into float, you can use list comprehension and create an new list with same items only now consist with float instead of strings.

```<code>l_str = [u'2.40', u'2.35', u'2.67']
l_float = [float(item) for item in l_str]
print (l_float)
</code>```

You can do this with map as well:

```<code>l_str = [u'2.40', u'2.35', u'2.67']
l_float = list(map(float, l_str))
print (l_float)
</code>```

Body:
I have some api request, I get response and parse some data in new list. List which I print is:

[u'2.40', u'2.35', u'2.67']

I need clear list as value:

[2.40, 2.35, 2.67]

How to do that ?

Body:
In order to cast it into float, you can use list comprehension and create an new list with same items only now consist with float instead of strings.

l_str = [u'2.40', u'2.35', u'2.67']
l_float = [float(item) for item in l_str]
print (l_float)

You can do this with map as well:

l_str = [u'2.40', u'2.35', u'2.67']
l_float = list(map(float, l_str))
print (l_float)


Title: Create new list from list created from api response

Body:
Try this,

item = [u'2.40', u'2.35', u'2.67']
new = [float(i) for i in item]


问:
Using OnkeyDown as an if condition Javascript
I would like to use .onkeydown to restrain my input field. I wrote this function, but I'd like to use it in an if condition, to check if entry keys are right or wrong.

But I don't know how form should I use in my if to call this function, because actually it's not really an Angular scope function, but a JS one...

var cpNumber = document.getElementById("cpNumber");
cpNumber.onkeydown = function(e) {
    if((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCode > 47 && e.keyCode < 58)
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 65))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 65))
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 66))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 66))
        || e.keyCode == 8) {
        return true;
    } else {
        return false;
    }
};

// If condition, check if entry keys are wrong.
// I tried cpNumber.onkeydown(e), but the "e"
// seems drop from the sky, it always shows "false".

if(cpNumber.onkeydown(e) === false) {
    alertPopup = $ionicPopup.alert({
        title: 'Oups...',
        cssClass: 'pop',
        template: '
This is Wrong !
'
    });
}
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <input class="input"
           type="text"
           id="cpNumber"
           maxlength="5"
           ng-model="cp"
           placeholder="CP">
</form></code>```

答:
You need to put the calls in the blocks themselves. Here's a fiddle for you to look at:

https://jsfiddle.net/tsamzx6h/

```<code>                          if((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCode > 47 && e.keyCode < 58)
                              || ((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCorde == 65))
                              || ((e.keyCode > 47 && e.keyCode < 58)
                              || (e.keyCode == 65))
                              || ((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCorde == 66))
                              || ((e.keyCode > 47 && e.keyCode < 58)
                              || (e.keyCode == 66))
                              || e.keyCode == 8)
                            {
                                alert("Good!");
                            }
                            else
                            {
                                alert("Wrong");
                            }
</code>```

Body:
I would like to use .onkeydown to restrain my input field. I wrote this function, but I'd like to use it in an if condition, to check if entry keys are right or wrong.

But I don't know how form should I use in my if to call this function, because actually it's not really an Angular scope function, but a JS one...

var cpNumber = document.getElementById("cpNumber");
cpNumber.onkeydown = function(e) {
    if((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCode > 47 && e.keyCode < 58)
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 65))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 65))
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 66))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 66))
        || e.keyCode == 8) {
        return true;
    } else {
        return false;
    }
};

// If condition, check if entry keys are wrong.
// I tried cpNumber.onkeydown(e), but the "e"
// seems drop from the sky, it always shows "false".

if(cpNumber.onkeydown(e) === false) {
    alertPopup = $ionicPopup.alert({
        title: 'Oups...',
        cssClass: 'pop',
        template: '
This is Wrong !
'
    });
}

<form>
    <input class="input"
           type="text"
           id="cpNumber"
           maxlength="5"
           ng-model="cp"
           placeholder="CP">
</form>

Body:
You need to put the calls in the blocks themselves. Here's a fiddle for you to look at:

https://jsfiddle.net/tsamzx6h/

                          if((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCode > 47 && e.keyCode < 58)
                              || ((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCorde == 65))
                              || ((e.keyCode > 47 && e.keyCode < 58)
                              || (e.keyCode == 65))
                              || ((e.keyCode > 95 && e.keyCode < 106)
                              || (e.keyCorde == 66))
                              || ((e.keyCode > 47 && e.keyCode < 58)
                              || (e.keyCode == 66))
                              || e.keyCode == 8)
                            {
                                alert("Good!");
                            }
                            else
                            {
                                alert("Wrong");
                            }


问:
if don't have data in database it should be ADD button display else EDIT button without page reload button should be change
Example starting company name is empty it should be ADD Button, After click the ADD button enter some data and click the save Now it should be change automatically EDIT button without page reload how to call in ajax success function please suggest me.

script

```<code><script>
    $(document).ready(function () {

        $('#data_form').on('submit', function (e) {

            var form_data = $(this).serialize();

            $.ajax({
                type: "POST",
                url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_company_insert_update',
                data: form_data,
                success: function (data)
                {
                    $('#ccity').text($("#city").val());
                },
                error: function ()
                {
                     alert('failed');
                }
            });

            e.preventDefault();
        });

    });

</script>
</code>```

form

below add and edit button how to call in ajax sucess

```<code><?php if (empty($s_city[0]) || empty($s_city)) {?>
    <a data-toggle="collapse" data-parent="#accordion" href="#collapse7">
        <div class="profile-edit col-sm-4 col-xs-4 col-md-4">Add</div>
    </a>
<?php } else { ?>
    <a data-toggle="collapse" data-parent="#accordion" href="#collapse7">
        <div class="col-md-4 col-sm-4 col-xs-4 profile-edit"> <i class="fa fa-pencil"></i> Edit</div>
    </a>
<?php } ?>
</div>
</code>```

答:
Change your form like as follow

```<code><form action="" id="data_form" method="post" >
        <div class="dashboard-column-main">
            <div class="dashboard-container">
                <div class="title-section">
                    <h3 class="section_title">Company Information</h3>
                </div>

                <div class="profile-back">
                    <div class="panel-group" id="accordion">
                        <div class="panel panel-default">

                            <div class="panel-heading row" id="first">
                                <div class="col-md-4 col-sm-4 col-xs-4">Company Name</div>
                                <div class="col-md-4 col-sm-4 col-xs-4 ellipsis" id="cname"><?php
                                    if (isset($s_company_name)) {
                                    echo $s_company_name;
                                }
                                ?>
                            </div>

                            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                                <div class="profile-edit col-sm-4 col-xs-4 col-md-4 aj-text">
                                    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
                                        Add
                                    <?php else: ?>
                                        <i class="fa fa-pencil"></i> Edit
                                    <?php endif; ?>
                                </div>
                            </a>
                        </div>

                        <div id="collapseOne" class="panel-collapse collapse">
                            <div class="panel-body">
                                <div class="row">
                                    <div class="col-md-7 col-lg-offset-2 text-center">
                                        <label class="col-md-4">Company Name</label>
                                        <div class="col-md-8">
                                            <input type="text" name="company_name" id="company_name" class="form-control"
                                            value="<?=(isset($s_company_name))?$s_company_name:null; ?>"/><br>
                                            <input type="hidden" name="save_type" id="save_type" value="<?=(empty($s_company_name[0]) || empty($s_company_name)) ? 'Save' : 'Update'; ?>">

                                            <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
                                                <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Save</button>
                                            <?php else: ?>
                                                <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Update</button>
                                            <?php endif; ?>
                                            <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

And your script will have to like this

```<code><script>
    $(document).ready(function () {

        $('#data_form').on('submit', function (e) {
            e.preventDefault();
            var form_data = $(this).serialize();
            $.ajax({
                type: "POST",
                url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_company_insert_update',
                data: form_data,
                dataType: 'json',
                success: function (result)
                {
                    $(".aj-text").html(result.replace_text);
                    $(".aj-text-btn").html(result.btn_text);
                    $("#save_type").val(result.save_type);
                    $('#cname').text($("#company_name").val());
                },
                error: function ()
                {
                    alert('failed');
                }
            });
        });
    });
</script>
</code>```

And replace your controller supplier_company_insert_update function as follow

```<code>public function supplier_company_insert_update() {

    $this->db->select('*');
    $this->db->from('supplier_otherdetails');
    $this->db->where('supplierid_fk', $this->session->id);
    $query = $this->db->get();
    $save_type = $this->input->post('save_type');
    $company_name = $this->input->post('company_name');

    if ($query->num_rows() > 0) {
        $this->Profile_model->update_supplier_company();
        //redirect('welcome/suppliercompany');
    } else {
        $this->Profile_model->insert_supplier_company();
        //redirect('welcome/suppliercompany');
    }

    if(trim($company_name)!='')
        echo json_encode(array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type));
    else
        echo json_encode(array('replace_text' => 'Save', 'btn_text' => 'Save', 'save_type' => $save_type));
}
</code>```

Hope this will work for you. If is there any help let us know...

Body:
Example starting company name is empty it should be ADD Button, After click the ADD button enter some data and click the save Now it should be change automatically EDIT button without page reload how to call in ajax success function please suggest me.

script

form

below add and edit button how to call in ajax sucess

<?php if (empty($s_city[0]) || empty($s_city)) {?>

Add

<?php } else { ?>

  Edit

<?php } ?>

Body:
Change your form like as follow

<form action="" id="data_form" method="post" >
        <div class="dashboard-column-main">
            <div class="dashboard-container">
                <div class="title-section">
                    <h3 class="section_title">Company Information</h3>
                </div>

                <div class="profile-back">
                    <div class="panel-group" id="accordion">
                        <div class="panel panel-default">

                            <div class="panel-heading row" id="first">
                                <div class="col-md-4 col-sm-4 col-xs-4">Company Name</div>
                                <div class="col-md-4 col-sm-4 col-xs-4 ellipsis" id="cname"><?php
                                    if (isset($s_company_name)) {
                                    echo $s_company_name;
                                }
                                ?>
                            </div>

                            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                                <div class="profile-edit col-sm-4 col-xs-4 col-md-4 aj-text">
                                    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
                                        Add
                                    <?php else: ?>
                                        <i class="fa fa-pencil"></i> Edit
                                    <?php endif; ?>
                                </div>
                            </a>
                        </div>

                        <div id="collapseOne" class="panel-collapse collapse">
                            <div class="panel-body">
                                <div class="row">
                                    <div class="col-md-7 col-lg-offset-2 text-center">
                                        <label class="col-md-4">Company Name</label>
                                        <div class="col-md-8">
                                            <input type="text" name="company_name" id="company_name" class="form-control"
                                            value="<?=(isset($s_company_name))?$s_company_name:null; ?>"/><br>
                                            <input type="hidden" name="save_type" id="save_type" value="<?=(empty($s_company_name[0]) || empty($s_company_name)) ? 'Save' : 'Update'; ?>">

                                            <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
                                                <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Save</button>
                                            <?php else: ?>
                                                <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Update</button>
                                            <?php endif; ?>
                                            <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

And your script will have to like this

<script>
    $(document).ready(function () {

        $('#data_form').on('submit', function (e) {
            e.preventDefault();
            var form_data = $(this).serialize();
            $.ajax({
                type: "POST",
                url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_company_insert_update',
                data: form_data,
                dataType: 'json',
                success: function (result)
                {
                    $(".aj-text").html(result.replace_text);
                    $(".aj-text-btn").html(result.btn_text);
                    $("#save_type").val(result.save_type);
                    $('#cname').text($("#company_name").val());
                },
                error: function ()
                {
                    alert('failed');
                }
            });
        });
    });
</script>

And replace your controller supplier_company_insert_update function as follow

public function supplier_company_insert_update() {

    $this->db->select('*');
    $this->db->from('supplier_otherdetails');
    $this->db->where('supplierid_fk', $this->session->id);
    $query = $this->db->get();
    $save_type = $this->input->post('save_type');
    $company_name = $this->input->post('company_name');

    if ($query->num_rows() > 0) {
        $this->Profile_model->update_supplier_company();
        //redirect('welcome/suppliercompany');
    } else {
        $this->Profile_model->insert_supplier_company();
        //redirect('welcome/suppliercompany');
    }

    if(trim($company_name)!='')
        echo json_encode(array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type));
    else
        echo json_encode(array('replace_text' => 'Save', 'btn_text' => 'Save', 'save_type' => $save_type));
}

Hope this will work for you. If is there any help let us know...


问:
How to send unquoted text as a parameter in Pyodbc?
Suppose I want to execute the following SQL statement using Pyodbc

```<code>Select col1 from Example_Table
</code>```

The column is initially unknown.So I am trying to send the column name as a parameter into the SQL statement.So i tried running the following statement.

```<code>Cursor.execute("Select ? from Example_Table",("col1",))
</code>```

But this is fetching something like this

```<code>[('col1',),('col1',),('col1',).....]
</code>```

Whenever I pass a string as a parameter it ends up with single quotation marks while querying(That's what I think is happening).I know that using %s instead of
? would be giving the results I want, but i can't use %s for my purposes.Is there any other way of doing this?

答:
You can always concat the same type in python. You can concat the variable in query string as below:</p>

```<code>Cursor.execute("Select "+ yourColumnVariable +" from Example_Table")
</code>```

Body:
Suppose I want to execute the following SQL statement using Pyodbc

Select col1 from Example_Table

The column is initially unknown.So I am trying to send the column name as a parameter into the SQL statement.So i tried running the following statement.

Cursor.execute("Select ? from Example_Table",("col1",))

But this is fetching something like this

[('col1',),('col1',),('col1',).....]

Whenever I pass a string as a parameter it ends up with single quotation marks while querying(That's what I think is happening).I know that using %s instead of
? would be giving the results I want, but i can't use %s for my purposes.Is there any other way of doing this?

Body:
You can always concat the same type in python. You can concat the variable in query string as below:

Cursor.execute("Select "+ yourColumnVariable +" from Example_Table")


问:
Identify empty string in Perl
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

```<code>foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}
</code>```

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

```<code>$name = Jim
$date = N/A
$size = small
</code>```

I hope this makes sense and is easy to fix.
-Thanks

答:
```<code>$name = "N/A" if (!defined($name) || ($name eq ""))
$date = "N/A" if (!defined($date) || ($date eq ""))
$size = "N/A" if (!defined($size) || ($size eq ""))
</code>```

Make sure you are using string comparison for comparing strings :)

Title: Identify empty string in Perl

Body:
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

$name = Jim
$date = N/A
$size = small

I hope this makes sense and is easy to fix.
-Thanks

Body:
$name = "N/A" if (!defined($name) || ($name eq ""))
$date = "N/A" if (!defined($date) || ($date eq ""))
$size = "N/A" if (!defined($size) || ($size eq ""))

Make sure you are using string comparison for comparing strings :)


问:
ElasticSearch count nested fields
How do you count objects of a nested field (which is a nested objects list) which meet a certain condition in ElasticSearch?

EXAMPLE

Having Customer index, with type Customer which has a Services nested field with following structure:

```<code>public class Customer
{
    public int Id;
    public List<Service> Services;
}

public class Service
{
    public int Id;
    public DateTime Date;
    public decimal Rating;
}
</code>```

How do I count all services which happened in June 2017 and got a rating higher than 5?

答:
Good question :)
In order to get what you want you should define your mapping upfront and nested property mapping works well.

The nested type is a specialized version of the object datatype that allows arrays of objects to be indexed and queried independently of each other.
https://www.elastic.co/guide/en/elasticsearch/reference/2.4/nested.html

Please find below full example :)

Mapping

```<code>PUT example_nested_test
{
  "mappings": {
    "nested": {
      "properties": {
        "Id": {
          "type": "long"
        },
        "Services": {
          "type": "nested",
          "properties": {
            "Id": {
              "type": "long"
            },
            "Date": {
              "type": "date"
            },
            "Rating": {
              "type": "long"
            }
          }
        }
      }
    }
  }
}
</code>```

POST Data

```<code>POST example_nested_test/nested/100
    {
      "Id" : 1,
      "Services": [
        {
          "Id": 1,
          "Date" :"2017-05-10",
          "Rating" : 5
        },
         {
          "Id": 2,
          "Date" :"2013-05-10",
          "Rating" : 2
        },
        {
          "Id": 4,
          "Date" :"2017-05-10",
          "Rating" : 6
        }]
    }
</code>```

Query

```<code>GET example_nested_test/_search
{
  "size":0,
  "aggs": {
    "Services": {
      "nested": {
        "path": "Services"
      },
      "aggs": {
        "Rating": {
          "filter": {
            "bool": {
              "must": [
                {
                  "range": {
                    "Services.Date": {
                      "gt": "2017",
                      "format": "yyyy"
                    }
                  }
                },
                {
                  "range": {
                    "Services.Rating": {
                      "gt": "5"
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
}
</code>```

Result :

```<code> "aggregations": {
    "Services": {
      "doc_count": 3,
      "Rating": {
        "doc_count": 1
      }
    }
  }
</code>```

Title: ElasticSearch count nested fields

Body:
How do you count objects of a nested field (which is a nested objects list) which meet a certain condition in ElasticSearch?

EXAMPLE

Having Customer index, with type Customer which has a Services nested field with following structure:

public class Customer
{
    public int Id;
    public List<Service> Services;
}

public class Service
{
    public int Id;
    public DateTime Date;
    public decimal Rating;
}

How do I count all services which happened in June 2017 and got a rating higher than 5?

Body:
Good question :)
In order to get what you want you should define your mapping upfront and nested property mapping works well.

The nested type is a specialized version of the object datatype that allows arrays of objects to be indexed and queried independently of each other.
https://www.elastic.co/guide/en/elasticsearch/reference/2.4/nested.html

Please find below full example :)

Mapping

PUT example_nested_test
{
  "mappings": {
    "nested": {
      "properties": {
        "Id": {
          "type": "long"
        },
        "Services": {
          "type": "nested",
          "properties": {
            "Id": {
              "type": "long"
            },
            "Date": {
              "type": "date"
            },
            "Rating": {
              "type": "long"
            }
          }
        }
      }
    }
  }
}

POST Data

POST example_nested_test/nested/100
    {
      "Id" : 1,
      "Services": [
        {
          "Id": 1,
          "Date" :"2017-05-10",
          "Rating" : 5
        },
         {
          "Id": 2,
          "Date" :"2013-05-10",
          "Rating" : 2
        },
        {
          "Id": 4,
          "Date" :"2017-05-10",
          "Rating" : 6
        }]
    }

Query

GET example_nested_test/_search
{
  "size":0,
  "aggs": {
    "Services": {
      "nested": {
        "path": "Services"
      },
      "aggs": {
        "Rating": {
          "filter": {
            "bool": {
              "must": [
                {
                  "range": {
                    "Services.Date": {
                      "gt": "2017",
                      "format": "yyyy"
                    }
                  }
                },
                {
                  "range": {
                    "Services.Rating": {
                      "gt": "5"
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
}

Result :

 "aggregations": {
    "Services": {
      "doc_count": 3,
      "Rating": {
        "doc_count": 1
      }
    }
  }

ContentLicense: CC BY-SA 4.0


问:
Windows 10 COMException HRESULT:0X800A03EC while saving Excel file
I have a VB.Net windows forms application which is working fine in windows 7 environment.

Now, I want to upgrade to windows 10. So I have started to test my application in windows 10 server machine.

I am getting an Exception (Exception from HRESULT:0X800A03EC) while saving a dynamically generated file in one of the folders on server.

I have identified the issue is not with the permissions.

```<code>'getting exception at this line of code.
xlApp.Workbooks(1).SaveAs(filename , xl.XlFileFormat.xlHtml)
</code>```

Code for reference:

```<code>Private Sub VierwInBrowser(ByVal xlApp As xl.Application)
    Dim fileName As String = String.Format("{0}\{1}", "C:\Data", GetUniqueFileName())
Try
    xlApp.Workbooks(1).SaveAs(fileName, xl.XlFileFormat.xlHtml)
Catch ex as Exception
Messagebox.Show(ex.Message)
End Try
    xlApp.Quit()
    xlApp = Nothing
    GC.Collect()
    browser.Visible = True
    browser.Navigate(fileName)
    browser.BringToFront()
End Sub
</code>```

答:
I have identified that the issue is with converting the excel sheet to html page in windows 10.

For this I have found a solution at https://support.microsoft.com/en-in/help/922850/error-message-in-office-when-a-file-is-blocked-by-registry-policy-sett

Body:
I have a VB.Net windows forms application which is working fine in windows 7 environment.

Now, I want to upgrade to windows 10. So I have started to test my application in windows 10 server machine.

I am getting an Exception (Exception from HRESULT:0X800A03EC) while saving a dynamically generated file in one of the folders on server.

I have identified the issue is not with the permissions.

'getting exception at this line of code.
xlApp.Workbooks(1).SaveAs(filename , xl.XlFileFormat.xlHtml)

Code for reference:

Private Sub VierwInBrowser(ByVal xlApp As xl.Application)
    Dim fileName As String = String.Format("{0}\{1}", "C:\Data", GetUniqueFileName())
Try
    xlApp.Workbooks(1).SaveAs(fileName, xl.XlFileFormat.xlHtml)
Catch ex as Exception
Messagebox.Show(ex.Message)
End Try
    xlApp.Quit()
    xlApp = Nothing
    GC.Collect()
    browser.Visible = True
    browser.Navigate(fileName)
    browser.BringToFront()
End Sub


问:
click button in activity 1 and if the button clicked show textview ... in activity 3
The Title is just a example. In my first Activity i have 2 buttons. If u hit the first Button (Button1) you will visit activity 2.1. But when you hit the second Button(Button2) you will visit Activity 2.2. In activity 3 its neccessary to know which Button the user hitted (Buttonenter code here2 or 1) because they will be different TextViews to show. So how show this different TextViews?

This Code is in Activity 3.

```<code> public void Button1 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

public void Button2 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText2);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}
</code>```

答:
On button click start activity and send data in intent.
Use Boolean flag to detect whether 1st button was clicked or not.

On First and Second Button click pass Boolean flag in Intent

```<code> Intent intent = new Intent(FirstActivity.this, ThirdActivity.class);
                intent.putExtra("BUTTON_1_CLICKED", true);
                startActivity(intent);
</code>```

In your 3rd Activity get clicked button flag using Bundle

```<code>if (extras != null) {
            Boolean value = extras.getBoolean("BUTTON_1_CLICKED", false);
           activity
        }
</code>```

Body:
The Title is just a example. In my first Activity i have 2 buttons. If u hit the first Button (Button1) you will visit activity 2.1. But when you hit the second Button(Button2) you will visit Activity 2.2. In activity 3 its neccessary to know which Button the user hitted (Buttonenter code here2 or 1) because they will be different TextViews to show. So how show this different TextViews?

This Code is in Activity 3.

 public void Button1 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

public void Button2 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText2);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

Body:
On button click start activity and send data in intent.
Use Boolean flag to detect whether 1st button was clicked or not.

On First and Second Button click pass Boolean flag in Intent

 Intent intent = new Intent(FirstActivity.this, ThirdActivity.class);
                intent.putExtra("BUTTON_1_CLICKED", true);
                startActivity(intent);

In your 3rd Activity get clicked button flag using Bundle

if (extras != null) {
            Boolean value = extras.getBoolean("BUTTON_1_CLICKED", false);
           activity
        }


问:
Loopback remoteMethod with onesignal push notification
i still learn, and trying to be learn. im looking for trying hard remote method on loopback 3 for push notification to specific user with onesignal.

any wrong in my code ?
because always :

Error: [ 'All included players are not subscribed' ]

My Case :

im using ionic 3 framework

loopback 3 (or latest)

2 User, (Customer & Seller)

Customer buying product from thread's seller.

If success to order, the seller will receive the notification.

and This is My code :

```<code>    Ajiorder.observe('after save', function (ctx, next) {
        console.log('Order', ctx.instance);
        let postingModel = app.models.AjiPosting;
        let userAuth = app.models.AjiUserAuth;

        postingModel.find({
            where:
            { id: ctx.instance.id }
        }, function (err, success) {
            console.log(success, 'SUKSES');
            if (ctx.instance) {
                let dataFilter = [];
                dataFilter.push({
                    'field': 'tag',
                    'key': 'id',
                    'relation': '=',
                    'value': success[0].id
                });
                console.log(success[0].idSeller, 'ID TOT')
                console.log(dataFilter, 'dataFilter');

                let data = {
                    idSeller: ctx.instance.idSeller
                }
                console.log(data, 'Data');
                userAuth.find({
                    where:
                    { id: ctx.instance.idCustomer }
                }, function (err, result) {
                    console.log(result, 'Data Personal');

                    let content = result[0].namaLengkap + ' ' + 'Order your product';
                    console.log(content, 'Nama Order');
                    console.log(ctx.instance.idSeller, 'My Dream', success[0].id);
                    if (ctx.instance.id != success[0].id) {
                        console.log('Spirit');
                        sendMessage(dataFilter, content, data);
                    }
                })
            }
            next();
        });
    });

    var sendMessage = function (device, message, data) {

        var restKey = 'XXXXXXXXXXXXXXXXXX';
        var appID = 'XXXXXXXXXXXXXXXXX';
        request(
            {
                method: 'POST',
                uri: 'https://onesignal.com/api/v1/notifications',
                headers: {
                    'authorization': 'Basic ' + restKey,
                    'content-type': 'application/json'
                },
                json: true,
                body: {
                    'app_id': appID,
                    'filters': device,
                    'data': data,
                    'contents': { en: message }
                }
            },
            function (error, response, body) {
                try {
                    if (!body.errors) {
                        console.log(body);
                    } else {
                        console.error('Error:', body.errors);
                    }
                } catch (err) {
                    console.log(err);
                }

            }
        )
    }
};
</code>```

and i got this error :

Error: [ 'All included players are not subscribed' ]

Picture : Picture of Console Log Here

any one can help me ?
sorry for my english too bad.

Greetings

答:
Solved !

I'm Forget to add some code from onesignal. thanks

Body:
i still learn, and trying to be learn. im looking for trying hard remote method on loopback 3 for push notification to specific user with onesignal.

any wrong in my code ?
because always :

Error: [ 'All included players are not subscribed' ]

My Case :

im using ionic 3 framework

loopback 3 (or latest)

2 User, (Customer & Seller)

Customer buying product from thread's seller.

If success to order, the seller will receive the notification.

and This is My code :

    Ajiorder.observe('after save', function (ctx, next) {
        console.log('Order', ctx.instance);
        let postingModel = app.models.AjiPosting;
        let userAuth = app.models.AjiUserAuth;

        postingModel.find({
            where:
            { id: ctx.instance.id }
        }, function (err, success) {
            console.log(success, 'SUKSES');
            if (ctx.instance) {
                let dataFilter = [];
                dataFilter.push({
                    'field': 'tag',
                    'key': 'id',
                    'relation': '=',
                    'value': success[0].id
                });
                console.log(success[0].idSeller, 'ID TOT')
                console.log(dataFilter, 'dataFilter');

                let data = {
                    idSeller: ctx.instance.idSeller
                }
                console.log(data, 'Data');
                userAuth.find({
                    where:
                    { id: ctx.instance.idCustomer }
                }, function (err, result) {
                    console.log(result, 'Data Personal');

                    let content = result[0].namaLengkap + ' ' + 'Order your product';
                    console.log(content, 'Nama Order');
                    console.log(ctx.instance.idSeller, 'My Dream', success[0].id);
                    if (ctx.instance.id != success[0].id) {
                        console.log('Spirit');
                        sendMessage(dataFilter, content, data);
                    }
                })
            }
            next();
        });
    });

    var sendMessage = function (device, message, data) {

        var restKey = 'XXXXXXXXXXXXXXXXXX';
        var appID = 'XXXXXXXXXXXXXXXXX';
        request(
            {
                method: 'POST',
                uri: 'https://onesignal.com/api/v1/notifications',
                headers: {
                    'authorization': 'Basic ' + restKey,
                    'content-type': 'application/json'
                },
                json: true,
                body: {
                    'app_id': appID,
                    'filters': device,
                    'data': data,
                    'contents': { en: message }
                }
            },
            function (error, response, body) {
                try {
                    if (!body.errors) {
                        console.log(body);
                    } else {
                        console.error('Error:', body.errors);
                    }
                } catch (err) {
                    console.log(err);
                }

            }
        )
    }
};

and i got this error :

Error: [ 'All included players are not subscribed' ]

Picture : Picture of Console Log Here

any one can help me ?
sorry for my english too bad.

Greetings


问:
iPhone background network connection by timer
I need to write an application, that every 10 minutes it should be awaken from suspended mode, get user location via gps and send this information to the server by network.

Depending on the response it should return to the suspended mode or show local notification to the user.

Is there a way to do this on iOS 4?
I've tried different approaches, but the only working for me was to start monitoring user location in backgroind and declare the application as location background application. In that case it worked in background and has a network connection. But this approach takes a lot of power and not accepted cause application should work 24/7.

May be there is a way to write some daemon that should work in background and wake my application every 10 minutes?

答:
App store friendly: use new APIs in iOS4, which allows u to make use of GPS location

Anti App store: create a daemon by adding a specific plist file to  System/Library/LaunchDaemons/ and put ur app under Applications/. this approach requires a jailbroken iPhone however...

detailed information plz google the following keywords: daemon, multitask, background, etc...

cheers, Lloyd


问:
Android Project not resolve gradle
I am using android studio and i updated it from 2.3 to 2.3.3 and after when i am trying to open a existing project it is not gradlling. Here is my Application base build gradle file where i use dependencies like this...

```<code>dependencies {
     classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
}
</code>```

In my gradle-wrapper.properties i have mention like this...

```<code>#Mon Jul 03 12:12:51 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
</code>```

In My file>setting>gradle....

答:
Follow the steps :

Go to your Project structure

Click on project on left side panel

Update the Gradle version to 3.3

Click on Ok Button

let it sync and you will be done

Title: Android Project not resolve gradle

Body:
I am using android studio and i updated it from 2.3 to 2.3.3 and after when i am trying to open a existing project it is not gradlling. Here is my Application base build gradle file where i use dependencies like this...

dependencies {
     classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
}

In my gradle-wrapper.properties i have mention like this...

#Mon Jul 03 12:12:51 IST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

In My file>setting>gradle....


问:
Shell Script output contains multiple words
I am trying to create a script in which I am running a command which gives a output. I am interested in few words in the output, I am using following script:

```<code>cfservices=$(cf services)<br/>
if [[ $cfservices == *"postgres...."* ]]; then<br/>
echo " done "<br/>
else<br/>
echo " fail "
</code>```

but this helps find only one word. Please help me find multiple words.

答:
You could use grep to find both:</p>

```<code>cf services | grep postgres | grep mongo
if [[ $? == 0 ]]; then
  echo " done"
else
  echo " fail "
fi
</code>```

Body:
I am trying to create a script in which I am running a command which gives a output. I am interested in few words in the output, I am using following script:

cfservices=$(cf services)

if [[ $cfservices == *"postgres...."* ]]; then

echo " done "

else

echo " fail "

but this helps find only one word. Please help me find multiple words.

Body:
You could use grep to find both:

cf services | grep postgres | grep mongo
if [[ $? == 0 ]]; then
  echo " done"
else
  echo " fail "
fi


问:
printing a texture2D to file or as image for debugging purposes
I am trying to figure out how an image is processed (what it looks like, etc...) at several stages of Image Processing operations, so I have written the following co-routine to capture a screenshot, but I am not sure how to print out the taken shots at different stages (for example as png images)

```<code>public void CaptureFrame(RectTransform rect)
{
    StartCoroutine( Co_Capture(rect) );
}

private IEnumerator Co_Capture(RectTransform rect)
{
    yield return new WaitForEndOfFrame();

    _texture = new Texture2D( (int)rect.sizeDelta.x, (int)rect.sizeDelta.y );
    _texture.ReadPixels( new Rect( rect.anchoredPosition.x - (rect.sizeDelta.x * 0.5f), rect.anchoredPosition.y - (rect.sizeDelta.y * 0.5f), rect.sizeDelta.x, rect.sizeDelta.y ), 0, 0 );
    _texture.Apply();

    OnImageCaptured( new ScreenShotEventArgs(_texture) );
}
</code>```

Given that I build the app to an Android device, ideally I would like to have the images saved both in a folder somewhere (through Unity3D Editor) as well as on the device in its data folder, for example. Something akin to Debug.Log messages that you print out at different stages to see which parts of your code are reached, etc...

What options do I have? What is the code/command/method for saving an image/picture through Unity3D and also on an Android tablet, so that the developer can see the images at various stages or processing?

答:
You got some of it right in the comment section. You use EncodeToPNG() to convert it to a byte array then save it with File.WriteAllBytes. What you didn't get right is the path.

You use save to Application.persistentDataPath if you want that to work on Android, iOS and any platform. It is a must to save it in a folder instead of directly saving it to Application.persistentDataPath.

So that should be Application.persistentDataPath+"/yourfoldername/imagename.png".

Again, this: Application.persistentDataPath+"/imagename.png" will fail on iOS because you are trying to write directly to the sandbox which requires a folder like I mentioned above.

Finally, I noticed you are using + to concatenate paths. Avoid doing that and instead use Path.Combine.

```<code>string tempPath = Path.Combine(Application.persistentDataPath, "yourfoldername");
tempPath = Path.Combine(tempPath, "yourfoldername.png");
</code>```

Body:
I am trying to figure out how an image is processed (what it looks like, etc...) at several stages of Image Processing operations, so I have written the following co-routine to capture a screenshot, but I am not sure how to print out the taken shots at different stages (for example as png images)

public void CaptureFrame(RectTransform rect)
{
    StartCoroutine( Co_Capture(rect) );
}

private IEnumerator Co_Capture(RectTransform rect)
{
    yield return new WaitForEndOfFrame();

    _texture = new Texture2D( (int)rect.sizeDelta.x, (int)rect.sizeDelta.y );
    _texture.ReadPixels( new Rect( rect.anchoredPosition.x - (rect.sizeDelta.x * 0.5f), rect.anchoredPosition.y - (rect.sizeDelta.y * 0.5f), rect.sizeDelta.x, rect.sizeDelta.y ), 0, 0 );
    _texture.Apply();

    OnImageCaptured( new ScreenShotEventArgs(_texture) );
}

Given that I build the app to an Android device, ideally I would like to have the images saved both in a folder somewhere (through Unity3D Editor) as well as on the device in its data folder, for example. Something akin to Debug.Log messages that you print out at different stages to see which parts of your code are reached, etc...

What options do I have? What is the code/command/method for saving an image/picture through Unity3D and also on an Android tablet, so that the developer can see the images at various stages or processing?

Body:
You got some of it right in the comment section. You use EncodeToPNG() to convert it to a byte array then save it with File.WriteAllBytes. What you didn't get right is the path.

You use save to Application.persistentDataPath if you want that to work on Android, iOS and any platform. It is a must to save it in a folder instead of directly saving it to Application.persistentDataPath.

So that should be Application.persistentDataPath+"/yourfoldername/imagename.png".

Again, this: Application.persistentDataPath+"/imagename.png" will fail on iOS because you are trying to write directly to the sandbox which requires a folder like I mentioned above.

Finally, I noticed you are using + to concatenate paths. Avoid doing that and instead use Path.Combine.

string tempPath = Path.Combine(Application.persistentDataPath, "yourfoldername");
tempPath = Path.Combine(tempPath, "yourfoldername.png");


问:
Filter log file entries based on date range
My server is having unusually high CPU usage, and I can see Apache is using way too much memory.
I have a feeling, I'm being DOS'd by a single IP - maybe you can help me find the attacker?

I've used the following line, to find the 10 most "active" IPs:

```<code>cat access.log | awk '{print $1}' |sort  |uniq -c |sort -n |tail
</code>```

The top 5 IPs have about 200 times as many requests to the server, as the "average" user. However, I can't find out if these 5 are just very frequent visitors, or they are attacking the servers.

Is there are way, to specify the above search to a time interval, eg. the last two hours OR between 10-12 today?

Cheers!

UPDATED 23 OCT 2011 - The commands I needed:

Get entries within last X hours [Here two hours]

```<code>awk -vDate=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print Date FS $4}' access.log
</code>```

Get most active IPs within the last X hours [Here two hours]

```<code>awk -vDate=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print $1}' access.log | sort  |uniq -c |sort -n | tail
</code>```

Get entries within relative timespan

```<code>awk -vDate=`date -d'now-4 hours' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print Date FS Date2 FS $4}' access.log
</code>```

Get entries within absolute timespan

```<code>awk -vDate=`date -d '13:20' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'13:30' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print $0}' access.log
</code>```

Get most active IPs within absolute timespan

```<code>awk -vDate=`date -d '13:20' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'13:30' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print $1}' access.log | sort  |uniq -c |sort -n | tail
</code>```

答:
If someone encounters with the awk: invalid -v option, here's a script to get the most active IPs in a predefined time range:

```<code>cat <FILE_NAME> | awk '$4 >= "[04/Jul/2017:07:00:00" && $4 < "[04/Jul/2017:08:00:00"' | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -20
</code>```

Body:
My server is having unusually high CPU usage, and I can see Apache is using way too much memory.
I have a feeling, I'm being DOS'd by a single IP - maybe you can help me find the attacker?

I've used the following line, to find the 10 most "active" IPs:

cat access.log | awk '{print $1}' |sort  |uniq -c |sort -n |tail

The top 5 IPs have about 200 times as many requests to the server, as the "average" user. However, I can't find out if these 5 are just very frequent visitors, or they are attacking the servers.

Is there are way, to specify the above search to a time interval, eg. the last two hours OR between 10-12 today?

Cheers!

UPDATED 23 OCT 2011 - The commands I needed:

Get entries within last X hours [Here two hours]

awk -vDate=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print Date FS $4}' access.log

Get most active IPs within the last X hours [Here two hours]

awk -vDate=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print $1}' access.log | sort  |uniq -c |sort -n | tail

Get entries within relative timespan

awk -vDate=`date -d'now-4 hours' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'now-2 hours' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print Date FS Date2 FS $4}' access.log

Get entries within absolute timespan

awk -vDate=`date -d '13:20' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'13:30' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print $0}' access.log

Get most active IPs within absolute timespan

awk -vDate=`date -d '13:20' +[%d/%b/%Y:%H:%M:%S` -vDate2=`date -d'13:30' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date && $4 < Date2) print $1}' access.log | sort  |uniq -c |sort -n | tail

Body:
If someone encounters with the awk: invalid -v option, here's a script to get the most active IPs in a predefined time range:

cat <FILE_NAME> | awk '$4 >= "[04/Jul/2017:07:00:00" && $4 < "[04/Jul/2017:08:00:00"' | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -20


问:
In app purchase is not working now but it work in past in objective c
In app purchase is not working now but it work in past in objective c.
It works perfectly in past but now it does not show any details of the product name price. Please some one give some solution.

Here i sending my code

```<code>- (void)viewDidLoad
{
NSLog(@"%@",entityid);
[super viewDidLoad];
purchasedItemIDs=[[NSMutableArray alloc]init];

self.navigationController.navigationBar.hidden=YES;
self.navigationItem.leftBarButtonItem = nil;
if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone){
    [self restrictRotation:YES];
}
else{
    [self restrictRotation:YES];
}
[self translation];

activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(157*scalex, 170*scaley, 20, 20)];
[activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[activityIndicatorView setColor:[UIColor grayColor]];
[self.view addSubview:activityIndicatorView];
CGAffineTransform transform;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
      transform = CGAffineTransformMakeScale(.85f, .85f);
}
else
{
      transform = CGAffineTransformMakeScale(1.5f, 1.5f);
}
activityIndicatorView.transform = transform;
[activityIndicatorView startAnimating];

_v2.hidden=YES;
_price.hidden=YES;
_productPriceLabel.hidden=YES;
_productTitleLabel.hidden=YES;
_productDescriptionLabel.hidden=YES;
_purchaseButton.hidden = YES;
_viewdetails.layer.cornerRadius=5.0;
[self fetchAvailableProducts];
}

 -(void)fetchAvailableProducts{
 NSLog(@"%@",entityid);
 if ([SKPaymentQueue canMakePayments])
 {
    SKProductsRequest *request = [[SKProductsRequest alloc]
                                  initWithProductIdentifiers:
                                  [NSSet setWithObject:entityid]];
    request.delegate = self;
    [request start];
 }
 else{
    _productDescriptionLabel.text =
    @"Please enable In App Purchase in Settings";
 }

}
-(void)translation{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    if( screenHeight == 568&&screenWidth==320  ){
        scaley=1.183;
        scalex=1.0;
    } else if ( screenWidth==375&&screenHeight==667 ){

        scalex=1.171;
        scaley=1.39;

    } else if (screenWidth==540&&screenHeight==960 ){
        scaley=2.0;
        scalex=1.168;

    } else {
        scalex=1.0;
        scaley=1.0;

    }

}
else{
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    if(screenWidth>screenHeight){
        scaley=1.6;
        scalex=3.2;

    }
    else if(screenWidth<screenHeight){
        scalex=2.4;
        scaley=2.133;
    }

}

}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{

NSLog(@"%@",response);

NSArray *products = response.products;

NSLog(@"%@",products);

if (products.count != 0)
{

    NSLog(@"%@",products);
    product = [response.products objectAtIndex:0];
    NSLocale *priceLocale = product.priceLocale;
    NSDecimalNumber *price = product.price;
    NSString *description = product.localizedDescription;
    //validProducts = [products objectAtIndex:0];
    _purchaseButton.enabled = YES;
    _productTitleLabel.text = product.localizedTitle;
    [_productTitleLabel sizeToFit];
    _productDescriptionLabel.text = description;

     CGFloat rr=[self heightForText:description];
    _productDescriptionLabel.frame=CGRectMake(_productDescriptionLabel.frame.origin.x,_productDescriptionLabel.frame.origin.y, _productDescriptionLabel.frame.size.width, rr);

    _v2.frame=CGRectMake(_v2.frame.origin.x,_productDescriptionLabel.frame.origin.y+rr+10, _v2.frame.size.width, _v2.frame.size.height);

    _price.frame=CGRectMake(_price.frame.origin.x,_v2.frame.origin.y+5, _v2.frame.size.width, _price.frame.size.height);

    _productPriceLabel.frame=CGRectMake(_productPriceLabel.frame.origin.x,_v2.frame.origin.y+5, _productPriceLabel.frame.size.width, _productPriceLabel.frame.size.height);
    _productDescriptionLabel.numberOfLines=rr/10.0;
    NSString *rupree=[priceLocale objectForKey:NSLocaleCurrencySymbol];
    rupree1=[priceLocale objectForKey:NSLocaleCurrencyCode];
    NSString *ui=[rupree stringByAppendingString:[price stringValue]];
    _productPriceLabel.text=ui;
    rup=[price stringValue];
    _v2.hidden=NO;
    _price.hidden=NO;
    _productPriceLabel.hidden=NO;
    _productTitleLabel.hidden=NO;
    _productDescriptionLabel.hidden=NO;
} else {
     _productTitleLabel.text = @"Product not found";
}}

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
  for (SKPaymentTransaction *transaction in transactions)
 {
    switch (transaction.transactionState) {
        case SKPaymentTransactionStatePurchased:{

            NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];

            if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]])
            {
              //  NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
                //NSString *receiptStr = [receiptData base64EncodedStringWithOptions:0];
                //NSLog(@"%@",receiptStr);
            }

           // if (hasAddObserver==YES) {
           if(![purchasedItemIDs containsObject:idf]){
                [[SKPaymentQueue defaultQueue]
                 finishTransaction:transaction];
            // NSString *email=[_email text];
            NSString *escapedString = [email stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
            NSString *post =[[NSString alloc] initWithFormat:@"email=%@",escapedString];
           idf=entityid;

            NSString *post5=[[NSString alloc] initWithFormat:@"&price=%@",rup];
            NSString *post6=[[NSString alloc] initWithFormat:@"&pricecode=%@",rupree1];
            NSString *post4;
            if ([idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew30"]||[idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew76"]||[idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew34"]){
                 post4=[idf stringByReplacingOccurrencesOfString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew" withString:@""];

            }
             else{
                 post4=[idf stringByReplacingOccurrencesOfString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.price" withString:@""];
            }
            NSString *post1=[[NSString alloc] initWithFormat:@"&id=%@",post4];
            NSString *post3=[post stringByAppendingString:post1];
            NSString *post51=[post5 stringByAppendingString:post6];
                NSLog(@"%@",post4);
            NSString *post511=[post3 stringByAppendingString:post51];
            NSString *url1=@"http://learn.onlinebusinessschool.com/learn-app/order-assessment.php?";
            NSString *hostStr = [url1 stringByAppendingString:post511];
            NSURL *url=[NSURL URLWithString:hostStr];
            NSLog(@"%@",url);
            NSData *postData = [post511 dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            NSError *error = nil;
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if ([response statusCode] >=200 && [response statusCode] <300)
            {
                NSData *responseData1 = [[NSData alloc]initWithData:urlData];
                NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData1 options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"new=%@",jsonObject);
                orderid1=[jsonObject objectForKey:@"invoiceId"];
                purchasedetails *mvc;

                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

                    mvc = [[UIStoryboard storyboardWithName:@"iPad_storyboard" bundle:nil]instantiateViewControllerWithIdentifier:@"purchasedetails"];
                }
                else{
                    mvc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"purchasedetails"];
                }
                mvc.name=name;
                mvc.email=email;
                mvc.customer_id=customer_id;
                mvc.password=password;
                mvc.entitytype=idf;

                mvc.label21=label3;
                mvc.coursetype=label1;
                mvc.orderid1=orderid1;
                mvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [self.navigationController pushViewController:mvc animated:YES];

            }
            }
            for (SKPaymentTransaction *transaction in queue.transactions)
            {
                NSString *productID = transaction.payment.productIdentifier;
                [purchasedItemIDs addObject:productID];
                NSLog(@"%@",purchasedItemIDs);
            }
            [activityIndicatorView stopAnimating];

            [self unlockFeature];

        }
        //}
            break;
         case SKPaymentTransactionStateFailed:
            NSLog(@"Transaction Failed");
             [self displayAlertViewWithMessage:@"Wait! transaction is failed ....."];
            [[SKPaymentQueue defaultQueue]
             finishTransaction:transaction];
            [activityIndicatorView stopAnimating];

            break;
        case SKPaymentTransactionStateRestored: {

            break;
        }
         case SKPaymentTransactionStatePurchasing: {
             //[//[SKPaymentQueue defaultQueue]finishTransaction:transaction];
            // currently purchasing
           // [self displayAlertViewWithMessage:@"Wait! Purchasing ....."];

             activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(157*scalex, 150*scaley, 20, 20)];
             [activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
             [activityIndicatorView setColor:[UIColor grayColor]];
             [self.view addSubview:activityIndicatorView];
             CGAffineTransform transform;
             if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
                 transform = CGAffineTransformMakeScale(.75f, .75f);
             }
             else{
                 transform = CGAffineTransformMakeScale(1.5f, 1.5f);
             }
             activityIndicatorView.transform = transform;
             [activityIndicatorView startAnimating];
            break;
        }

        default:
            break;
    }
}
}
</code>```

答:
Solution: Fix your code.

Seriously, this could be anything from your server misbehaving, to the in-app purchase being registered incorrectly at Apple, to your code only working by coincidence in the first place.

Just start debugging your code. Or go back to previous versions in your source code control, see if it is working there, and check what is the first version that fails and what you changed in that version.

Body:
In app purchase is not working now but it work in past in objective c.
It works perfectly in past but now it does not show any details of the product name price. Please some one give some solution.

Here i sending my code

- (void)viewDidLoad
{
NSLog(@"%@",entityid);
[super viewDidLoad];
purchasedItemIDs=[[NSMutableArray alloc]init];

self.navigationController.navigationBar.hidden=YES;
self.navigationItem.leftBarButtonItem = nil;
if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone){
    [self restrictRotation:YES];
}
else{
    [self restrictRotation:YES];
}
[self translation];

activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(157*scalex, 170*scaley, 20, 20)];
[activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[activityIndicatorView setColor:[UIColor grayColor]];
[self.view addSubview:activityIndicatorView];
CGAffineTransform transform;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
      transform = CGAffineTransformMakeScale(.85f, .85f);
}
else
{
      transform = CGAffineTransformMakeScale(1.5f, 1.5f);
}
activityIndicatorView.transform = transform;
[activityIndicatorView startAnimating];

_v2.hidden=YES;
_price.hidden=YES;
_productPriceLabel.hidden=YES;
_productTitleLabel.hidden=YES;
_productDescriptionLabel.hidden=YES;
_purchaseButton.hidden = YES;
_viewdetails.layer.cornerRadius=5.0;
[self fetchAvailableProducts];
}

 -(void)fetchAvailableProducts{
 NSLog(@"%@",entityid);
 if ([SKPaymentQueue canMakePayments])
 {
    SKProductsRequest *request = [[SKProductsRequest alloc]
                                  initWithProductIdentifiers:
                                  [NSSet setWithObject:entityid]];
    request.delegate = self;
    [request start];
 }
 else{
    _productDescriptionLabel.text =
    @"Please enable In App Purchase in Settings";
 }

}
-(void)translation{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    if( screenHeight == 568&&screenWidth==320  ){
        scaley=1.183;
        scalex=1.0;
    } else if ( screenWidth==375&&screenHeight==667 ){

        scalex=1.171;
        scaley=1.39;

    } else if (screenWidth==540&&screenHeight==960 ){
        scaley=2.0;
        scalex=1.168;

    } else {
        scalex=1.0;
        scaley=1.0;

    }

}
else{
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    if(screenWidth>screenHeight){
        scaley=1.6;
        scalex=3.2;

    }
    else if(screenWidth<screenHeight){
        scalex=2.4;
        scaley=2.133;
    }

}

}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{

NSLog(@"%@",response);

NSArray *products = response.products;

NSLog(@"%@",products);

if (products.count != 0)
{

    NSLog(@"%@",products);
    product = [response.products objectAtIndex:0];
    NSLocale *priceLocale = product.priceLocale;
    NSDecimalNumber *price = product.price;
    NSString *description = product.localizedDescription;
    //validProducts = [products objectAtIndex:0];
    _purchaseButton.enabled = YES;
    _productTitleLabel.text = product.localizedTitle;
    [_productTitleLabel sizeToFit];
    _productDescriptionLabel.text = description;

     CGFloat rr=[self heightForText:description];
    _productDescriptionLabel.frame=CGRectMake(_productDescriptionLabel.frame.origin.x,_productDescriptionLabel.frame.origin.y, _productDescriptionLabel.frame.size.width, rr);

    _v2.frame=CGRectMake(_v2.frame.origin.x,_productDescriptionLabel.frame.origin.y+rr+10, _v2.frame.size.width, _v2.frame.size.height);

    _price.frame=CGRectMake(_price.frame.origin.x,_v2.frame.origin.y+5, _v2.frame.size.width, _price.frame.size.height);

    _productPriceLabel.frame=CGRectMake(_productPriceLabel.frame.origin.x,_v2.frame.origin.y+5, _productPriceLabel.frame.size.width, _productPriceLabel.frame.size.height);
    _productDescriptionLabel.numberOfLines=rr/10.0;
    NSString *rupree=[priceLocale objectForKey:NSLocaleCurrencySymbol];
    rupree1=[priceLocale objectForKey:NSLocaleCurrencyCode];
    NSString *ui=[rupree stringByAppendingString:[price stringValue]];
    _productPriceLabel.text=ui;
    rup=[price stringValue];
    _v2.hidden=NO;
    _price.hidden=NO;
    _productPriceLabel.hidden=NO;
    _productTitleLabel.hidden=NO;
    _productDescriptionLabel.hidden=NO;
} else {
     _productTitleLabel.text = @"Product not found";
}}

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
  for (SKPaymentTransaction *transaction in transactions)
 {
    switch (transaction.transactionState) {
        case SKPaymentTransactionStatePurchased:{

            NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];

            if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]])
            {
              //  NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
                //NSString *receiptStr = [receiptData base64EncodedStringWithOptions:0];
                //NSLog(@"%@",receiptStr);
            }

           // if (hasAddObserver==YES) {
           if(![purchasedItemIDs containsObject:idf]){
                [[SKPaymentQueue defaultQueue]
                 finishTransaction:transaction];
            // NSString *email=[_email text];
            NSString *escapedString = [email stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
            NSString *post =[[NSString alloc] initWithFormat:@"email=%@",escapedString];
           idf=entityid;

            NSString *post5=[[NSString alloc] initWithFormat:@"&price=%@",rup];
            NSString *post6=[[NSString alloc] initWithFormat:@"&pricecode=%@",rupree1];
            NSString *post4;
            if ([idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew30"]||[idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew76"]||[idf isEqualToString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew34"]){
                 post4=[idf stringByReplacingOccurrencesOfString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.pricenew" withString:@""];

            }
             else{
                 post4=[idf stringByReplacingOccurrencesOfString:@"com.onlinebusinessschool.com.OnlineBusinessSchool.price" withString:@""];
            }
            NSString *post1=[[NSString alloc] initWithFormat:@"&id=%@",post4];
            NSString *post3=[post stringByAppendingString:post1];
            NSString *post51=[post5 stringByAppendingString:post6];
                NSLog(@"%@",post4);
            NSString *post511=[post3 stringByAppendingString:post51];
            NSString *url1=@"http://learn.onlinebusinessschool.com/learn-app/order-assessment.php?";
            NSString *hostStr = [url1 stringByAppendingString:post511];
            NSURL *url=[NSURL URLWithString:hostStr];
            NSLog(@"%@",url);
            NSData *postData = [post511 dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            NSError *error = nil;
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if ([response statusCode] >=200 && [response statusCode] <300)
            {
                NSData *responseData1 = [[NSData alloc]initWithData:urlData];
                NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData1 options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"new=%@",jsonObject);
                orderid1=[jsonObject objectForKey:@"invoiceId"];
                purchasedetails *mvc;

                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

                    mvc = [[UIStoryboard storyboardWithName:@"iPad_storyboard" bundle:nil]instantiateViewControllerWithIdentifier:@"purchasedetails"];
                }
                else{
                    mvc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"purchasedetails"];
                }
                mvc.name=name;
                mvc.email=email;
                mvc.customer_id=customer_id;
                mvc.password=password;
                mvc.entitytype=idf;

                mvc.label21=label3;
                mvc.coursetype=label1;
                mvc.orderid1=orderid1;
                mvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [self.navigationController pushViewController:mvc animated:YES];

            }
            }
            for (SKPaymentTransaction *transaction in queue.transactions)
            {
                NSString *productID = transaction.payment.productIdentifier;
                [purchasedItemIDs addObject:productID];
                NSLog(@"%@",purchasedItemIDs);
            }
            [activityIndicatorView stopAnimating];

            [self unlockFeature];

        }
        //}
            break;
         case SKPaymentTransactionStateFailed:
            NSLog(@"Transaction Failed");
             [self displayAlertViewWithMessage:@"Wait! transaction is failed ....."];
            [[SKPaymentQueue defaultQueue]
             finishTransaction:transaction];
            [activityIndicatorView stopAnimating];

            break;
        case SKPaymentTransactionStateRestored: {

            break;
        }
         case SKPaymentTransactionStatePurchasing: {
             //[//[SKPaymentQueue defaultQueue]finishTransaction:transaction];
            // currently purchasing
           // [self displayAlertViewWithMessage:@"Wait! Purchasing ....."];

             activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(157*scalex, 150*scaley, 20, 20)];
             [activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
             [activityIndicatorView setColor:[UIColor grayColor]];
             [self.view addSubview:activityIndicatorView];
             CGAffineTransform transform;
             if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
                 transform = CGAffineTransformMakeScale(.75f, .75f);
             }
             else{
                 transform = CGAffineTransformMakeScale(1.5f, 1.5f);
             }
             activityIndicatorView.transform = transform;
             [activityIndicatorView startAnimating];
            break;
        }

        default:
            break;
    }
}
}