text:
Q: Virtual Console for Web App Using Websockets I have a WCF Service which is hosted by a Windows Service. It can also run as a console program when a command argument is present. It has one interface that employs MSMQIntegrationBinding, and another that binds to HTTP for service utility methods. This works well.  I have a web application (written for IE 11) that lets the user monitor the service, and perform the utility methods. There are many Console.WriteLines in the code that obviously don't display if the code is running as a service.
My boss has now requested that he be able to view the service in action in a console, like it were running as a console app. I would like to add a new virtual console window to my web app that would just display new Console.WriteLines as they occur on the server. I was thinking I could write a function in my wcf service that would accept the message as a string, do a Console.WriteLine, and then push out the message to any listening clients like my web app console window. I'm thinking of using javascript on the client.
I've read about using Websockets with netHttpBinding for a WCF service and that's the approach I would like to take.  However, the examples I see seem to be bi-directional, like chat windows (http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-4-5-Part-3) that just echo back a message to the client.  I want one way server-to-client messaging. Can somebody help? Here's my latest code try:
IWMLogger.VB
<ServiceContract(CallbackContract:=GetType(IWMLogger_MessageCallback))>
Public Interface IWMLogger_ClientListener
    <OperationContract(IsOneWay:=True)>
    Function ListenForServerMessages() As Task
End Interface

<ServiceContract>
Interface IWMLogger_MessageCallback
    <OperationContract(IsOneWay:=True)>
    Function SendMessageToClient(ByVal msg As String) As Task
End Interface

WMLogger.VB
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.Single)> _
Public Class WMLogger_Service
Implements IWMLogger_Service, IWMLogger_Service_MSMQ, IWMLogger_ClientListener

    Public Async Function ListenForServerMessages() As Task Implements IWMLogger_ClientListener.ListenForServerMessages
        Dim callback = OperationContext.Current.GetCallbackChannel(Of IWMLogger_MessageCallback)()
        If DirectCast(callback, IChannel).State = CommunicationState.Opened Then
            'Not sure what to do here
            'Await callback.SendMessageToClient(
        End If
    End Function
End Class

A: Have you looked into SignalR? Personally I would go this route, having the console app running on your web server register to the same SignalR hub as the clients (i.e. your web app will host the SignalR hub). Then use the console app to push the messages to the SignalR hub on your web app, which will relay them to all listening clients (given the correct setup).
The disadvantage the WCF route has is the usual configuration nightmare, certainly possible - but in my option not as straight forward as SignalR.
Have you seen the following stack overflow question for a good comparison between WCF and SignalR Push data to client using SignalR vs WCF?
There is some great tutorials for this over at http://www.asp.net/signalr

A: I ended up going with a SignalR solution that finally worked. I think it might be a bit of overkill, but I am just glad it works.
Please see my answer at: WCF SSE via SignalR
Thanks for all the suggestions.


text:
Q: Why is my AngularFire push( ) not working? I'm trying to learn Angular with Firebase by running through a typical to-do tutorial, but I'm sort of modifying the app as I go. Instead of list of to-dos, I'm actually creating 'Users'.
Firebase is set up correctly, pulling object data down from Firebase works as well and I can see everything populating as expected via ng-repeat.
But I'm trying to 'add a new member' using the .push() method, and I'm receiving an error. Please take a look:
Here's an example of the JSON data that I uploaded to Firebase (just one user)
{
  "members": {
    "-JWT5y43YFy1mGirVVS2": {
    "date": 1410328158691,
    "firstname": "Michael",
    "lastname": "Jordan",
    "project": "sample project description",
    "image": "http://telehealth.org/wp-content/images/user-placeholder.jpg",
    "upcoming": "PTO on Thursday",
    "status": {
      "color":  "red",
      "contact": {
      "email": "test@email.com",
      "yahoo": "yahooIM"
        },
      "projects": {
        "projectone": "project one",
        "projecttwo": "project two",
        "projectthree": "project three"
        }
      }
    }
  }
}

Here's my .html code

Team Members

add member

    <form class="formmember"
        name="memberform"
        ng-submit="addMember()"
        novalidate>

                <input type="text" name="firstname" placeholder"First Name" ng-required="true">
                <button type="submit" class="btn"
                ng-disabled="memberform.$invalid">Add</button>

    </form>

{{member.firstname}}

            <button>View</button>

And here's my Controller.js
myApp.controller('MembersController', function($scope, $firebase){

var ref = new Firebase('https://scrumcheck.firebaseio.com/members');
var members = $firebase(ref);

$scope.members = members.$asObject();

$scope.addMember = function(){
    members.$push({
        firstname: $scope.firstname,
        date: Firebase.ServerValue.TIMESTAMP
    });
}

});

The console log shows this error:
 Error: Firebase.set failed: First argument contains undefined in property 'firstname'

I was hoping that by pushing to Members, an object with just the firstname key, it would allow me to do so. Am I only allowed push() an entire object, with all key-values in it?
Thanks!

A: Checkout your $scope.firstname model, that's where the issue is. make sure it's not a null value and properly defined.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting collection's linklist to then get the handle to compare to main-menu in shopify Say this is my navigational structure in shopify:

*

*Shoes

*

*Flats

*Sandals

*Bags
Currently I've gotten a fairly simple navigational component working, where if you're on a page (let's say shoes) the navigation on the page will highlight, because it matches the menu's handle with the page handle. Good so far:
{% for link in linklists.main-menu.links %}
      {{ link.title }}
{% endfor %}

Now the question is, how do I check the sub-collection (Flats) and match it with it's parent collection to then do the same thing?

A: You need to adjust this condition
{% if collection.handle == link.handle %}
    class="current"
{% endif %}

so that it check for the internal links as well. Add this snippet before this condition
{% assign sub_link = false %}
{% assign inside_links_handle = link.handle %}
{% for inside_link in linklists[inside_links_handle].links %}
    {% if collection.handle == inside_link.handle %}
        {% assign sub_link = true %}
        {% break %}
    {% endif %}
{% endfor %}

And change the condition to this {% if collection.handle == link.handle or sub_link == true %} class='current' {% endif %}
Here you are looking inside the linklist which is inside another linklist (nested). More nesting levels, just iterate the code to consider inside levels. This should work.


text:
Q: How to get contact details in C# code , when new contact is created in Exchange Server 2013 I need to synchronize contacts in Exchange Server and Sugar CRM Application.
10 users exists in my Exchange server , same users exists in Sugar CRM Application.
my task is to create service that, if any User [ex:David] create new contact in Exchange server that contact should be created in same user account[David] in CRM Aplication through my service.
How can i get newly added contact details in C# code [EWS Managed API] ?
Please share your ideas ?

A: I think you'd want to set up streaming notifications on David's contacts folder using the EWS Managed API. You'd use the same code as is included in How to: Stream notifications about mailbox events by using EWS in Exchange. The difference is that you'd use WellKnownFolderName.Contacts.


text:
Q: GSL+OMP: Thread safe random number generators in C++ I have a code in which I am trying to execute in parallel.
#include<iostream>
#include<omp.h>
#include<math.h>
#include<cstdlib>
#include<iterator>
#include<string.h>
#include<vector>
#include<map>
#include<time.h>
#include<gsl/gsl_rng.h>
#include<gsl/gsl_randist.h>

gsl_rng ** threadvec = new gsl_rng*[omp_get_num_threads()];
using namespace std;

int main(){
   clock_t begin = omp_get_wtime();
   vector<double> PopVals;
   map<int, vector<double> > BigMap;
   int Num1 = 100;
   double randval;
   int Num2 = 10;
   #pragma omp parallel
   {
       gsl_rng_env_setup();
       for (int b = 0; b < omp_get_num_threads(); b++)
           threadvec[b] = gsl_rng_alloc(gsl_rng_taus);
   }
   for( int i = 0; i < Num1; i++){
       PopVals.resize(Num2);
       #pragma omp parallel for
          for( int j = 0; j < Num2; j++){
              randval = gsl_rng_uniform(threadvec[omp_get_thread_num()]);
              PopVals[j] = randval;
          }
       BigMap.insert(make_pair(i,PopVals));
       PopVals.clear();
   }

map<int,vector<double> >::iterator it = BigMap.find(Num1-1);
vector<double> OutVals = it->second;

for (int i = 0; i < Num2; i++)
    cout << endl << OutVals[i] << endl;

for (int b = 0; b < omp_get_num_threads(); b++)
        gsl_rng_free(threadvec[b]);

clock_t end = omp_get_wtime();
double elapsed_time = double(end - begin);
cout << endl << "Time taken to run: " << elapsed_time <<  " secs" << endl;
}

When I run this, there are 8 threads executing the nested loop in parallel, but I keep seeing the same random number for each thread. I attributed this behavior to lack of setting the seed, for each iteration. It would be great if somebody can point out, how can i generate unique random numbers in each iteration of the loop in a thread safe way.
The output of the above code is 0.793816, 10 times. Whereas, I want unique numbers for each of the values in the inner loop.
Thanks.

A: There are multiple issues here.
Using omp_get_num_threads out of parallel regions
Outside of a parallel region, omp_get_num_threads() always returns 1. Use omp_get_max_threads() instead, it will return the number of threads for any upcoming parallel region unless manually overridden. Especially threadvec has only one entry.
Don't initialize the environment in a parallel region
Calling gsl_rng_env_setup in a parallel region won't work properly. Also you are trying to allocate the whole vector of rngs by all threads... Simply remove the parallel region and use omp_get_max_threads() correctly. Or you could also do:
gsl_rng_env_setup(); // serial
#pragma omp parallel
threadvec[omp_get_thread_num()] = gsl_rng_alloc(gsl_rng_taus);

Allthough from the documentation it is not 100% clear if that is threadsafe, so just use the serial loop version.
Properly seed your rngs differently
By default, all rngs are seeded with the same number, so obviously they will return the exact same sequence. Seed them properly with the thread number, e.g. gsl_rng_set(threadvec[b], b * 101);. Note that Tausworthe generators are weird. Those particular generate the same sequence of numbers when seeded with 0 or 1.
Implicitly shared variables
Your variable randval is defined outside of the parallel region, hence it is implicitly shared. You could force it to be private, but it is better to declare variables as locally as possible. That makes reasoning about OpenMP code much easier.
At the end, it looks something like this:
#include <cstdlib>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <iostream>
#include <iterator>
#include <map>
#include <math.h>
#include <omp.h>
#include <string.h>
#include <time.h>
#include <vector>

// DO NOT using namespace std;

int main() {
  clock_t begin = omp_get_wtime();
  std::vector<double> PopVals;
  std::map<int, std::vector<double>> BigMap;
  constexpr int Num1 = 100;
  constexpr int Num2 = 10;
  gsl_rng_env_setup();
  gsl_rng **threadvec = new gsl_rng *[omp_get_max_threads()];
  for (int b = 0; b < omp_get_max_threads(); b++) {
    threadvec[b] = gsl_rng_alloc(gsl_rng_taus);
    gsl_rng_set(threadvec[b], b * 101);
  }
  for (int i = 0; i < Num1; i++) {
    PopVals.resize(Num2);
    #pragma omp parallel for
    for (int j = 0; j < Num2; j++) {
      double randval = gsl_rng_uniform(threadvec[omp_get_thread_num()]);
      PopVals[j] = randval;
    }
    BigMap.insert(std::make_pair(i, PopVals));
    PopVals.clear();
  }

  std::map<int, std::vector<double>>::iterator it = BigMap.find(Num1 - 1);
  std::vector<double> OutVals = it->second;

  for (int i = 0; i < Num2; i++)
    std::cout << std::endl << OutVals[i] << std::endl;

  for (int b = 0; b < omp_get_max_threads(); b++)
    gsl_rng_free(threadvec[b]);

  clock_t end = omp_get_wtime();
  double elapsed_time = double(end - begin);
  std::cout << std::endl << "Time taken to run: " << elapsed_time << " secs" << std::endl;
  delete[] threadvec;
}


text:
Q: How to Get Type of a Variable in C++ I want to create a function to display a variable's value by using a pointer, but I attempted to create only one function to display any type of value. I had to use template  but I have some issues with displaying strings or chars. Just for solving it, I need a getType() function (like in Java)
     #include <iostream>
     using namespace std;

     template <typename T>
     void displayByPtr(T *ptr){

           if( // If ptr's data type is char // ){

               T *holder = ptr;
               cout << "\nDisplayed char/string by pointer: ";
               while((*holder) != '\0'){
                   cout << (*holder);
                   holder++;
           }
           cout << "\n";
           } else {
             cout << "\nDisplayed value by pointer :" << (*ptr) << "\n";
           }

     }

    int main(){

         char decision = 'Y';
         while(decision == 'Y'){
              cout << "Enter a type \n Press 1 for integer,\n Press 2 for double, \n";
              cout << " Press 3 for float, \n Press 4 for character/string, \n --> ";
              int type = 0;
              cin >> type;
              switch(type){

                             .
                             .
                             .
                  case 4:
                       char inputCh[100];
                       char *ptr4;
                       cout << "Enter char value: ";
                       cin >> inputCh;
                       ptr4 = inputCh;
                       displayByPtr<char>(ptr4);
                       cout << "\n Would you like to continue ? ";
                       cin >> decision;
                       break;

I actually tried it with typeid(variable).name() in "if( // If ptr's data type is char // )" just for once, and it did not work out. Im trying to do some research for that function's syntax, but I would like to hear if there's an another way.

A: You can use template specialization.
     template <typename T> // general version
     void displayByPtr(T *ptr){

           cout << "\nDisplayed value by pointer :" << (*ptr) << "\n";

     }

     template <> // specialized to char
     void displayByPtr(char *ptr){

           char *holder = ptr;
           cout << "\nDisplayed char/string by pointer: ";
           while((*holder) != '\0'){
               cout << (*holder);
               holder++;
           }
           cout << "\n";

     }


text:
Q: Android: When I run the app it crashes Hi. When I run my app in the emulator it crashes, I'm new on Android, please help.
This is my main.java:
http://pastebin.com/UvECkaxN
and this is my main.xml:
http://pastebin.com/GMvE3XGc

A: The button sub is not initialised. Add the below code snippet in your onCreate() method, before setting the onClickListener for it.
sub = (Button) findViewById(R.id.bSub);

A: Add this line in your Activity oncreate()
sub = (Button) findViewById(R.id.bSub);

A: you forget to create the reference button sub.
you just need to add this below line in your onCreate.
sub = (Button) findViewById(R.id.bSub);


text:
Q: Listing and removing all cache entries from a given group using IDistributedCache I'm storing some key generated by users in a IDistributedCache set up.
The key are long lived and they can be manually revoked by an user, if the user knows each one of them:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();
    //...
}

//ControllerBase:

//Adding the key:
await _cache.SetAsync(userKey, userId, new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(10)
});

//Removing the key:
await _cache.RemoveAsync(key);

Now, what I want to do is to be able to list all keys still present in the cache that were created by one of the users. Also, I want to be able to bulk delete them.
Is there such a functionality available right now?
Maybe with cancelation tokens? How can I do that?

A: No, you can only work with one key at a time with IDistributedCache. Mass key eviction and similar scenarios are beyond the scope of this facade. If you need to handle more advanced scenarios, then you should connect to your cache directly, using the appropriate client. For example, for a Redis backing, you can use the StackExchange.Redis package, and issue whatever commands you like via that.

A: You can flush the store using FLUSHALL method(IServer.FlushAllDatabasesAsync() - please note that AllowAdmin flag must be true in the config). The method exist in IServer interface which can be retrieved from IConnectionMultiplexer. If you're using StackExchange.Redis DI, IDistributedCache doesn't have the ability to do so as of now. You can use System.Reflection to get IConnectionMultiplexer from (RedisCache)IDistributedCache.


text:
Q: Joint distribution of $(X_1,X_1 + X_2)$ Let $X_1$ and $X_2$ geometric random variables independent with parameters $p_1$ and $p_2$. Find the joint distribution of $(X_1,X_1 + X_2)$.
My attempt is the following:
\begin{align*}
     P[X_1=x_1,X_1 + X_2=x_2] &= P[X_1 + X_2=x_2|X_1=x_1]P[X_1=x_1]\\
     &=  P[x_1 + X_2=x_2] p_1(1-p_1)^{x_1}\\
     &=  P[X_2=x_2-x_1] p_1(1-p_1)^{x_1}\\
     &=  p_2(1-p_2)^{x_2-x_1} p_1(1-p_1)^{x_1}\\
\end{align*}
Is this right? I do not know because I did not use the independence of $X_1$ and $X_2$.

A: You actually did use independence when you wrote $$P[X_1 + X_2=x_2|X_1=x_1]
=P[x_1 + X_2=x_2|X_1=x_1]=P[X_2=x_2-x_1].$$
Note that the equality you wrote is for $x_2\geqslant x_1$, for $x_2<x_1$ is $0$.


text:
Q: CSS to stretch span to height of container I've set two span elements side by side with a separating border being applied to one of the spans. The problem occurs when one span has more lines than the other. If the span with less content is the one which has the border applied to it, the border doesn't stretch to the bottom of the container.
I've tried adding height and min-height elements to the span, the containing div, the HTML and body tags in various combinations with no success.
Here is the sample HTML:

        Flash Exposure Compensation
        +/- EV
more text
more text
more text
more text

And the applicable CSS:
.newspecs div {
    display: block;
    clear: both;
}
.newspecs span {
    display: inline-block;
    vertical-align: top;
}
.ns_row_type_1,
.ns_row_type_2 {
    border-bottom: 1px solid #fff;
}
.ns_row_type_1 {
    background-color: #ccc;
}
.ns_field_name {
    width: 100px;
    padding: 3px;
    border-right: 1px solid #fff;
}
.ns_field_value {
    width: 280px;
    padding: 3px;
}

The full CSS and HTML is at:
http://yazminmedia.com/clients/IR/test.htm
Anyone have an idea of what is going on?
Thanks!

A: Option 1: Floats, extra border, and 1px negative margin

*

*http://jsfiddle.net/95uMq/
Option 2: CSS3

*

*http://jsfiddle.net/95uMq/1/
Option 3: Table based Layout

*

*http://jsfiddle.net/95uMq/2/

A: You should really be using a HTML TABLE here as this is a table of data that you are trying to display.
However as a nasty hack, change ns_field_value to...

.ns_field_value {width: 280px; padding: 3px; margin-left:-4px; border-left:1px solid #fff}

This just adds a border-left to the field value 'cell' and then does a -4px margin so that the borders overlap appearing to create a single border.


text:
Q: Kill bxSlider on button click so it can be reloaded I am using bxslider to create a somewhat customized thumbnail/slider element. Basically I have a simple grid of thumbnails and the intent is to have the slider open on the specific thumbnail image on click.
The issue I'm coming across is that the slider remains active after closing the slider window and I need it to stop/reset.
Scouring the internet led me to the function destroySlider(), but that is resulting the following error in the console:

Uncaught TypeError: $(...).bxSlider(...).destroySlider is not a
  function

Any thoughts on how best to do this is appreciated, code below:

JS:
function removeSlider(a, b) {
    $(a).click(function(){
      $(b).removeClass("open-slide");
      $('.bxslider').bxSlider().destroySlider();
    });
  }

$('.open-slider').on('click', function (e) {
  var startingImg = $(this).data('starting-img');
  var slideSection = $(this).data('slide-section');
  e.preventDefault();
  $('#' + slideSection).addClass('open-slide');
  $('.bxslider').bxSlider({
    startSlide: parseInt(startingImg)
  });
  removeSlider('.remove-port-item', '.slide-contain')
})

HTML:

        <button class="remove-port-item button-close-slide">X</button>

A: Referring to comment by @Chris G above ^:

Try storing the slider in a global variable when you create it:
  mySlider = $('.bxslider').bxSlider({ .... Then call
  myslider.destroySlider(); Edit: according to the docs on github, this
  will do it.

I tried this earlier with no luck, but I figured out why and here is the correct code:
var slider = $('.bxslider').bxSlider();

function removeSlider(a, b) {
    $(a).click(function(){
      $(b).removeClass("open-slide");
      slider.destroySlider();
    });
  }

$('.open-slider').on('click', function (e) {
  var startingImg = $(this).data('starting-img');
  var slideSection = $(this).data('slide-section');
  e.preventDefault();
  $('#' + slideSection).addClass('open-slide');
  slider.reloadSlider({
    startSlide: parseInt(startingImg)
  })
  removeSlider('.remove-port-item', '.slide-contain')
})

As Chris G points out, the ultimate solution is to move bxSlider to a global variable, but there was an extra step due to the fact that the click function for opening the slider is using a variable scoped to that function (startingImg). This was solved by running:
slider.reloadSlider({
   startSlide: parseInt(startingImg)
})

UPDATE: This works if only using one set of slides in the markup. The minute I try to use multiple sets of slides, even though they have their own unique IDs, it breaks reloadSlider and destroySlider. I am still trying to work through this.

A: In order for the image clicks and X button to work regardless of the state, it needs to be checked, both when opening and closing the slider:
Demo:

var slider = {};

function removeSlider(a, b) {
  $(a).click(function() {
    $(b).removeClass("open-slide");
    var slideSection = $(a).parent().parent().attr("id");
    if (slider[slideSection]) {
      slider[slideSection].destroySlider();
      slider[slideSection] = null;
    }
  });
}

$('.open-slider').on('click', function(e) {
  var startingImg = parseInt($(this).data('starting-img'));
  var slideSection = $(this).data('slide-section');
  e.preventDefault();
  $('#' + slideSection).addClass('open-slide');
  if (slider[slideSection]) slider[slideSection].goToSlide(startingImg);
  else slider[slideSection] = $('.bxslider').bxSlider({
    startSlide: startingImg
  });
})

$(document).ready(function() {
  removeSlider('.remove-port-item', '.slide-contain');
});
.open-slider img {
  width: 100%;
  height: 20px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.12/jquery.bxslider.min.css">

    <button class="remove-port-item button-close-slide">X</button>

Edit: changed JS code to work for multiple groups of thumbs + slider.


text:
Q: Multiple identity properties for authentication in ZF2 with Doctrine 2 I have login form with input text fields:

*

*Group Name

*User Name

*User Password

I have two tables

*

*groups

*

*id

*name

*users

*

*id

*name

*group_id
I have its mapping entities and associations.
But user name not unique within table users, because different groups can include users with equal names. Therefore i need:

*

*find group by name in table groups

*find user by name in table users with condition where group_id=<group_id>
How to do it correctly in Zend Framework 2 using Doctrine 2?
All official documentation and examples depict situation, where identity property is single column (example).
Sorry for my bad language. Thanks.

A: Instead of making my own implementation of Doctrine's authentication services i decide to implement it via form validation inside isValid() method of my authentication form.
Example:
<?php

namespace My\Form\Namespace;

use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\InputFilter\InputFilterProviderInterface;

class Auth extends Form implement InputFilterProviderInterface
{
    protected $_em;

    public function __construct(ServiceLocatorInterface $sm)
    {
        parent::__construct('auth');

        // inject Doctrine's Entity Manager
        $this->_em = $sm->get('Doctrine\ORM\EntityManager');

        // login field
        $this->add(...);

        // password field
        $this->add(...);

        // group_name field
        $this->add(...);
    }

    public function getInputFilterSpecification()
    {
        //Input filter specification here
        ...
    }

    public function isValid()
    {
        /*
         * input filter validations
         */
        if (!parent::isValid())
            return false;

        /*
         * group exists validation
         */
        $group = $this->_em
            ->getRepository('<Group\Entity\Namespace>')
            ->findOneBy(array(
                'name' => $this->get('group_name')->getValue(),
            ));
        if (!$group){
            $this->get('group_name')
                ->setMessages(array(
                    'Group not found',
                ));
            return false;
        }

        /*
         * user exists validation
         */
        $user = $this->_em
            ->getRepository('<User\Entity\Namespace>')
            ->findOneBy(array(
                'group_id' => $group->getId(),
                'name' => $this->get('login')->getValue(),
            ));
        if (!$user){
            /*
             * It's not good idea to tell that user not found,
             * so let it be password error
             */
            $this->get('password')
                ->setMessages(array(
                    'Login or password wrong',
                ));
            return false;
        }

        /*
         * password validation
         */
        $password = $this->get('password')->getValue();
        // assume that password hash just md5 of password string
        if (md5($password) !== $user->getPassword()){
            $this->get('password')
                ->setMessages(array(
                    'Login or password wrong',
                ));
            return false;
        }

        return true;
    }
}

Inside controller it is enough to call $form->isValid() to make sure that user entered correct authentication data.

A: I have the same problem.
I have to do two authentications in same application, because my boss doesn't wanna two databases. So, I had to make two user tables and two login pages.
One route to admin -> /admin/login
And the front-end for other users -> /login
I've tried to put on more authenticate in doctrine authentication array but it didn't work.
I think I'll open a issue on doctrine github page.


text:
Q: Reacts js TypeError: Cannot read property 'params' of undefined i want to move to next pages as i change the url
Here is some of my code for web app in react js. I am trying for pagination but I am unable to access params. How can I access the params as these are also not showing on console as I tried using console.log().
const Products = (props) => {
  console.log(props);
  const [products, setProducts] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const classes = useStyles();
  const page = props.match.params.page ? props.match.params.page : 1;
  const getData = () => {
    productService
      .getProduct(page)
      .then((data) => {
        setProducts(data.products);
        setTotal(data.total);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  React.useEffect(getData, []);
  return (

Products List:

      {userService.isAdmin() && (
        <Fab color="primary" aria-label="add" className={classes.addBtn}>
          <AddIcon />
        </Fab>
      )}

        {products.length == 0 ? (

No Product Found!

        ) : (
          <Grid container spacing={3}>
            {products.map((product, index) => (
              <SingleProduct key={index} product={product} onDelete={getData} />
            ))}
          </Grid>
        )}
        <Grid items xs={12}>
          total: {total}
        </Grid>

  );
};
export default Products;

A: Just use optional chaining
const page = props.match?.params?.page || 1;

A: It seems you are checking the params for a number. By default the params value is a string. You can fix your issue by converting it as a number using parseInt.
....
   const getData = () => {
   productService
     .getProduct(parseInt(page))
     .then...
....

Hope it helped.

A: Your problem is simple. Your object defined in props.match is not defined and therefore the error is throw. A simple solution for that is using optional chaining.
    const page = props.match?.params?.page || 1;

You can also use the prop-types npm package for validating your components properties. Something like this would validate and define a default value for your component prop.
import PropTypes from 'prop-types';

const Products = (props) => {...};

Products.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      page: PropTypes.number,
    }).isRequired,
  }).isRequired,
};

Products.defaultProps = {
  match: { params: {page: 1} },
};

Finally, whenever you use useEffect make sure you're observing the right parameters for executing the callback. In your case it makes sense to observe for changes in the page variable since you are updating your component state using this hook. If you don't do this even if you change the value of your page property your component state will not update.
React.useEffect(getData, [page]);


text:
Q: What is wrong with this search filter code for a webpage search input box? This gets called on the onkeyup event in my html search bar input.
I walked through it with the debugger and it is actually getting the searchInput that the user types, but something about the filter() function doesn't work. It doesn't actually filter through the storageSvc array and then re-rendering the table with the filtered data. "name" is part of an object in my data array.
No errors, its just not actually filtering the data.
function searchTeam(){
    let searchInput = document.getElementById("searchInput").value;
    storageSvc.filter({name:searchInput});
    // re render table
    renderTable("#tableContainer", storageSvc.list());
}
filter(filterObj) {
    //returns a copy of the filtered array
    ///e.g., storageSvc.filter({coachLicenseLevel:1});
    return this.model.data.filter((d) => {
        for (const key of Object.keys(filterObj)) {
            if (d[key] !== filterObj[key]) {
                return false;
            }
        }
        return true;
    });
}

A: You're not actually using the returned value from the filter function.
Try assigning the returned value of the filter function to a variable and then pass that variable to your render fucntion:
function searchTeam() {
  let searchInput = document.getElementById("searchInput").value;
  const filteredResults = storageSvc.filter({ name: searchInput });
  // renderTable("#tableContainer", storageSvc.list() );
  renderTable("#tableContainer", filteredResults);
}

function filter(filterObj) {
  //returns a copy of the filtered array
  ///e.g., storageSvc.filter({coachLicenseLevel:1});
  return this.model.data.filter((d) => {
    for (const key of Object.keys(filterObj)) {
      if (d[key] !== filterObj[key]) {
        return false;
      }
    }
    return true;
  });
}


text:
Q: Is it possible to build dumpimage from u-boot for arm .? I am trying to extract a FIT image created by mkimage on an ARM board.
Usually when we build u-boot, mkimage and dumpimage are built for the host.
I would instead like to cross-compile and install in a ramfs. Is there any method to do this?
Rewrite Makefile :
I have modified the make file such a that it take arm cross tool as HOSTCC, I can see .o files are created for arm arch(file *.o).
**Sample Makefile is given as below ** (just i want dumpimage to be compiled for arm, so I have commented out all other sections)=>
# git diff 0b94ce5ed4a6c2cd0fec7b8337e776b03e387347
diff --git a/Makefile b/Makefile
index 88128ec..8ed7a33 100755
--- a/Makefile
+++ b/Makefile
@@ -7,6 +7,7 @@ PATCHLEVEL = 07
 SUBLEVEL =
 EXTRAVERSION =
 NAME =
+CC=arm-linux-gnueabihf-gcc

 # *DOCUMENTATION*
 # To see a list of typical targets execute "make help"
@@ -224,7 +225,7 @@ unexport CDPATH

 #########################################################################

-HOSTARCH := $(shell uname -m | \
+#HOSTARCH := $(shell uname -m | \
    sed -e s/i.86/x86/ \
        -e s/sun4u/sparc64/ \
        -e s/arm.*/arm/ \
@@ -233,6 +234,7 @@ HOSTARCH := $(shell uname -m | \
        -e s/ppc/powerpc/ \
        -e s/macppc/powerpc/\
        -e s/sh.*/sh/)
+HOSTARCH := arm

 HOSTOS := $(shell uname -s | tr '[:upper:]' '[:lower:]' | \
        sed -e 's/\(cygwin\).*/cygwin/')
@@ -254,8 +256,8 @@ CONFIG_SHELL := $(shell if [ -x "$$BASH" ]; then echo $$BASH; \
      else if [ -x /bin/bash ]; then echo /bin/bash; \
      else echo sh; fi ; fi)

-HOSTCC       = cc
-HOSTCXX      = c++
+HOSTCC       = arm-linux-gnueabihf-gcc
+HOSTCXX      = arm-linux-gnueabihf-g++
 HOSTCFLAGS   = -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer
 HOSTCXXFLAGS = -O2

@@ -283,7 +285,7 @@ os_x_before = $(shell if [ $(DARWIN_MAJOR_VERSION) -le $(1) -a \
    $(DARWIN_MINOR_VERSION) -le $(2) ] ; then echo "$(3)"; else echo "$(4)"; fi ;)

 # Snow Leopards build environment has no longer restrictions as described above
-HOSTCC       = $(call os_x_before, 10, 5, "cc", "gcc")
+HOSTCC       = $(call os_x_before, 10, 5, "arm-linux-gnueabihf-gcc", "arm-linux-gnueabihf-gcc")
 HOSTCFLAGS  += $(call os_x_before, 10, 4, "-traditional-cpp")
 HOSTLDFLAGS += $(call os_x_before, 10, 5, "-multiply_defined suppress")

@@ -392,13 +394,13 @@ export RCS_TAR_IGNORE := --exclude SCCS --exclude BitKeeper --exclude .svn \
 # Rules shared between *config targets and build targets

 # Basic helpers built in scripts/
-PHONY += scripts_basic
-scripts_basic:
-       $(Q)$(MAKE) $(build)=scripts/basic
-       $(Q)rm -f .tmp_quiet_recordmcount
+#PHONY += scripts_basic
+#scripts_basic:
+#      $(Q)$(MAKE) $(build)=scripts/basic
+#      $(Q)rm -f .tmp_quiet_recordmcount

 # To avoid any implicit rule to kick in, define an empty command.
-scripts/basic/%: scripts_basic ;
+#scripts/basic/%: scripts_basic ;

 PHONY += outputmakefile
 # outputmakefile generates a Makefile in the output directory, if using a
@@ -470,11 +472,11 @@ ifeq ($(config-targets),1)
 KBUILD_DEFCONFIG := sandbox_defconfig
 export KBUILD_DEFCONFIG KBUILD_KCONFIG

-config: scripts_basic outputmakefile FORCE
-       $(Q)$(MAKE) $(build)=scripts/kconfig $@
+#config: scripts_basic outputmakefile FORCE
+#      $(Q)$(MAKE) $(build)=scripts/kconfig $@

-%config: scripts_basic outputmakefile FORCE
-       $(Q)$(MAKE) $(build)=scripts/kconfig $@
+#%config: scripts_basic outputmakefile FORCE
+#      $(Q)$(MAKE) $(build)=scripts/kconfig $@

 else
 # ===========================================================================
@@ -670,7 +672,7 @@ libs-y += $(if $(BOARDDIR),board/$(BOARDDIR)/)

 libs-y := $(sort $(libs-y))

-u-boot-dirs    := $(patsubst %/,%,$(filter %/, $(libs-y))) tools examples
+u-boot-dirs    := tools

 u-boot-alldirs := $(sort $(u-boot-dirs) $(patsubst %/,%,$(filter %/, $(libs-))))

@@ -1197,7 +1199,7 @@ u-boot.sym: u-boot FORCE

 # The actual objects are generated when descending,
 # make sure no implicit rule kicks in
-$(sort $(u-boot-init) $(u-boot-main)): $(u-boot-dirs) ;
+#$(sort $(u-boot-init) $(u-boot-main)): $(u-boot-dirs) ;

 # Handle descending into subdirectories listed in $(vmlinux-dirs)
 # Preset locale variables to speed up the build process. Limit locale
@@ -1205,24 +1207,30 @@ $(sort $(u-boot-init) $(u-boot-main)): $(u-boot-dirs) ;
 # make menuconfig etc.
 # Error messages still appears in the original language

-PHONY += $(u-boot-dirs)
-$(u-boot-dirs): prepare scripts
-       $(Q)$(MAKE) $(build)=$@
+PHONY += tools
+#-Xlinker -rpath-link=/home/phate/rpi/chroot-raspbian-armhf/usr/lib/arm-linux-gnueabihf
+LDFLAGS += -L./lib_sample/ -lcrypto
+LDFLAGS += -L/home/pritam/documents/workspace/codebase/linux/u-boot/codebase/openssl/openssl/ -lcrypto

-tools: prepare
+LD_LIBRARY_PATH=./lib_sample/
+export LD_LIBRARY_PATH
+tools: #prepare scripts
+       make $(build)=$@
+
+#tools: #prepare
 # The "tools" are needed early
-$(filter-out tools, $(u-boot-dirs)): tools
+#$(u-boot-dirs)):
 # The "examples" conditionally depend on U-Boot (say, when USE_PRIVATE_LIBGCC
 # is "yes"), so compile examples after U-Boot is compiled.
-examples: $(filter-out examples, $(u-boot-dirs))
+#examples: $(filter-out examples, $(u-boot-dirs))

 define filechk_uboot.release
-       echo "$(UBOOTVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
+#      echo "$(UBOOTVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
 endef

 # Store (new) UBOOTRELEASE string in include/config/uboot.release
-include/config/uboot.release: include/config/auto.conf FORCE
-       $(call filechk,uboot.release)
+#include/config/uboot.release: include/config/auto.conf FORCE
+#      $(call filechk,uboot.release)

 # Things we need to do before we recursively start building the kernel
@@ -1232,7 +1240,7 @@ include/config/uboot.release: include/config/auto.conf FORCE
 # version.h and scripts_basic is processed / created.

 # Listed in dependency order
-PHONY += prepare archprepare prepare0 prepare1 prepare2 prepare3
+#PHONY += prepare archprepare prepare0 prepare1 prepare2 prepare3

 # prepare3 is used to check if we are building in a separate output directory,
 # and if so do:
@@ -1257,7 +1265,7 @@ ifeq ($(wildcard $(LDSCRIPT)),)
    @/bin/false
 endif

-archprepare: prepare1 scripts_basic
+#archprepare: prepare1 scripts_basic

 prepare0: archprepare FORCE
    $(Q)$(MAKE) $(build)=.
@@ -1377,11 +1385,11 @@ checkarmreloc: u-boot
            false; \
    fi

-env: scripts_basic
-       $(Q)$(MAKE) $(build)=tools/$@
+#env: scripts_basic
+#      $(Q)$(MAKE) $(build)=tools/$@

-tools-only: scripts_basic $(version_h) $(timestamp_h)
-       $(Q)$(MAKE) $(build)=tools
+#tools-only: scripts_basic $(version_h) $(timestamp_h)
+#      $(Q)$(MAKE) $(build)=tools

 tools-all: export HOST_TOOLS_ALL=y
 tools-all: env tools ;
diff --git a/common/image-sig.c b/common/image-sig.c
index eda5e13..c6df99f 100644
--- a/common/image-sig.c
+++ b/common/image-sig.c
@@ -3,6 +3,7 @@
  *
  * SPDX-License-Identifier:    GPL-2.0+
  */
+//#undef USE_HOSTCC

 #ifdef USE_HOSTCC
 #include "mkimage.h"
diff --git a/scripts/Makefile b/scripts/Makefile
index 2f081f7..345a272 100644
--- a/scripts/Makefile
+++ b/scripts/Makefile
@@ -16,4 +16,4 @@ build_docproc: $(obj)/docproc
    @:

 # Let clean descend into subdirs
-subdir-        += basic kconfig
+#subdir-       += basic kconfig
diff --git a/scripts/Makefile.build b/scripts/Makefile.build
index 06e5c20..9056412 100644
--- a/scripts/Makefile.build
+++ b/scripts/Makefile.build
@@ -269,8 +269,8 @@ define rule_cc_o_c
    $(cmd_modversions)                                                \
    $(call echo-cmd,record_mcount)                                    \
    $(cmd_record_mcount)                                              \
-       scripts/basic/fixdep $(depfile) $@ '$(call make-cmd,cc_o_c)' >    \
-                                                     $(dot-target).tmp;  \
+#scripts/basic/fixdep $(depfile) $@ '$(call make-cmd,cc_o_c)' >    \
+#                                                    $(dot-target).tmp;  \
    rm -f $(depfile);                                                 \
    mv -f $(dot-target).tmp $(dot-target).cmd
 endef
diff --git a/scripts/basic/Makefile b/scripts/basic/Makefile
index f883857..b281340 100644
--- a/scripts/basic/Makefile
+++ b/scripts/basic/Makefile
@@ -11,8 +11,8 @@
 # SPDX-License-Identifier:     GPL-2.0
 #

-hostprogs-y    := fixdep
-always         := $(hostprogs-y)
+#hostprogs-y   := fixdep
+#always                := $(hostprogs-y)

-# fixdep is needed to compile other host programs
-$(addprefix $(obj)/,$(filter-out fixdep,$(always))): $(obj)/fixdep
+## fixdep is needed to compile other host programs
+#$(addprefix $(obj)/,$(filter-out fixdep,$(always))): $(obj)/fixdep
diff --git a/tools/Makefile b/tools/Makefile
index f72294a..be9b221 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -225,6 +225,7 @@ HOST_EXTRACFLAGS += -include $(srctree)/include/libfdt_env.h \
            $(patsubst -I%,-idirafter%, $(filter -I%, $(UBOOTINCLUDE))) \
            -I$(srctree)/lib/libfdt \
            -I$(srctree)/tools \
+               -I/home/pritam/documents/workspace/codebase/linux/u-boot/codebase/openssl/openssl/include \
            -DCONFIG_SYS_TEXT_BASE=$(CONFIG_SYS_TEXT_BASE) \
            -DUSE_HOSTCC \
            -D__KERNEL_STRICT_NAMES \

OUTPUT is =>
make -f ./scripts/Makefile.build obj=tools
HOSTLD  tools/dumpimage
/home/pritam/documents/workspace/tools/sdks/bolide/petalinux/tools/linux-i386/gcc-arm-linux-gnueabi/bin/../lib/gcc/arm-linux-gnueabihf/5.2.1/../../../../arm-linux-gnueabihf/bin/ld: cannot find -lssl
/home/pritam/documents/workspace/tools/sdks/bolide/petalinux/tools/linux-i386/gcc-arm-linux-gnueabi/bin/../lib/gcc/arm-linux-gnueabihf/5.2.1/../../../../arm-linux-gnueabihf/bin/ld: cannot find -lcrypto
collect2: error: ld returned 1 exit status
scripts/Makefile.host:103: recipe for target 'tools/dumpimage' failed
make[1]: *** [tools/dumpimage] Error 1
Makefile:1217: recipe for target 'tools' failed
make: *** [tools] Error 2

NOTE I have downloaded and compile openssl for arm and path is assigned to LDFLAGS  as we can see in Makefile patch
How can I link Libraries that are built separately for arm ?
Kindly correct me if I go wrong.

A: I faced this problem where I only needed dumpimage tool on linux x86/64.
The following worked for me.
1) wget ftp://ftp.denx.de/pub/u-boot/u-boot-latest.tar.bz2
2) cd u-boot-2017.09
3) make qemu-x86_defconfig
4) make tools
Host tools are now ready.

A: Along with changes in Makefiles as mentioned above, on crypto and ssl link issue, I have compiled openssl for arm and linked *.a in a u-boot top level Makefile using HOSTLDFLAGS.

A: You could build U-boot tools Cross compiled.
Example: make ARCH=arm CROSS_COMPILE=aarch64-linux-gnu- CROSS_BUILD_TOOLS=1 tools
This will give you cross compiled tools generated in your tools directory.


text:
Q: How to tell if stderr has been redirected in Windows? I want my program to have different behaviors between when stderr is connected to a console and when it is redirected to a file/pipe. In Unix systems I can just test isatty(STDERR_FILENO), but how do I do that in Windows? MSVCRT also has a function named _isatty, it doesn't function properly (for example, Detect NUL file descriptor (isatty is bogus)). Is there any Windows or NT API I can call to test it?

A: *

*Call GetStdHandle to get the stderr handle.

*Pass that handle to GetFileType to find out what type of file it is.

*If that returns FILE_TYPE_CHAR then stderr could be a console, but call GetConsoleMode to check.

*If GetConsoleMode fails then stderr has been redirected to another character device, such as a printer.

A: For me, the simplest approach was to use fseek(stderr, 0, SEEK_CUR) which returns 0 if the stderr is redirected to a file and <>0 if stderr is not redirected.


text:
Q: cabal-version option ignored I'm trying to install a fairly old package (see here) with stack. It uses a custom Setup.hs script which depends on cabal >= 1.20 due to (among other things) a reliance on the buildNumJobs field of the BuildFlags type.
For some reason, the cabal-version was set to >= 1.10 which is clearly too low. I changed it once I figured out what was going on, but the problem persisted. What do I have to do for stack and cabal to pick up on the new cabal-version constraint?
I tried simply replacing the buildNumJobs value with a default value, which resulted in the following error at build time:
Warning: skia.cabal: This package requires at least Cabal version 1.20
Configuring skia-0.1.0.0...
setup.EXE: This package description follows version 1.20 of the Cabal
specification. This tool only supports up to version 1.18.1.5.

Again, what do I need to do for stack to respect the cabal-version option?

A: Turns out, all I had to do was to run stack setup --upgrade-cabal. I still wonder though why stack doesn't detect the inconsistency automatically...


text:
Q: Redirecting URLs when switching over from Volusion We have a site which we are switching over from Volusion to Magento.
This site has around 1500 products, and the url's for each of these product pages is going to be different from the current url on Magento. (The Volusion url's are extremely ugly. The Magento ones will just be site.com/product-name)
I want to 301 redirect the old urls to the new ones so we keep our search engine rankings.
Is there a better way to do this than to manually go one by one, and lining up all of the old urls with the new ones? Doing this will take hours and hours, and I'm looking for a faster solution.

A: Assuming that your product SKUs are consistent between Volusion and Magento then this is easily scripted or manipulated in Excel.
To do this in Excel: First export the product SKUs and URLs from Volusion into a CSV, then export the product SKUs and URLs from Magento into a CSC. You can then quite easily create a third CSV file in Excel that contains the following columns:
SKU,Old URL,New URL
MYSKU,http://domain.com/old_productUrl,http://domain.com/nice-new-product-url
MYSKU2,http://domain.com/old_productUrl2,http://domain.com/nice-new-product-url-2

Once you have this CSV file I highly recommend using Optimise Web's Mass 301 Redirect extension. This will allow you to manage the 301 redirects using a CSV file (read the docs to ensure the format is correct).
I do NOT recommend manually creating redirects in the Magento "URL Rewrite Management" screen. Mostly because they're hard to manage in there, but also because if you ever need to purge that data (it happens) then you'll lose any manually added entries when you re-index.


text:
Q: Is it possible to display a UIDocumentInteractionController in a container? I have a UIViewController within a container view. The view controller displays a PDF in a UIDocumentInteractionController like so:
let documentInteractionController = UIDocumentInteractionController(url: pdfUrl)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)

The UIDocumentInteractionController displays itself modally. I'd like it to be displayed within the container. Is this possible?

A: Responding a little late to this but I had the same question recently- I'm not sure about your full navigation setup, but returning the navigation controller in the delegate method below will present the preview within the navigation stack.  (returning anything else will present the default modal view)
Documentation here: https://developer.apple.com/reference/uikit/uidocumentinteractioncontrollerdelegate/1616799-documentinteractioncontrollervie
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    //return self to present modally
    //return nav controller to push document preview into the stack
    return self.navigationController!
}


text:
Q: how to find the vcruntime140.dll in flutter build windows?
I am new to Flutter, I've tried to build a Windows application right now. But in Flutter docs, they said that I have to put these files in my build folder. Where I can find those files so I can build my Flutter to a .exe program?
This showed an error while I transfer it folder to my friend's computer.


text:
Q: AngularJS controller is not defined mailtype appModule.controller("mailBoxController", function ($scope, $location, mailFactory, $routeParams) {
    /*
     get url parameter boxValue
     boxValue holds mail type
    */
   var boxvalue = $routeParams.boxValue;

    $scope.mailType = boxvalue;
    // mailBox
    $scope.mailBox = null;

//

    /**
     * Based on mailType assign title to $scope.titleType
     *
     * Mail Type   ->   Title
     *  "inbox"    ->   "Inbox"
     *  "draft"    ->   "Draft"
     *   sent"     ->   "Sent Mail"
     *
     **/

    if ($scope.mailType =='inbox'){
      $scope.titleType = 'Inbox'
    }
    if ($scope.mailType =='draft'){
      $scope.titleType = 'Draft'
    }
    if ($scope.mailType =='sent'){
      $scope.titleType = 'Sent Mail'
    }

\\
    $scope.readMailList = function () {
        /**
         * Based on mailType use the factory method to get the email list
         * Assign the response data to $scope.mailBox
         **/
        if ($scope.mailType == 'draft'){
          mailBox =  mailFactory.getDraftMsg() }
        if ($scope.mailType == 'sent'){
          mailBox =  mailFactory.getSentMsg() }
        if ($scope.mailType == 'inbox'){
          mailBox =  mailFactory.getInbox() }

    }

    $scope.deleteMessage = function (mailId) {
        /**
         * delete Email
         * And call the readMailList function
         * */
        mailFactory.deleteEmail(mailId);
        $scope.readMailList();

    }

    $scope.showEmail = function (mailId) {
        /**
         *  if mailType is inbox or sent then route to mailBoxInfo.html
         *  if mailType is draft then route to mailEditor.html
         **/
        if($scope.mailType=='inbox'){
          $location.path('mailBox/inbox/mailBoxInfo/'+mailId);
        }
          if($scope.mailType=='sent'){
          $location.path('mailBox/sent/mailBoxInfo/'+mailId);
        }
        if($scope.mailType=='draft'){
          $location.path('mailEditor/'+mailId);
        }
    }

    $scope.readMailList();
});

this is my code an the error i am getting is controller is not found


text:
Q: Not all embedded Youtube videos play on iPhone app I've been using the standard method to embed a Youtube video in a UIWebview as a thumbnail to give the appearance of playing the video in the iPhone app.
But many times the video either gives a broken play button or returns after 1 minute or so that the video could not be played.
I assume this is because the poster either didn't make the video public yet, or maybe it hadn't been converted to iPhone format yet?  Anyway, is there any way to check for this in the API JSON or Atom feed?  I looked thru every tag and couldn't find anything that would clearly confirm the video is not playable on the iPhone.

A: The iPhone does not natively support flash, so I don't see why it could support rendering the youtube player within a UIWebView. Perhaps you should try using an .mp4.


text:
Q: Bind different functions to different options in AngularJS I am in need to do such thing
<select>
  <option ng-sth="firstMethodToBeCalled()">Option 1</option>
  <option ng-sth="secondMethodToBeCalled()">Option 2</option>
<select>

Is there any way to do this?
I need this because i currently have this kind of code:
<select ng-model="someModel" ng-change="callThisFunction()">
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  ...
  <option value="valueN">Option N</option>
</select>

And I want to add only two more options to this Select but calling different function. I can refactor it to call same wrapper function and determine which final function shall be called with some conditional logic but I am wondering if there is a possibility to assign different. I have been looking for this for some time and didn't come across any solution.

A: Unfortunately, i'm afraid you can't.
By the way, i would keep to have single function in ng-change and the put some logic inside it (and call your second function too from there), like this:
$scope.callThisFunction = function(){
   if(someModel == "baz")
      myFirstfunction();
   else
      mySecondFunction();
}

it's the cleanest solution in my opinion, and the most mantainable.

A: Yes ! there is a way you can achieve this.Create a functions object with keys as your selected option which is your ng-model and value as a function aligned to it and performa ny action in it.
In your JS
$scope.functions ={
    "value1":function(){
        console.log("function for option 1 called");
    },"value2":function(){
        console.log("function for option 2  called");
    }
};

In your HTML
<select ng-model="someModel" ng-change="functions[someModel]()">
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  ...
  <option value="valueN">Option N</option>
</select>

Call the functions object in your ng-change by passing the your ng-model which is selected option which will invoke corresponding function.


text:
Q: Using img_to_graph from Sklearn I have the following code:
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering

image = cv2.imread("/home/facu/holo.tif",0)
image = image

spectrum = np.fft.fftshift(np.fft.fft2(image))
intensity = 10*np.log(np.abs(spectrum))

mask = intensity.astype(bool)
img = intensity.astype(float)
graph = image.img_to_graph(img, mask=mask)
graph.data = np.exp(-graph.data/graph.data.std())

labels = spectral_clustering(graph, k=2, mode = 'arpack')
label_img = -np.ones(mask.shape)
label_im[mask] = labels

So I'm trying to use the "spectral clustering" function but I get this error:

AttributeError: 'numpy.ndarray' object has no attribute 'img_to_graph'

How can I do for converting my "intensity" numpy array into a correct img_to_graph attribute?

A: You are overwriting your imported image = sklearn.feature_extraction.image with image = cv2.imread("/home/facu/holo.tif",0), so the function img_to_graph will not be accessible anymore.
The solution is to rename one of them, e.g. with
raw_img = cv2.imread("/home/facu/holo.tif",0)

and adjusting the rest accordingly.


text:
Q: Draw abline outside of plot margins on one side only I'm working on an R plot that will be separated into two parts by a vertical line I'm creating with abline().I would like that abline to go over the boundaries of my plot on one side only.
I found this helpful post about setting par(xpd=). However, I could not figure out how to get this command make the line go over the plot border on one side only, as outlined in the screenshot below.

*

*Is there a way to do this in base R? (Or do I have to rebuild the
whole thing in ggplot etc?)

*I feel that the key might the differences between figure region,
device region, etc. but was unable to really determine the difference
between those. I looked at this
source
but at least for my plot those settings seem to amount to the same
thing - it would be cool if anyone had some help here as well!
Here's my approach:
plot(100, 100)
par(xpd=TRUE)
abline(v=70, lty=3)

And what I get / want:

Any  help is appreciated!

A: Use lines. Set limits of y as you want.
plot(100, 100)
par(xpd = TRUE)
lines(x = c(70,70), y = c(45, par('usr')[4]), lty = 2)
# par('usr') gives the 4 extremes of plot
# par('usr')[4] gives the extreme on top

Another option is to not mess with xpd and use axis instead. Use tck to define the length of line beyond the plot. tck = -0.25 means the length is one fourth of the plot height towards bottom.
plot(100, 100)
par(xpd = FALSE) #Only because we made TRUE above
abline(v = 70, lty = 2)
axis(1, at = 70, labels = NA, tck = -0.25, lty = 2)


text:
Q: Adding dynamic elements I am using the code bellow to use the Jquery UI Slider.

How can add multiple sliders with a button? I want to add slider elements when I click the button bellow.

And how can I control them? This single slider has a jQuery code to work...

A: $("#adding").click(function() {
    $("
").slider({
        // options
    }).appendTo("#sliderContainer");
});


text:
Q: How expensive is the IsInvokeRequired Is there any documentation on exactly how expensive it is:
if (x.IsInvokeRequired)
{
    beginInvoke . . . .
}

*

*If you have a case where 90% of the time is on a background thread (and thus required) is it worth it?

*If you have a case where 90% of the time is on a UI thread (and thus not required) is it worth it?

Any metrics around this would be great.

A: Real Answer:
Use a profiler
Fuzzy Answer:
I think you need to consider the relative costs of both functions vs. the absolute cost of InvokeRequired.
InvokeRequired for Control essentially compares the current ThreadId with the expected ThreadId.  If you look in reflector the code is slightly more complex but in effect that's what it's doing.  This is fairly cheap as it's just a few function calls and a comparison.
BeginInvoke involves taking several locks, adding delegates to an invoke queue and potentially a Marshal between threads.  This code is much more expensive relative to the actual InvokeRequired call (likely an order of magnitude or 2).  You would need a great deal more calls where InvokeRequired returns true before you would see any gain by just going straight to BeignInvoke.

A: No metrics, but a quick trip into Reflector tells us that the call is most likely not very expensive at all:
[SRDescription("ControlInvokeRequiredDescr"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
        public bool InvokeRequired
        {
            get
            {
                using (new MultithreadSafeCallScope())
                {
                    HandleRef ref2;
                    int num;
                    if (this.IsHandleCreated)
                    {
                        ref2 = new HandleRef(this, this.Handle);
                    }
                    else
                    {
                        Control wrapper = this.FindMarshalingControl();
                        if (!wrapper.IsHandleCreated)
                        {
                            return false;
                        }
                        ref2 = new HandleRef(wrapper, wrapper.Handle);
                    }
                    int windowThreadProcessId = SafeNativeMethods.GetWindowThreadProcessId(ref2, out num);
                    int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
                    return (windowThreadProcessId != currentThreadId);
                }
            }
        }

It's likely best to make the check regardless of the usage, as any performance gain from this sort of micro-optimization would be more than offset by the risk of an issue popping up.

A: InvokeRequired's cost depends on which class is implementing ISynchronizeInvoke, and the specific usage case.  The "cost" will very depending on the implementation you are using.  However, in general, it's typically a fairly low overhead call.  (In many cases, it can be as simple as a check to see if the current thread is the same as the original thread.)
That being said, if you need it, it's worth the cost, ALWAYS.  Even if it's only 1% of the time that it will be required, it should be included.  Otherwise, you are asking for a crash, lock, or some other very undesirable behavior.  Most cases where you could be using this are cases where you should always include this cost.
The most common use case is synchronizing delegates onto the UI thread.  In this case, you must use it, or very bad things happen...  Also, in this case, the cost is very low compared to the waiting on the message pump for UI interactions, so it's really not worth worrying about.
If you are using it with a custom implementation of ISynchronizeInvoke, and it's happening in a tight loop, AND you've profiled and found that it's causing problems for you, then it may be worth worrying about.  In this case, though, I would recommend trying to rework the algorithm itself to avoid the need for synchronizing as much as possible, but still use InvokeRequired as needed.


text:
Q: ¿Cómo convertir encriptación usando BouncyCastle de C# a Java? Tengo el siguiente código de encriptación en C#
IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding");
cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", keyBytes), counter));
byte[] encryptedBytes = cipher.DoFinal(inputBytes);

return encryptedBytes;

Deseo convertir a su sintaxis correspondiente a Java, pero en Java no existe CipherUtilities, ni tampoco el objeto recibe en el método Init un ParametersWithIV.


text:
Q: calculate if number bigger than defined percent of numbers in list without storing list in memory after first calculation I have percent value and list with fixed length (mean that list must always has same length). In loop inputting x with type int. Task is to know if x is bigger than %
of elements, after delete first element and append to end inputted x.
My code:
needed_percent = .9975
arr = [x for x in range(1, 10_000+1)]

while True:
    x = int(input('Enter number: '))
    count_less_than_x = 0
    for n in arr:
        if x > n:
            count_less_than_x += 1
    percent = count_less_than_x / len(arr)

    if percent >= needed_percent:
        print(f'Yes! Input number={x} bigger than {needed_percent*100}% elements in list')
    else:
        print(f'No. Input number={x} less than {needed_percent*100}% elements in list')

    del arr[0]
    arr.append(x)

Some test for example:
Enter number: 1000
No. Input number=1000 less than 99.75% elements in list
Enter number: 9990
Yes! Input number=9990 bigger than 99.75% elements in list
Enter number: 9975
No. Input number=9975 less than 99.75% elements in list
Enter number: 9976
No. Input number=9976 less than 99.75% elements in list
Enter number: 9977
Yes! Input number=9977 bigger than 99.75% elements in list
Enter number: 9977
No. Input number=9977 less than 99.75% elements in list
Enter number:

It's working alright... in this case, but in other real case i have few thousands of arrays and 300k elements in each.
I don't want to store array in memory after running loop if it's even possible. Other words i hope that there is some math solution to calculate some value before loop, delete array from memory and then get same results on every iteration.
Please, write feedback what do you think about possibility of this even if you think (or sure) it's impossible

A: A couple of options:

*

*Store the list in an sqlite database, and run a query to get the result. That should be memory efficient and not require storing the list in memory.

*If you want a simpler alternative to one, you could store the list in a file and read the values one at a time from the file, although deleting the first entry will be trickier in this case. a) You could overwrite the value with a string that you will know to skip when you read it next time. b) or you could create a new file as you read values from the current file and insert the values skipping the first one, and appending the new value to it. Then deleting the file you read from.


text:
Q: Keyword search in linq I have three fields in a form on the view:
[Textfield] : Name
[Dropdown]  : Sector
[Dropdown]  : Country

My requirement is to filter the results via these three keywords in the controller method, and also order the result first by received date and then by name.
There are so many possibilities, eg: if Name matches and Sector matches do filtering etc.
I can do it with if else or with any other cumbersome way, but how can I do this in LINQ in one statement. I need to return a list.

A: If you need just simple search to find out that some of your columns contains specified string, try something like this.
// dc is some datacontext
var query = dc.MyEntities.Where(x=> x.Name.Contains(inputName) ||
                                    x.Sector.Contains(inputSector) ||
                                    x.Contry.Contains(inputCountry))
                         .OrderBy(x=> x.receivedDate)
                         .ThenBy(x=> x.Name);
var resultList = query.ToList();

Also check (set) the collation of your database to do case sensitive (CS) or case insensitive (CI) search - according to your needs. However to do case insensitive search on CS collation you will need extend the code above with ToUpper().
x.Name.ToUpper().Contains.(inputName.ToUpper());

But beware, it won't pass the Turkey test :-) - there is something weird with uppercasing their i and lowercasing I.
Here is also interesting resource on case insensitive .Contains(string): Case insensitive 'Contains(string)'
If you need some sophisticated full text search. I would look for:

*

*TSQL full text search - but it needs some effort to make it work with LINQ to SQL: Is it possible to use Full Text Search (FTS) with LINQ?

*LUCENE.NET is also good option for fulltext search. But it is not integrated with LINQ (however you can try this project: LinqToLucene - but it is currently Alpha version)

A: Have a look at this solution and see if it helps you to achieve your desired goal: search keywords using linq

A: Thanks everyone who answered my question. Found the answer what i was looking for below and hope it will help others.
http://blog.tech-cats.com/2008/01/using-optional-parameters-in-sql-server.html


text:
Q: Filenet Bulk Actions Script via API I know there is a great way to access the bulk action on acce.
Access the object store search in the administration console
On the SQL view tab, enter an appropriate query.
On the Bulk Actions tab, select Enable.
In the Script section, select Run script.
Enter your JavaScript code into the Script field. For more information, see an example below.
Click Run. The administration console runs the query and the JavaScript action.
What I was wondering is there a way to Access this same thing via the api?
AKA via api feed it a query and then feed it a script and watch it run


text:
Q: Clickhouse: Should i optimize MergeTree table manually? I have a table like:
create table test (id String, timestamp DateTime, somestring String) ENGINE = MergeTree ORDER BY (id, timestamp)
i inserted 100 records then inserted another 100 records and i run select query
select * from test clickhouse returning with 2 parts their lengths are 100 and they are ordered in themselves. Then i run the query optimize table test and it started to return with 1 part and its length is 200 and ordered. So should i run optimize query after all insert and does it increase select query performance like select count(*) from test where id = 'foo' ?

A: Merges are eventual and may never happen. It depends on the number of inserts that happened after, the number of parts in the partition, size of parts. If the total size of input parts are greater than the maximum part size then they will never be merged.
It is very unreasonable to constantly merge up to one part.
Merger does not have such goal. In the contrary the goal is to have the minimum number of parts withing smallest number of merges. Merges consume the huge amount of disk and processor resources.
It makes no sense to merge two 300GB parts into one 600GB part for 3 hours. Merger have to read, decompress 600GB, merge, compress, write them back, after that the performance of the selects will not grow at all or will grow minimally.

A: Usually not, you can rely on Clickhouse background merges.
Also, Clickhouse has no intention to merge all the data from the partition into one part file, because "over-optimization" can affect performance too


text:
Q: Knapsack with weight and item limit if I have a knapsack with weight limit W, item Limit K and I have N items, N >= k
I know how to maximize it in by having a 3 dimensional memorization array m[N][W][K] (N items to consider, W weight left, K items left to choose from) and thus do it in O(N * W * K) complexity but is there way to do it even faster in a 2 dimensional memorization array and achieve a faster complexity, something like O(N * W) complexity?

A: The memoization you are using is not correct: "m[N][W][K] (N items to consider, W weight left, K items left to choose from)". It does not capture the complete information of which items are left to choose from versus how many items are left to choose from.
The problem you are trying to solve is the Multi dimensional knapsack, which is more complex than the classic problem.


text: Q: Django.Подключение liqpay Доброго времени суток) Начинаю делать интернет магазин в рамках обучения Django.Возник вопрос как подключить систему оплаты к примеру liqpay.Подскажите в каком направлении смотреть или какая технология этого процесса. Материала крайне мало(


text:
Q: How to create private variable accessible to Prototype function? I'm trying to get a deeper hold on prototypal inheritance and class creation (I know, there are other ways, but for the purpose of this I'm trying to grasp prototypes.) My question is: Using the following code example, is there a way to create private variables inside of Tree and Fruit that will not be returned with the function, but is still accessible to the prototype functions genus and bulk?
var Tree = function ( name, size ) {
    this.name = name;
    this.size = size;
};

Tree.prototype.genus = function(){
    return ((typeof this.name !== 'undefined') ? this.name : 'Hybridicus Maximus');
};
Tree.prototype.bulk = function(){
    return ((typeof this.size !== 'undefined') ? this.size : '8') + ' ft';
};

var Fruit = function( name, size ) {
    this.name = name;
    this.size = size;
};

Fruit.prototype = new Tree();
// Fruit.prototype = Tree.prototype; -- I know this can be used, too.

Fruit.prototype.bulk =  function(){
    return ((typeof this.size !== 'undefined') ? Math.floor(this.size / 2) : '4') + ' lbs';
};

var pine = new Tree('Pine', 9);
var apple = new Fruit('Apple', 6);

console.log(pine.genus(), pine.bulk()); // Outputs: "Pine 9 ft"
console.log(apple.genus(), apple.bulk()); // Outputs: "Apple 3 lbs"

EDIT: I'm trying to replace this.name and this.size with private variables that can be accessed in the prototype functions. Sorry for the lack of clarity!

A: This is what I wrote about in a blog post about Classes, Private Members, & Prototypal Inheritance in JavaScript.  Basically you want to create a private variable accessor function unique to every object and then have those prototype methods call that private accessor function, supplying it with the key that is only available within the closure:
(function(_) {
  Tree = function ( name, size ) {
    var hidden = {
      name: name,
      size: size
    };
    this._ = function($) {
      return _ === $ && hidden;
    };
  };

  Tree.prototype.genus = function(){
    return ((typeof this._(_).name !== 'undefined') ? this._(_).name : 'Hybridicus Maximus');
  };
  Tree.prototype.bulk = function(){
    return ((typeof this._(_).size !== 'undefined') ? this._(_).size : '8') + ' ft';
  };

  Fruit = function( name, size ) {
    Tree.apply(this, arguments);
  };
  Fruit.prototype = new Tree();
  // Fruit.prototype = Tree.prototype; -- I know this can be used, too.

  Fruit.prototype.bulk =  function(){
    return ((typeof this._(_).size !== 'undefined') ? Math.floor(this._(_).size / 2) : '4') + ' lbs';
  };
})({});

var pine = new Tree('Pine', 9);
var apple = new Fruit('Apple', 6);

console.log(pine.genus(), pine.bulk()); // Outputs: "Pine 9 ft"
console.log(apple.genus(), apple.bulk()); // Outputs: "Apple 3 lbs"

console.log(pine._(), pine._({})); // Outputs: "false false" because outside of closure

You will notice that the last line shows that private variables are not accessible outside of the closure and thusly can't be retrieved by third-party code unless made available by an accessor function.

A: Yes.  You can do this:
(function() {
  var private = "hi";

  Tree.prototype.genus = function(){
    return ((typeof this.name !== 'undefined') ? this.name : 'Hybridicus Maximus');
  };
  Tree.prototype.bulk = function(){
    return ((typeof this.size !== 'undefined') ? this.size : '8') + ' ft';
  };
})();

Now, that'll provide a private variable that those functions can see, but it'll be a private "class" variable - all instances will share the same variable, in other words. If you want a private variable per instance, you have to do that in the constructor (or "init" method, or whatever), meaning the methods that share those privates would also have to be created there. (You could of course put a function on the prototype that would create the instance methods at construction time.)
edit — One thing you could do is use a technique like this to build a mechanism like jQuery's ".data()", so that you'd have a class variable that acts as a place to keep per-instance values.  It'd be kind-of clunky, but it'd be workable.

A: It can be easily achieved like this
function SharedPrivate(){
  var private = "secret";
  this.constructor.prototype.getP = function(){return private}
  this.constructor.prototype.setP = function(v){ private = v;}
}

var o1 = new SharedPrivate();
var o2 = new SharedPrivate();

console.log(o1.getP()); // secret
console.log(o2.getP()); // secret
o1.setP("Pentax Full Frame K1 is on sale..!");
console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
o2.setP("And it's only for $1,795._");
console.log(o1.getP()); // And it's only for $1,795._

Obviously the key point is to create an access route to a private variable by utilizing a closure and then sharing this access point among the objects to be created. Utilizing the access point as a prototype of the objects to be created for natural sharing is the ideal case. Accordingly  the same functionality can be achieved by utilizing the factory pattern and Object.create() as follows;
function SharedPrivate(){
var priv = "secret";
return {gp : function(){return priv},
        sp : function(v){priv = v}
       }
}
sharedProto = SharedPrivate(); // priv is now under closure to be shared
var p1 = Object.create(sharedProto); // sharedProto becomes o1.__proto__
var p2 = Object.create(sharedProto); // sharedProto becomes o2.__proto__

JavaScript prototypical structure is golden..!

A: i made up this based on your title of question, not the content you gave. i had the same question here.
var Tree = function(){

    var outprivatename = "bigsecret"

    var Tre = function(nickname){
        var privatename = "secret that no one should know"
        this.nickname = nickname
        outprivatename = outprivatename + "-->" + nickname
        this.deepsecret=function(){return privatename + "---" + nickname}
    }

    Tre.prototype.getname=function(){
        console.log(outprivatename+'-----'+this.nickname)
        // console.log(privatename)
      return this.nickname
    }
    return Tre

}
//case one: each has unique closure; `outprivatename` is different for them
var pine = new (Tree())('pine')
var apple = new (Tree())('apple')
pine.getname() //bigsecret-->pine-----pine
apple.getname() //bigsecret-->apple-----apple
console.log(pine.deepsecret()) //secret that no one should know---pine
console.log(apple.deepsecret()) //secret that no one should know---apple

//case one: two share one closure; `outprivatename` is same for both
var Hybrid = Tree()
var hybrid1 = new Hybrid("pinapple1")
var hybrid2 = new Hybrid("pinapple2")

hybrid1.getname() //bigsecret-->pinapple1-->pinapple2-----pinapple1
hybrid2.getname() //bigsecret-->pinapple1-->pinapple2-----pinapple2
console.log(hybrid1.deepsecret()) //secret that no one should know---pinapple1
console.log(hybrid2.deepsecret()) //secret that no one should know---pinapple2

basically the Tree function provided a closure for the constructor Tre inside of it. Instead of using the deepest privatename, you can use the one that's outside of Tre but inside of the anonymous function Tree.


text:
Q: How do i report to toolStripStatusLabel text a string value using a backgroundworker? In this method i want to make the report:
private int reportingmethod()
{
   if (result.Contains("forumPage"))
                        {
                            toolStripStatusLabel1
                            int index2 = result.IndexOf("\" text");
                            result = result.Remove(index2);
                            Names.Add(result);
                        }
}

I want to report the value in the variable result.
In backgroundworker dowork event:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            reportingmethod();
        }

And a button click event that start the backgrounworker:
private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

Then in the background progress changed event i did:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripStatusLabel1.Text = e.Result.ToString();
        }

First i'm not sure getting the Result like i did in the progress changed event is the right way.
Second how do i pass the result from the Do Work event ?
And third how do i report the result value from the reportingmethod ?
I never used before this toolStripStatusLabel with backgroundworker.

A: You need to disable this property:
Control.CheckForIllegalCrossThreadCalls = false;

Then you can edit any value while the worker is running.


text:
Q: Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected end of file (Laravel) The master.blade.php's file contains:
@section('content')
  @foreach($admons as $admon)

{{ $admons->admon }}

  @foreach
@stop

and it is throwing me the error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException
syntax error, unexpected end of file

C:\AppServ\www\Viniza\app\storage\views\b48f03c3d0a952af7b5dd24750898f94

 $(document).ready(function() {
$('ul.sf-menu').sooperfish();
$('.top').click(function() {$('html, body').animate({scrollTop:0}, 'fast'); return false;});
});
</script>

the full content of master.blade.php's file is:
{{ HTML::style('css/style.css') }}
{{ HTML::script('js/jquery.js') }}

@section('content')
  @foreach($admons as $admon)

{{ $admons->admon }}

  @foreach
@stop

<!DOCTYPE HTML>

  <title>Viniza Konw</title>
  <meta name="keywords" content="coffee buy shop" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

CoffeJuanValdez

Home

          {{ HTML::image('images/header_image.jpg', "Imagen no encontrada",
            array('id' => 'center', 'title' => 'center')) }}

Copyright © CSS3_winter_scene | design from css3templates.co.uk

A: This error in Symphony is usually telling you that you didn't 'end' a control structure (i.e. an 'if' or 'foreach').
You have a couple typos, where you are ending your foreach with "@foreach" it should be "@endforeach".
That should do it for you.

A: In my case, it was the silliest mistake. I missed out a ; while creating a route with a closure function.
So, if you've not made any mistakes as pointed out by above 2 answers, look for any syntax error in your routes\web.php (Laravel 5.3+)

A: I just ran into the same error and it was due to a GIT conflict.
So if the first answer doesn't fix the problem, look for "<<< HEAD" in your code


text:
Q: Preselecting value in select2 Texbox is dynamically filled with a remote call using Select2 and how do I set preselected value. Here is the code
<input type="hidden" id="e6">

$("#e6").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: {
        url: url,
        dataType: 'jsonp',
        data: function (term, page) {
            return {
                q: term, // search term
                page_limit: 10, };
        },
        results: function (data, page) {
                return {results: data};
        }
    }
});

I tried this to preselect value 1049
$('#e6').select2('val', '1049');
but this doesn't set the value on the textbox.
Any ideas?

A: The solution that worked for me (and that is decribed in the documentation) was:
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

A: I got it to work with
$("#e6").val("input id of the select2 option here").trigger("change")

A: in 2019 this worked for me
    // Create a DOM Option and pre-select by default~
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');

A: In case anybody wants to know how to solve this
$("#e6").select2('data', {id: '1049', text: 'MyLabel'});

A: You can use initSelection method
initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},

Check this link and loading remote data section here

A: for multiple selection...
var li = $("#e6");
li.select2({
    placeholder: "Placeholder"
});

var unselected = li.find('option:not(:selected)');
var selected = [];
for (var i = 0; i < unselected.length; i++) {
    selected[i] = { id: unselected[i].value, text: unselected[i].text };
}
li.select2('data', selected);

A: This worked for me
<script>
  $(function() {
    if (window.formPrefill) {
      // setTimeout to force script to run when all the stack on doc.ready is complete.
      setTimeout(() => $(".js-select2-companies").select2('data', window.formPrefill), 10);
    }
  })
</script>

A: According to documentation, you can do it like this for multiple preselection:
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

https://select2.org/programmatic-control/add-select-clear-items

A: in my case, my selected values were saved with comma seperated in my database so i used this approach and it worked for me
        var ele = document.getElementById('farmProduce');
        let val =ele.getAttribute('value')
        for(i=0; i < len; i++){
            ele.innerHTML = ele.innerHTML + '<option value="' + farm_produce[i].name + '"' + (val.includes(farm_produce[i].name) ? 'selected="'+true+'"' : null)+'>' + farm_produce[i].name + '</option>';
        }

so essentially, just setting the selected attribute to true and false for each option did the tricks for me


text:
Q: How to make all horizontal child div's to fit to the parent? Here is my HTML snippet,

A

B

C

If I have a CSS like:
.bigger
{
  height: 300px;
}

Is there any way in CSS to make all child div's to have height same as of parent i.e all should have 300px height?

A: If you want to realize this in purely CSS you could try this
DEMO
I've set it up for 4 items. You could extend it to as many items you want.
/* one item */
.bigger > div:first-child:nth-last-child(1) {
    height: 300px;
}

/* two items */
.bigger > div:first-child:nth-last-child(2),
.bigger > div:first-child:nth-last-child(2) ~ div {
    height: 150px;
}

/* three items */
.bigger > div:first-child:nth-last-child(3),
.bigger > div:first-child:nth-last-child(3) ~ div {
    height: 100px;
}

/* four items */
.bigger > div:first-child:nth-last-child(4),
.bigger > div:first-child:nth-last-child(4) ~ div {
    height: 75px;
}

A: A solution using Flexbox:
.bigger {
  height: 400px;
  background: #eea;

  display: flex;
  flex-direction: column;
}

.bigger div {
  margin: 4px;
  border: 1px dotted green;
  flex: auto;
}

Demo: http://codepen.io/anon/pen/nAjLt
(Note that Codepen does vendor prefixing)

A: .bigger {
    width:100%;
    height:auto;
    border:1px solid red;
}
.bigger div {
    height:100px;
    width:100%;
    border:1px solid blue;
}

Use this css, for your purpose, By setting height to auto it will adjust to any no of divs.
Also  .bigger div will set all the div to 100px height.
Live Demo
EDIT : For Fixed Container
.bigger {
    width:100%;
    height:300px;
    border:1px solid red;
    display:table;
}
.bigger div {
    display:table-row;
    height:auto;
    width:100%;
}

Live Demo2
Also it will be same for all the browsers :)

A: Allowing elements to take up equal amounts of space is something that's traditionally only been possible with the use of
s. You can, however, use CSS to make your
s behave like
s instead:
HTML

A

B

C

A

B

C

(relevant) CSS
.bigger {
    display: table;
    height: 300px;
    width: 100%;
}

.bigger > div {
    display: table-row;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
}

A: To work with child and parents, you need to use auto and max

A

B

C

Here you can use
.bigger {
  height: auto; // this will do the trick..
  overflow: none;
  min-height: 300px;
}

Use max and min, only to make sure the height remains same each time the child increases or descreases, then use this:
.bigger div {
  height: 100%; // note this..
}

Try out this fiddle here: http://jsfiddle.net/afzaal_ahmad_zeeshan/2bJfW/ Add a div more to it and check the thing,
If you want to create the div height dynamically, then there is no CSS, you will require JS or lets say jQuery for that. Because you will need to count the number of child and then change the percentage of their height, lets say from 100 to 30 (for 3) or 22 for (4) and so on, because the text won't get fit in that size.

A: .bigger
{
  height: auto;
}
.bigger div
{
height:50px;
}

You should mentioned height of each inner div,then only it works properly.
Now u add another inner div elements inside of bigger div the height should be same.
Here I have mentioned height 50px, u give at what height you wants.


text:
Q: arm; VFP; Floating-point Extension; Undefined Instructions; I have a device on ARM cortex-a9 and trying to implement "lazy float switching" for OS for this device. "lazy switching" is when

*

*VFP support is disabled,

*thread tries to execute any VFP instruction and generates exception,

*exception handler turn on VFP, manage thread context & return so the same instruction will be tried again,

*scheduler turns off VFP before switching threads.

The problem is that almost all VFP instructions generate synchronous exception when VFP is enabled.
Simply speaking
vadd.f32    s19, s19, s17

at first exception handler enables VFP and returns to retry vadd.f32 s19, s19, s17, the user-space code generates another exception
at second time generate synchronous exception.
Exception Register, FPEXC is FPEXC.EX == 0, FPEXC.EN == 1, FPEXC.DEX == 1
And I could not understand what is the reason for this synchronous exception. I checked that

*

*Interrupts are disabled FPSCR[15, 12-8] == 0;

*VFPv3 is presented and implements full hardware FPU instruction set;

*MVFR0 & MVFR1 are also indicate that all features are implemented and software simulation is not required.

Any ideas what could be the reason of these extra exceptions?

PS:
apps are build w/ -mcpu=cortex-a9 -marm -mfpu=vfpv3-fp16 -mfloat-abi=hard -ffast-math;
vpush..., vldr... generate exception only when VFP is off (behave as expected)

A: According to the Cortex-A9 FPU docs, the only reason for FPEXC.DEX to be set is if the thing was incorrectly configured to attempt short vector operations. The "V" in VFP has been deprecated since NEON came about, and isn't supported at all on anything newer than Cortex-A8.
You need to make sure that FPSCR.Len and FPSCR.Stride* are set to 0.
* OK, so strictly the value of Stride shouldn't matter when Len == 0, but hey, there's no good reason not to...


text:
Q: Trace the Repository 's Get method with SQLPROFILER I have a performance issue caused by a latency in return from  the Repository 's Get method .
  var res = Data.TicketRepository.GetSingle(filterExpression, includeNavigations);

So i configured a trace on my database to view the sql statement generated by that linq-to-sql function.
However after the debugger finish with that method i don't get any trace  in the profiler.
what m i doing wrong ?
Is it possible for the profiler to track the execution that have been triggred outside of SSMS ?

A:
Is it possible for the profiler to track the execution that have been triggred outside of SSMS ?

Yes.  You're doing something wrong.  Profiler can track activity from every session.
If you discover your sessions session_id by running select @@spid, you can filter that in Profiler.


text:
Q: Does member initialization list copy string C++ if I use member initialization list in my constructor of a class that has char* in it, does it copy the value to a new allocated memory or just points the pointer on the same value?
ex.
MyString::MyString(const MyString & other) : m_str(other.m_str) {}

will this be fine or should I run cell by cell to copy the info?
EDIT: just to clarify the question I changed a line.

A: I just copies the pointer, so they will both point to the same string.
This will likely cause you problems if you later want to delete the pointed-to string.

A: It does both:

*

*It copies the pointer.

*The copy of the pointer points to the same thing as the original.

A: A pointer variable is (in a very simplistic way of looking at it) basically nothing more than an integer variable that is handled specially by the compiler. The contents of a (initialized) pointer variable is the address to where it points in memory.
If you initialize one pointer variable to the contents of another pointer variable, you copy the contents, leading to two different variables both having the same content and both pointing to the same memory.


text:
Q: MapChart with "countries/us/us-all" I can't bind the high map us all countries.
I am having error in data series, below is my map configuration.
importing files
import { MapChart } from 'angular-highcharts';
import * as Highcharts from 'highcharts/highmaps';
import * as usJson from 'src/assets/maps/us-all.geo.json';

map configuration
new MapChart({
            chart: {
                map: usJson
            },
            title: {
                text: "Highmaps basic demo"
            },
            subtitle: {
                text:
                    'Source map: World, Miller projection, medium resolution'
            },
            mapNavigation: {
                enabled: true,
                buttonOptions: {
                    alignTo: "spacingBox"
                }
            },
            legend: {
                enabled: true
            },
            colorAxis: {
                min: 0
            },
            series: [
                {
                    type: 'mappoint',
                    mapData: usJson,
                    name: 'Cities',
                    data: [
                        {
                            "value": 438,
                            "code": "nj"
                        },
                        {
                            "value": 387.35,
                            "code": "ri"
                        }
                    ]
                }],

        });
    }

}

Also added highmaps module in app module file.
*here is all series data link.
https://cdn.jsdelivr.net/gh/highcharts/highcharts@v7.0.0/samples/data/us-population-density.json


text:
Q: unit testing package naming convention Is there even a standard convention for this? I see a lot of different and perhaps misguided package naming that is very mixed in some projects and thus is never consistent:
Let's say I want to write unit tests for something that falls under the 'stuff' package.
 com.company.product.amodule.submodule.stuff

The unit test could be one of these possibilities (or even somewhere between):

*

*com.company.test.product.amodule.submodule.stuff

*com.company.product.amodule.submodule.stuff.test

A: I tend to keep the tests in the same namespace/package as the code it's testing, but in a different project.

A: Have it inside the same namespace (package). I like maven convention to separate source folders
src root-folders:

*

*production code: src/main/...

*test code: src/test/...

You can map this to your own build-system


text:
Q: Centroid distance calculation in PCA space and in 'feature-space' diverge I'm measuring the centroids of a PCA-space and a 'feature-space' spanning ~20 treatments and 3 groups. If I understood my maths teacher correctly the distance between them should be identical. However in the way I calculate them they're not and I was wondering if the way I do the math, either of them is wrong.
I use the notorious wine dataset as an illustration for my method/MWE:
library(ggbiplot)
data(wine)
treatments <- 1:2 #treatments to be considerd for this calculation
wine.pca <- prcomp(wine[treatments], scale. = TRUE)
#calculate the centroids for the feature/treatment space and the pca space
df.wine.x <- as.data.frame(wine.pca$x)
df.wine.x$groups <- wine.class
wine$groups <- wine.class
feature.centroids <- aggregate(wine[treatments], list(Type = wine$groups), mean)
pca.centroids <- aggregate(df.wine.x[treatments], list(Type = df.wine.x$groups), mean)
pca.centroids
feature.centroids
#calculate distance between the centroids of barolo and grignolino
dist(rbind(feature.centroids[feature.centroids$Type == "barolo",][-1],feature.centroids[feature.centroids$Type == "grignolino",][-1]), method = "euclidean")
dist(rbind(pca.centroids[pca.centroids$Type == "barolo",][-1],pca.centroids[pca.centroids$Type == "grignolino",][-1]), method = "euclidean")

The last two lines return 1.468087 for the distance in the feature-space and 1.80717 within the pca-space, indicating there's a fly in the ointment...

A: It's because of scaling and centering, if you don't do scaling and centering the distance will be exactly same in the original and PCA feature space.
wine.pca <- prcomp(wine[treatments], scale=FALSE, center=FALSE)

dist(rbind(feature.centroids[feature.centroids$Type == "barolo",][-1],feature.centroids[feature.centroids$Type == "grignolino",][-1]), method = "euclidean")
#         1
# 2 1.468087
dist(rbind(pca.centroids[pca.centroids$Type == "barolo",][-1],pca.centroids[pca.centroids$Type == "grignolino",][-1]), method = "euclidean")
#         1
# 2 1.468087

Another way is to get the same result is to scale / center the original data and then apply PCA with scaling / centering like the following:
wine[treatments] <- scale(wine[treatments], center = TRUE)
wine.pca <- prcomp(wine[treatments], scale = TRUE)

dist(rbind(feature.centroids[feature.centroids$Type == "barolo",][-1],feature.centroids[feature.centroids$Type == "grignolino",][-1]), method = "euclidean")
#        1
# 2 1.80717
dist(rbind(pca.centroids[pca.centroids$Type == "barolo",][-1],pca.centroids[pca.centroids$Type == "grignolino",][-1]), method = "euclidean")
#        1
# 2 1.80717


text:
Q: AWS RDS SQL Server - distributing queries to read-replicas We are using AWS RDS SQL Server and need some help with solving the following problem - how to handle heavy read queries and prevent the report queries from blocking the rest of the operations.
We were hoping RDS Multi-AZ would solve this problem for us, but it turned out Multi-AZ for SQL Server does not create readable replicas.

A: Database Migration Service doesn't really help with MSSQL on RDS(1).
You can replicate once, but cannot do any continuous replication due to how RDS is locked down.
I have found this product to be looking somewhat useful: CloudBasic RDS AlwaysOn
(1)http://docs.aws.amazon.com/dms/latest/userguide/CHAP_Introduction.Sources.html

A: You can use the Amazon Database Migration Service to create a readable replica. https://aws.amazon.com/dms/
As per the FAQ's:
Q. In addition to one-time data migration, can I use AWS Database Migration Service for continuous data replication?
Yes, you can use AWS Database Migration Service for both one-time data migration into RDS and EC2-based databases as well as for continuous data replication. AWS Database Migration Service will capture changes on the source database and apply them in a transactionally-consistent way to the target. Continuous replication can be done from your data center to the databases in AWS or in the reverse, replicating to a database in your datacenter from a database in AWS. Ongoing continuous replication can also be done between homogenous or heterogeneous databases. For ongoing replication it would be preferable to use Multi-AZ for high-availability.