text:
Q: How to pass String value to java from cmd (maven project)? I need to pass String value (jbehave story file name) to .java file from cmd. Something like this:
mvn verify -PMyTests -DstoryName=purchasing.story

To use in java in that way:
System.out.println(storyName);

My setup:
Now tests being launched by
mvn verify -PMyTests

pom.xml file structure:
...
<dependencies>
    ...
</dependencies>
<build>
    ...
<build>

<profiles>
    <profile>
        <id>MyTests</id>
        <build>
            <plugins>
                ...
            </plugins>
        </build>
    </profile>

MyStories.java:
public class MyStories extends JUnitStories {
    ...
    @Override
    protected List<String> storyPaths() {
        return new StoryFinder()
            .findPaths(codeLocationFromClass(embeddableClass).getFile(), asList(
                    "**/purchasing.story"
                    ), null);
    }
}

Tried these topics: Is there a way to use maven property in java class during compilation, How to pass java code a parameter from maven for testing, but with no result.
Straightforward tutorials, search tips or documentation with examples appreciated.
P.S. Found solution which is simple enough and works for me: http://syntx.co/languages-frameworks/how-to-pass-parameters-to-the-junit-tests-from-the-maven-surefire-plugin/
Solution provided in comments (topic which I "duplicated") is more complex than this one so it is easier for novice to make mistake implementing it

A: You need to read the System property like this:
public class MyStories extends JUnitStories {
    ...
    @Override
    protected List<String> storyPaths() {
        String storyName = System.getProperty("storyName");
        return new StoryFinder()
            .findPaths(codeLocationFromClass(embeddableClass).getFile(),
                       asList("**/" + storyName),
                       null);
    }
}


text:
Q: What's the deal with all the Either cruft? The Either class seems useful and the ways of using it are pretty obvious. But then I look at the API documentation and I'm baffled:
def joinLeft [A1 >: A, B1 >: B, C] (implicit ev: <:<[A1, Either[C, B1]]):
         Either[C, B1]
   Joins an Either through Left.

def joinRight [A1 >: A, B1 >: B, C] (implicit ev: <:<[B1, Either[A1, C]]):
         Either[A1, C]
   Joins an Either through Right.

def left : LeftProjection[A, B]
   Projects this Either as a Left.

def right : RightProjection[A, B]
   Projects this Either as a Right.

What do I do with a projection and how do I even invoke the joins?
Google just points me to the API documentation.
This might just be a case of "paying no attention to the man behind the curtain", but I don't think so. I think this is important.

A: left and right are the important ones. Either is useful without projections (mostly you do pattern matching), but projections are quite worthy of attention, as they give a much richer API. You will use joins much less.
Either is often used to mean "a proper value or an error". In this respect, it is like an extended Option . When there is no data, instead of None, you have an error.
Option has a rich API. The same can be made available on Either, provided we know, in Either, which one is the result and which one is the error.
left and right projection says just that. It is the Either, plus the added knowledge that the value is respectively at left or at right, and the other one is the error.
For instance, in Option, you can map, so opt.map(f) returns an Option with f applied to the value of opt if it has a one, and still None if opt was None. On a left projection, it will apply f on the value at left if it is a Left, and leave it  unchanged if it is a Right. Observe the signatures:

*

*In LeftProjection[A,B], map[C](f: A => C): Either[C,B]

*In RightProjection[A,B], map[C](f: B => C): Either[A,C].

left and right are simply the way to say which side is considered the value when you want to use one of the usual API routines.
Alternatives could have been:

*

*set a convention, as in Haskell, where there were strong syntactical reasons to put the value at right. When you want to apply a method on the other side (you may well want to change the error with a map for instance), do a swap before and after.

*postfix method names with Left or Right (maybe just L and R). That would prevent using for comprehension. With for comprehensions (flatMap in fact, but the for notation is quite convenient) Either is an alternative to (checked) exceptions.

Now the joins. Left and Right means the same thing as for the projections, and they are closely related to flatMap. Consider joinLeft. The signature may be puzzling:
joinLeft [A1 >: A, B1 >: B, C] (implicit ev: <:<[A1, Either[C, B1]]):
         Either[C, B1]

A1 and B1 are technically necessary, but not critical to the understanding, let's simplify
joinLeft[C](implicit ev: <:<[A, Either[C, B])

What the implicit means is that the method can only be called if A is an Either[C,B]. The method is not available on an Either[A,B] in general, but only on an Either[Either[C,B], B]. As with left projection, we consider that the value is at left (that would be right for joinRight). What the join does is flatten this (think flatMap). When one join, one does not care whether the error (B) is inside or outside, we just want Either[C,B]. So Left(Left(c)) yields Left(c), both Left(Right(b)) and Right(b) yield Right(b). The relation with flatMap is as follows:
joinLeft(e) = e.left.flatMap(identity)
e.left.flatMap(f) = e.left.map(f).joinLeft

The Option equivalent would work on an Option[Option[A]],  Some(Some(x)) would yield Some(x) both Some(None) and None would yield None. It can be written o.flatMap(identity). Note that Option[A] is isomorphic to Either[A,Unit] (if you use left projections and joins) and also to Either[Unit, A] (using right projections).

A: Ignoring the joins for now, projections are a mechanism allowing you to use use an Either as a monad. Think of it as extracting either the left or right side into an Option, but without losing the other side
As always, this probably makes more sense with an example. So imagine you have an Either[Exception, Int] and want to convert the Exception to a String (if present)
val result = opReturningEither
val better = result.left map {_.getMessage}

This will map over the left side of result, giving you an Either[String,Int]

A: joinLeft and joinRight enable you to "flatten" a nested Either:
scala> val e: Either[Either[String, Int], Int] = Left(Left("foo"))
e: Either[Either[String,Int],Int] = Left(Left(foo))

scala> e.joinLeft
res2: Either[String,Int] = Left(foo)

Edit: My answer to this question shows one example of how you can use the projections, in this case to fold together a sequence of Eithers without pattern matching or calling isLeft or isRight. If you're familiar with how to use Option without matching or calling isDefined, it's analagous.

While curiously looking at the current source of Either, I saw that joinLeft and joinRight are implemented with pattern matching. However, I stumbled across this older version of the source and saw that it used to implement the join methods using projections:
def joinLeft[A, B](es: Either[Either[A, B], B]) =
  es.left.flatMap(x => x)

A: My suggestion is add the following to your utility package:
implicit class EitherRichClass[A, B](thisEither: Either[A, B])
{
   def map[C](f: B => C): Either[A, C] = thisEither match
   {
     case Left(l) => Left[A, C](l)
     case Right(r) => Right[A, C](f(r))
   }
   def flatMap[C](f: B => Either[A, C]): Either[A, C] = thisEither match
   {
     case Left(l) => Left[A, C](l)
     case Right(r) => (f(r))
   }
}

In my experience the only useful provided method is fold. You don't really use isLeft or isRight in functional code. joinLeft and joinRight might be useful as flatten functions as explained by Dider Dupont but, I haven't had occasion to use them that way. The above is using Either as right biased, which I suspect is how most people use them. Its like an Option with an error value instead of None.
Here's some of my own code. Apologies its not polished code but its an example of using Either in a for comprehension. Adding the map and flatMap methods to Either allows us to use the special syntax in for comprehensions. Its parsing HTTP headers, either returning an Http and Html error page response or a parsed custom HTTP Request object. Without the use of the for comprehension the code would be very difficult to comprehend.
object getReq
{
  def LeftError[B](str: String) = Left[HResponse, B](HttpError(str))
  def apply(line1: String, in: java.io.BufferedReader): Either[HResponse, HttpReq] =
  {
    def loop(acc: Seq[(String, String)]): Either[HResponse, Seq[(String, String)]] =
    {
      val ln = in.readLine
      if (ln == "")
        Right(acc)
      else
        ln.splitOut(':', s => LeftError("400 Bad Syntax in Header Field"), (a, b) => loop(acc :+ Tuple2(a.toLowerCase, b)))
    }

    val words: Seq[String] = line1.lowerWords

    for
    {
      a3 <- words match
      {
        case Seq("get", b, c) => Right[HResponse, (ReqType.Value, String, String)]((ReqType.HGet, b, c))
        case Seq("post", b, c) => Right[HResponse, (ReqType.Value, String, String)]((ReqType.HPost, b, c))
        case Seq(methodName, b, c) => LeftError("405" -- methodName -- "method not Allowed")
        case _ => LeftError("400 Bad Request: Bad Syntax in Status Line")
      }
      val (reqType, target, version) = a3
      fields <- loop(Nil)
      val optLen = fields.find(_._1 == "content-length")
      pair <- optLen match
      {
        case None => Right((0, fields))
        case Some(("content-length", second)) => second.filterNot(_.isWhitespace) match
        {
          case s if s.forall(_.isDigit) => Right((s.toInt, fields.filterNot(_._1 == "content-length")))
          case s => LeftError("400 Bad Request: Bad Content-Length SyntaxLine")
        }
      }
      val (bodyLen, otherHeaderPairs) = pair
      val otherHeaderFields = otherHeaderPairs.map(pair => HeaderField(pair._1, pair._2))
      val body = if (bodyLen > 0) (for (i <- 1 to bodyLen) yield in.read.toChar).mkString else ""
    }
    yield (HttpReq(reqType, target, version, otherHeaderFields, bodyLen, body))
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: GetComponent of special type? First of all i know Unity have function FindObjectOfType() , but i dont want use this.
I made kind of "ReferenceManager" for all my script references in unity.
CameraManager,EventManager,UIManager etc..
These "Managers" never communicate between each other they always comunicate like this.
e.g. CameraManager --> ReferenceManager --> EventManager
Currently i have in my ReferenceManager public struct References where i hold all managers references.
My question is :
Is there some nice way how can i have 1 method what will return Manager of type i want.?
My Current code :
public class ReferenceManager : MonoBehaviour
{
    [SerializeField]
    public References references = new References(); //all references go throught this struct
    public struct References
    {
        [field: SerializeField]
        public CameraManager cameraManager { get; set; }
        [field: SerializeField]
        public UIManager uiManager { get; set; }
    }
    private void Awake()
    {
        AssignReferences();
    }
    void AssignReferences()
    {
        List<ISystemComponent> systemComponentsList = Reference.GetSystemComponents();
        foreach(ISystemComponent sC in systemComponentsList)
        {
            if(sC.GetType() == typeof(CameraManager))
            {
                references.cameraManager = sC as CameraManager;
            }
            if(sC.GetType() == typeof(UIManager))
            {
                references.uiManager = sC as UIManager;
            }

        }
    }
}
public static class Reference
{
    static List<ISystemComponent> systemComponentList = new List<ISystemComponent>(); //i hold all Managers in this list
    public static void SubscribeSystemComponent(ISystemComponent sC)
    {
        systemComponentList.Add(sC);
    }//any manager can be added to list by this method
    public static List<ISystemComponent> GetSystemComponents()
    {
        return systemComponentList;
    }
}
public interface ISystemComponent
{

}//this connects all managers with interface
public class CameraManager : MonoBehaviour, ISystemComponent //first manager
{
    private void Awake()
    {
        Reference.SubscribeSystemComponent(this);
    }
}
public class UIManager : MonoBehaviour, ISystemComponent //second manager
{
    ReferenceManager rM;
    CameraManager cM;
    private void Awake()
    {
        Reference.SubscribeSystemComponent(this);
    }
    private void Start()
    {
        GetReferences();
    }
    void GetReferences()
    {
        ReferenceManager rM = FindObjectOfType<ReferenceManager>();
        cM = rM.references.cameraManager; ///This way i currectly connect 2 managers   1 manager ---> ReferenceManager ---> 2 manager
    }
}

I want make 1 generic method what will always return Manager of type what i will call for, something like this :
  //Desired example
    ISystemComponent GetReference(/*Ispecify here somehow what type of manager i want*/)
    {
        return /*based of my specification that type will be returned by this method*/
    }

I will be happy for any ideas, thanks.

A: Call:
 GetISystemComponent<MazeManager>();

Method:
    public static T GetISystemComponent<T>() where T : ISystemComponent
    {
        foreach(ISystemComponent sC in systemComponentList)
        {
            if(sC.GetType().Equals(typeof(T)))
            {
                return (T)sC;
            }
        }
       Debug.LogError(typeof(T) + " - this component type not exist in List of ISystemComponent" );
       return default(T);
    }

A: I believe Everts' suggestion is to use a Dictionary<Type, ISystemComponent>:
public class ReferenceManager : MonoBehaviour
{
    [SerializeField]
    public References references = new References(); //all references go throught this struct
    public struct References
    {
        [field: SerializeField]
        public CameraManager cameraManager { get; set; }
        [field: SerializeField]
        public UIManager uiManager { get; set; }
    }
    private void Awake()
    {
        AssignReferences();
    }
    void AssignReferences()
    {
        var systemComponentsList = Reference.GetSystemComponents().Values;
        foreach(ISystemComponent sC in systemComponentsList)
        {
            if(sC.GetType() == typeof(CameraManager))
            {
                references.cameraManager = sC as CameraManager;
            }
            if(sC.GetType() == typeof(UIManager))
            {
                references.uiManager = sC as UIManager;
            }

        }
    }
}
public static class Reference
{
    private static Dictionary<Type, ISystemComponent> systemComponentDict = new(); //i hold all Managers in this list
    public static void SubscribeSystemComponent(ISystemComponent sC)
    {
        systemComponentDict.Add(sC.GetType(), sC);
    }//any manager can be added to list by this method
    public static Dictionary<Type, ISystemComponent> GetSystemComponents()
    {
        return systemComponentDict;
    }

    public static T GetISystemComponent<T>() where T : ISystemComponent
    {
        if(!systemComponentsDict.TryGetValue(typeof(T), out var component))
        {
            Debug.LogError(typeof(T) + " - this component type not exist in List of ISystemComponent" );
            component = default(T);
        }
        return component;
    }
}


text:
Q: Links between service Rancher Server 1.0.0 I'm porting my docker environment to rancher server 1.0.0.
I have a wordpress container which is linked to a mysql container.
Each one are in separate stack: One stack for the wordpress container and one for the mysql container.
Previously, linking between those two container was achieve using a docker-compose.yml for my wordpress container containing:
wordpress:
    external_links:
        - mysql:mysql

This was working perfectly before, but not anymore when those containers are within a rancher server.
The documentation about DNS service is not clear for me:
http://docs.rancher.com/rancher/rancher-services/internal-dns-service/
In rancher, my stack is named mysql and my service mysql.
I have tried to link using what
wordpress:
    external_links:
        - mysql.mysql:mysql

But this does not works too.
Those two containers are in a custom catalog, the only way right now to make this work is to create and start the two services and then change linking by upgrading the wordpress service afterward.
Any idea ?
I'm i missing something ?
Thanks a lots !

A: Here is the solution:
Instead of:
    external_links:
        - mysql.mysql:mysql

Use the following syntax for linking service within a stack:
    external_links:
        - mysql/mysql:mysql

Or more generically:
    external_links:
        - stack_name/service_name:alias_name

Hope this help !


text:
Q: PostgreSQL calculate weighted average based on user input I have a table with scores that lists for each film and critic, what score that critic gives to that film: (film_id, critic_id, score). I have the following PostgreSQL query to find the 10 films that have the highest average score across a given array of critics:
SELECT
    f_id, avg(f_score)
FROM
    (
        SELECT
            s.film_id as f_id, s.critic_id as c_id, s.score as f_score
        FROM
            score s
        WHERE
            s.critic_id = ANY(ARRAY['CRITIC_BOB_0213', 'CRITIC_AMY_9671'])
        GROUP BY
            s.film_id, s.critic_id, s.score
    )
sub
GROUP BY
    f_id
ORDER BY
    avg desc
LIMIT
    10;

In this case, the user would say that he wants to know the scores for critics Bob and Amy, and it returns:
f_id     | avg
"742545"   13.0330650266333
"220176"   6.7783259974
"662682"   6.52305498088333
...

Now, I want the user to be able to give a certain weight to a certain critic.
So basically, the user gives as input [('CRITIC_BOB_0213', 0.923), ('CRITIC_AMY_9671', 0.212)] (for instance if he values Bob's judgement more than Amy's), and I need the query to reflect that. So you would get a weighted average: avg(score_bob*0.923 + score_amy*0.212). I need it to be in the query itself, the number of films is in the millions and I don't want to have to return them all before calculating the weighted average in my backend code.
Is this possible in PostgreSQL?

A: Solved it myself by doing:
SELECT
    f_id, avg(weighted_score)
FROM
    (
        SELECT
            s.film_id as f_id
        ,
        CASE
            WHEN s.critic_id='CRITIC_BOB_0213' THEN s.score*CRITIC_BOB_WEIGHT
            WHEN s.critic_id='CRITIC_AMY_9671' THEN s.score*CRITIC_AMY_WEIGHT
            ELSE -1
        END as weighted_score
        FROM
            score s
        WHERE
            s.critic_id = ANY(ARRAY['CRITIC_BOB_0213', 'CRITIC_AMY_9671'])
        GROUP BY
            s.film_id, s.critic_id
    )
sub
GROUP BY
    f_id
ORDER BY
    avg desc
LIMIT
    10;

Hope it will help others in the future.


text:
Q: If $a\equiv b \pmod{p_i}$ for $i=1,2,...,k$ then prove $a\equiv b \pmod{p_1p_2\cdots p_k}$ If $a\equiv b \pmod{p_i}$ for $i=1,2,\cdots,k$ then prove $a\equiv b \pmod{ p_1p_2\cdots p_k}$
$a\equiv b \pmod{p_1}$ implies $a-b=p_1x_1$
Similarly, $a-b=p_2x_2,\ \cdots,\ a-b=p_kx_k$
So,
$$(a-b)^k = p_1p_2...p_kx$$ where $x=x_1x_2...x_k$
I'm stuck here, please help!

A: So $p_i$ divides $(a-b)^k$, since $p_i$ is prime, $p_i$ divides $(a-b)$ or $(a-b)^{k-1}$ recursively you obtain $p_i$ divides $(a-b)$ thus $p_1...p_k$ divides $a-b$ since $p_i$ is prime.
Here I use that if $p,q$ divide $u$ and $gcd(p,q)=1$ then $pq$ divide $u$. To see this, write $u=cp=dq, ap+bq=1$, thus $u=apu+bqu=apdq+bqcp=pq(ad+bc)$.


text:
Q: Private destructors on heap and stack class base
{
public:
    virtual ~base() = 0;
};

base::~base()
{
    cout <<"Destructing base"<<endl;
}

class derived : public base
{
    ~derived()
    {
        cout <<"Destructing derived"<<endl;
    }
};

int main()
{
    base* b = new derived();
    delete b;
    b = 0;

}

Here - I have declared the derived destructor as private and allocated memory on heap. But when I run this, I do see the derived destructor also getting called.
Instead if I run this in the main function as below by allocating memory on the code segment as below -
int main()
{
  derived d;
}

This throws an error saying the destructor is private.
I am confused - Doesn't delete internally also call the destructor before calling free()?


text:
Q: How to access DotnetNuke.Entities.Users from javascript I want to collect userInfo from Dotnetnuke to my javascript webpage.
To collect it I utilize $.getJSON:
$.getJSON("/DesktopModules/myModule/API/Service/GetUsers", "portalId=2",
    function (allData) {
        var mappedUsers = $.map(allData, function (item) {
            return new myModule.User(item);
        });
        self.Users(mappedUsers);
    });

I have this service controller:
public class ServiceController : DnnApiController
{
    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage GetUsers(int portalId)
    {
        myController controller = new myController();
        ArrayList items = controller.GetUsers(portalId);
        return Request.CreateResponse(HttpStatusCode.OK, items);
    }
}

public class myController // : ISearchable, IPortable
{
    public ArrayList GetUsers(int portalId)
    {
        return UserController.GetUsers(portalId);
    }
}

According to the DNN API documentation the method is defined as:
public static ArrayList GetUsers(
     int portalId
)

But when I test my service in a browser it fails with an error:
"Type 'DotNetNuke.Entities.Users.UserInfo' with data contract name 'UserInfo:http://schemas.datacontract.org/2004/07/DotNetNuke.Entities.Users' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer."
Any ideas how to solve this?

A: The problem is that you can't serialize the UserInfo without setting up a custom serialization.  The UserInfo object cannot be serialized to JSON automatically.
The simplest solution would be to create your own object representing the UserInfo in your response - either a cut down class or just the individual properties you need.


text:
Q: iPhone Sensor Data app ploting in Streaming mode Im using the Sensor Data app to access the data from the iPhone's accelerometer. I want to use the steaming option to stream the data to my MacBook in real time. For this I would like some sort of a script that collects this data and plots it in real time.
The makers of the app provide this Python script which sends the data in a string format,
import SocketServer

PORTNO = 10552

class handler(SocketServer.DatagramRequestHandler):
    def handle(self):
        newmsg = self.rfile.readline().rstrip()
        print "Client %s said ``%s''" % (self.client_address[0], newmsg)
        self.wfile.write(self.server.oldmsg)
        self.server.oldmsg = newmsg

s = SocketServer.UDPServer(('',PORTNO), handler)
print "Awaiting UDP messages on port %d" % PORTNO
s.oldmsg = "This is the starting message."
s.serve_forever()`

Does anyone know of any scripts out there that do this?

A: In order to gain full control over the plots, you would probably have to install a plotting library in your computer. Matplotlib is an open-source python library that will help you to solve this situation. If you are already familiar with MATLAB programming, this won't be that much different, they even provide an introduction to Matplotlib for MATLAB users. This will certainly help you plotting things.


text:
Q: Why can we use Cursors directly? Looking at the source code for android.database.Cursor, I notice that all its member functions are undefined.
If so, how can we directly use Cursor? Shouldn't we have to use some concrete class that implements Cursor?

A:
Shouldn't we have to use some concrete class that implements Cursor?

You do "use some concrete class that implements Cursor". For example, when you query SQLite, you get a SQLiteCursor back. We just tend to reference it as the interface type (Cursor), in case we change the implementation sometime (e.g., switch to querying a ContentProvider).
If you look at the JavaDocs for Cursor, you will see a list of classes that implement this interface.


text:
Q: Regex for 'rec-01-' to select jobs in Jenkins view I am setting up a Jenkins view and want to use Regex to automatically select matched jobs. The jobs to be selected all have a prefix like 'rec-01-', 'rec-24-', 'rec-98-', etc. The only difference is the two digits.
I tried with this regex ^(rec-[0-9]+-) and many similar ones but no luck.

A: Jenkins tries to do a full match of the regular expression against the job names, so the following should work:
rec-[0-9]+-.*


text:
Q: Skip validation of Primefaces Inputtext on keyup event but validate on submit I have two requirements for my InputText:

*

*value of the p:inputText should be immediately displayed on screen in h:outputText with keyup-event

*the value should be unique in database

I'm using Primefaces 4.0, JSF 2.2 with Glassfish 4 and Java 7
My code looks like this at the moment
Example.xhtml
<h:form>
    <p:inputText id="value" value="#{myBean.value}" >
        <p:ajax event="keyup" update="example" process="@this" />
        <f:validator binding="#{uniqueValueValidator}" />
    </p:inputText>
    <h:outputText id="example" value="#{myBean.value}">
    <p:commandButton value="Save" action="#{myBean.saveValue}"/>
</form>

MyBean.java
@Named
@RequestScoped
public class MyBean {

    @Inject
    private DBService service;

    private String value;
    //getter, setter

    public String saveValue() {
        service.saveValue(value);
        return "showall";
    }
}

UniqueValueValidator.java
@Named
public class UniqueValueValidator implements Validator {

    @Inject
    private DBService service;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
        throws ValidatorException {

        if(service.isValueNotUnique(value.toString()) {
              // throw ValidatorException
        }
    }
}

My problem is now, that on every keyup-event the value is validated and a call to the database is made. But I want to validate the value only when the form is submitted.
My first solution was to move the validation into the saveValue method.
public String saveValue() {
    if(service.isValueNotUnique(value) {
        // add a FacesMessage
        return null;
    } else {
         service.saveValue(value);
         return "showall";
    }
}

But here I think it is not good practice to mix validation code and logic code in one method.
So I hope you have a nicer solution for me ;)

A: The issue lies in the ajax tag inside the inputText component:
<p:ajax event="keyup" update="example" process="@this" />

This means that you are submitting the component on each keyup event. And the validator will be called each time consequently.
A possible workaround is to move the validator to another component, following the same technique used for validating multiple components:
In the facelets page add an inputHidden that uses uniqueValueValidator:
<h:form id="formId" >
    <p:inputText id="value" value="#{myBean.value}" >
        <p:ajax event="keyup" update="example" process="@this" />
    </p:inputText>
    <h:inputHidden id="hidden">
        <f:validator validatorId="uniqueValueValidator" />
    </h:inputHidden>
    <p:message for="hidden" />
    <p:commandButton value="Save" action="#{myBean.saveValue}" process="@form" update="@form"/>
</h:form>

UniqueValueValidator:
@Named
@FacesValidator("uniqueValueValidator")
public class UniqueValueValidator implements Validator {

    @Inject
    private DBService service;

    @Override
    public void validate(FacesContext context, UIComponent component, Object obj) {

        Object inputValue = ((UIInput) context.getViewRoot().findComponent("formId:value")).getSubmittedValue();

        if(service.isValueNotUnique((String) inputValue) {
            // throw ValidatorException
        }
    }

}

}
This approach, like yours, implies a round-trip client-server-client of the inputed content on each keyup event. If this is not necessary, you can avoid it with a javascript approach as explained in the other answer.
Links

*

*The BalusC Code: Validator for multiple components

*jsf validate two fields in one time

A: You can get rid of the ajax request in the p:inputText and simply copy the value from the input to the inputtext with jquery as the follows:
<h:form id="myForm">
    <p:inputText id="value" value="#{myBean.value}" onkeyup="$("#myForm\\:example").html($(this).val()">
        <f:validator binding="#{uniqueValueValidator}" />
    </p:inputText>
    <h:outputText id="example" value="#{myBean.value}">
    <p:commandButton value="Save" action="#{myBean.saveValue}"/>
</form>


text:
Q: How does electromagnetic induction happen? Electric and magnetic fields are different from each other(i think i am correct).. How does changing magnetic field induce electric current???

A: Alfred and Sam29 are quite correct, but the Maxwell equations and saying electric and magnetic fields are just different components of one thing, the electromagnetic field, is just a (nicely consistent) way of representing what is observed in nature.
It does not answer the question of why it is observed in nature.
I'm not sure there is a good answer (other than "it just is"), but I would propose a poor answer:
I assume you have no problem with the principle of the electromagnet.
If you run a current through a wire, a magnetic field is observed around the wire.
This can be exploited to make powerful magnets.
Turning on the current causes the field to appear, and turning it off makes it disappear.
Turning the current on half-way gives you half of the magnetic field.
Then, all you have to do is see there's no reason to suppose the relationship is one-way only.
Then if you supply the magnetic field from outside, if it's two-way, you should see a current, and you do.
There's a simple demonstration:
Take a flashlight battery, and take a short piece of wire connected to one end of the battery, and tap it on the other end.
You see a tiny spark.
Now do the same thing with a long piece of wire in a coil (making an electromagnet).
You get a fat spark.
Why? Because when you disconnect the wire from the battery, the magnetic field in the electromagnet doesn't just disappear, its change induces current in the coil.
Again, it may be easier to see that, because of conservation of energy and whatnot, the relationship between current and magnetic field has to be two-way.
Then, Maxwell's equations make a beautifully concise explanation of that two-way relationship.

A: As Alfred correctly pointed out, both the electric and magnetic fields are fundamentally the same field, the electromagnetic field - they are just different components. By this logic, naturally, if you were to somehow change one component (by moving a magnet or something of that sort), it would lead to a change in the other.
Keep in mind that this obviousness is now easier to see because of Maxwell's laws. Before them, many physicists tried to answer the same question using their own approaches, and they failed. Electromagnetic theory gives answers in perfect harmony with experiments. I suggest you look up the laws, and that would answer your question better than any of us here could.

A: Electric fields and magnetic fields are very related. This can be summarized as: a changing magnetic field creates a changing electric field (and vice versa). Moving the magnet closer changes the  magnetic field at the coil, creating an electric field in the wire.
Have you learnt about the force of a magnetic field on a charge yet? If you have, then here's another way to think of it. Imagine instead of moving the magnet into the coil, you moved the coil to the magnet. By the Lorentz force, the charges in the wire would  move in a spiral e.g along the wire.
Moving the wire through the magnetic field is physically the same as increasing the magnetic field at the coil. That's why changing the magnetic field creates a current.


text:
Q: Is it possible to set an event on the specific point of an image? I have a image like this:

All I'm trying to do is print a message in console like these:
console.log("#1 point is hovered");
console.log("#2 point is hovered");

See? I want to detect mouse hover on every point on the image. Is doing such a thing possible?

A: There are <map> and <area> tags in HTML:

<map id="imagemap" name="planetmap">
  <area shape="circle" coords="104,101,15" href="first.htm" alt="First Point">
  <area shape="circle" coords="331,243,15" href="second.htm" alt="Second Point">
</map>

https://www.w3schools.com/tags/tag_map.asp
So you can attach an event to any defined area (circle, polygon or rectangle) and manipulate it with javascript. See example below:

var points = document.querySelectorAll('#imagemap area');
result = document.getElementById('result');

Array.prototype.slice.call(points).forEach(function(point) {

  point.addEventListener('mouseenter', function() {
    result.innerHTML = this.alt + '
' + result.innerHTML;
  });

});
#result {
  background-color: #eee;
  padding: 10px 15px;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  max-height: 50px;
  overflow: auto;
}

<map id="imagemap" name="planetmap">
  <area shape="circle" coords="104,101,15" href="first.htm" alt="First Point">
  <area shape="circle" coords="331,243,15" href="second.htm" alt="Second Point">
</map>

A: Use imagemap for this and use specific coordinates to add links using map and area and get its coordinates.
Have a look at the below example:

$('area').each(function() {
  $(this).on('mouseover', function() {
    console.log($(this).attr('coords'));
  });
});

  <map name="logos">
    <area shape="circle" coords="68,56,33" href="http://www.stumbleupon.com/" title="StumbleUpon" alt="StumbleUpon">
    <area shape="rect" coords="220,19,306,54" href="http://www.youtube.com/" title="Youtube" alt="Youtube">
    <area shape="rect" coords="367,32,516,84" href="http://www.google.com/" title="Google" alt="Google">
    <area shape="rect" coords="556,12,639,115" href="http://www.wikipedia.com/" title="Wikipedia" alt="Wikipedia">
    <area shape="rect" coords="128,62,244,114" href="http://www.skype.com/" title="Skype" alt="Skype">
    <area shape="rect" coords="301,103,444,136" href="http://www.yahoo.com/" title="Yahoo" alt="Yahoo">
    <area shape="rect" coords="25,158,135,207" href="http://www.ebay.com/" title="eBay" alt="eBay">
    <area shape="rect" coords="180,147,271,175" href="http://www.flickr.com/" title="Flickr" alt="Flickr">
    <area shape="rect" coords="299,166,379,208" href="http://www.digg.com/" title="Digg" alt="Digg">
    <area shape="circle" coords="500,184,32" href="http://wordpress.org/" title="Wordpress.org" alt="Wordpress.org">
    <area shape="rect" coords="599,142,667,209" href="http://www.blogger.com/" title="Blogger" alt="Blogger">
    <area shape="default" nohref="nohref" title="Default" alt="Default">
  </map>

Hope this helps!


text:
Q: Add New row for a 3D Array in Numpy How to add a new row for a 3D array?
Ex: Let's say we have arrays with these dimensions
arr1.shape = (1,1,20)
arr2.shape = (1,1,20)

combined.shape = (1,2,20)

How can I do this in numpy?

A: You can use concatenate and specify the desired axis like the following:
import numpy as np

arr1 = np.ones((1, 1, 20))
arr2 = np.ones((1, 1, 20))

print(np.concatenate((arr1, arr2), axis=1).shape)

Alternativly you can use hstack like the following:
import numpy as np

arr1 = np.ones((1, 1, 20))
arr2 = np.ones((1, 1, 20))

print(np.hstack((arr1,arr2)).shape)


text:
Q: How can two children from one class interact with each other? I have two players created from the Player class, they have their own army with attack 10 and defense 5.
When I enter player1.attack () the first player attacks the second player's army, but I just don't understand how two children from one class can interact with each other.
Please give me some examples or tell where I can read about this?

A: I think it might help:

class Player {
  constructor(d, a) {
    this.defense = d;
    this.attack = a;
  }

  static attack(attacker, defender) {
    defender.defense -= attacker.attack;
  }
}

var p1 = new Player(10, 5);
var p2 = new Player(100, 20);

Player.attack(p1, p2);
console.log(p1);
console.log(p2);

A: One child must have a reference to another:
let p1 = new Player();
let p2 = new Player();

p1.attack(p2);

In this case I've explicitly passed the reference to p2 as an argument to the attack method, which would look something like this:
class Player {
  constructor () {
    this.health = 50;
    this.attack = 10;
    this.defense = 5;
  }

  takeHit (attackRating) {
    let damage = attackRating - this.defense;
    if (damage > 0) {
      this.health -= damage;
        if (this.health < 1) {
        this.die();
      }
    }
  }

  attack (enemy) {
    // we'll assume we were passed a valid player, you can
    // check if you wish.
    enemy.takeHit(this.attack);
  }
}

Implementation of the die method left as an exercise to the reader.


text:
Q: Merge two Lists in C# and merge objects with the same id into one list item I have already thought about how I'm going to solve this by rolling my own solution, but I wondered if .NET already has the functionality for what I'm trying to acheive - if so, I'd rather use something built-in.
Suppose I have two instances of a Widget object, let's call them PartA and PartB. The information from each has been garnered from two different web services, but both have matching IDs.
PartA
{
    ID: 19,
    name: "Percy",
    taste: "",
    colour: "Blue",
    shape: "",
    same_same: "but different"
}

PartB
{
    ID: 19,
    name: "",
    taste: "Sweet",
    colour: "",
    shape: "Hexagon",
    same_same: "but not the same"
}

I want to merge these to create the following:
Result
{
    ID: 19,
    name: "Percy",
    taste: "Sweet",
    colour: "Blue",
    shape: "Hexagon",
    same_same: "but different"
}

Notice how the value for same_same differs between each, but we consider PartA the master, so the result retains the value but different.
Now to complicate matters:
Suppose we have two lists:
List<Widget> PartA = getPartA();
List<Widget> PartB = getPartB();

Now here's some pseudocode describing what I want to do:
List<Widget> Result = PartA.MergeWith(PartB).MergeObjectsOn(Widget.ID).toList();

A: If your lists are one for one (i.e. same number of items and each item in the PartA list has a match in the PartB list), then I would consider the Zip extension method. Note that Zip does not actually require each list to have same number of items. However, if you can't rely on "pairing up" items with matching IDs, then my simplistic approach won't work.
You could do something like this:
var alist = GetPartAWidgets().OrderBy(w => w.ID);
var blist = GetPartBWidgets().OrderBy(w => w.ID);
var merged = alist.Zip(blist, (a,b) => new Widget()
             {
               ID = a.ID,
               Name = string.IsNullOrEmpty(a.Name) ? b.Name : a.Name,
               //etc.
             });

If you want your linq to look cleaner, you could encapsulate the individual Widget merging logic in a function or extension method and use that instead of the inline delegate.

A: You could write your own extension method(s), something like this:
static class Extensions
{
    public static IEnumerable<T> MergeWith<T>(this IEnumerable<T> source, IEnumerable<T> other) where T : ICanMerge
    {
        var otherItems = other.ToDictionary(x => x.Key);
        foreach (var item in source)
        {
            yield return (T)item.MergeWith(otherItems[item.Key]);
        }
    }
    public static string AsNullIfEmpty(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return null;
        else
            return s;
    }
}

Where ICanMerge is like:
public interface ICanMerge
{
    object Key { get; }
    ICanMerge MergeWith(ICanMerge other);
}

Implemented e.g. like:
public class Widget : ICanMerge
{
    object ICanMerge.Key { get { return this.ID; } }
    int ID {get;set;}
    string taste {get;set;}
    public ICanMerge MergeWith(ICanMerge other)
    {
        var merged = new Widget();
        var otherWidget = (Widget)other;
        merged.taste = this.taste.AsNullIfEmpty() ?? otherWidget.taste;
        //...
        return merged;
    }
}

Then it's as simple as PartA.MergeWith(PartB).ToList().

A:    public interface IMerge<out T>
{
    IEnumerable<IMergeMatched<T>> Matched();

    IEnumerable<IMergeMatched<T>> Matched(Func<T, T, bool> predicate);

    IEnumerable<T> NotMatchedBySource();

    IEnumerable<T> NotMatchedBySource(Func<T, bool> predicate);

    IEnumerable<T> NotMatchedByTarget();

    IEnumerable<T> NotMatchedByTarget(Func<T, bool> predicate);
}

public interface IMergeMatched<out T>
{
    T Source { get; }

    T Target { get; }
}

public static class Enumerable
{
    public static IMerge<TSource> Merge<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> target,
                                             Func<TSource, TSource, bool> predicate)
    {
        return new Merge<TSource>(source, target, predicate);
    }
}

public class Merge<T> : IMerge<T>
{
    private readonly Func<T, T, bool> _predicate;
    private readonly IEnumerable<T> _source;
    private readonly IEnumerable<T> _target;
    private IEnumerable<IMergeMatched<T>> _matcheds;
    private IEnumerable<T> _notMatchedBySource;
    private IEnumerable<T> _notMatchedByTarget;

    public Merge(IEnumerable<T> source, IEnumerable<T> taget, Func<T, T, bool> predicate)
    {
        _source = source;
        _target = taget;
        _predicate = predicate;
    }

    public IEnumerable<IMergeMatched<T>> Matched()
    {
        if (_matcheds == null)
        {
            Analize();
        }
        return _matcheds;
    }

    public IEnumerable<IMergeMatched<T>> Matched(Func<T, T, bool> predicate)
    {
        return Matched()
            .Where(t => predicate.Invoke(t.Source, t.Target))
            .ToArray();
    }

    public IEnumerable<T> NotMatchedBySource()
    {
        if (_notMatchedBySource == null)
        {
            Analize();
        }
        return _notMatchedBySource;
    }

    public IEnumerable<T> NotMatchedBySource(Func<T, bool> predicate)
    {
        return NotMatchedBySource()
            .Where(predicate)
            .ToArray();
    }

    public IEnumerable<T> NotMatchedByTarget()
    {
        if (_notMatchedByTarget == null)
        {
            Analize();
        }
        return _notMatchedByTarget;
    }

    public IEnumerable<T> NotMatchedByTarget(Func<T, bool> predicate)
    {
        return NotMatchedByTarget()
            .Where(predicate)
            .ToArray();
    }

    private void Analize()
    {
        var macheds = new List<MergeMached<T>>();
        var notMachedBySource = new List<T>(_source);
        var notMachedByTarget = new List<T>(_target);

        foreach (var source in _source)
        {
            foreach (var target in _target)
            {
                var macth = _predicate.Invoke(source, target);
                if (!macth) continue;

                macheds.Add(new MergeMached<T>(source, target));
                notMachedBySource.Remove(source);
                notMachedByTarget.Remove(target);
            }
        }

        _matcheds = macheds.ToArray();
        _notMatchedBySource = notMachedBySource.ToArray();
        _notMatchedByTarget = notMachedByTarget.ToArray();
    }
}

public class MergeMached<T> : IMergeMatched<T>
{
    public MergeMached(T source, T target)
    {
        Source = source;
        Target = target;
    }

    public T Source { get; private set; }

    public T Target { get; private set; }
}

How to use?
var source = new List<MediaFolder>
            {
                new MediaFolder
                    {
                        Id = "Id1",
                        Name = "Name1",
                        Path = "Path1"
                    },
                new MediaFolder
                    {
                        Id = "Id2",
                        Name = "Name2",
                        Path = "Path2"
                    },
                new MediaFolder
                    {
                        Id = "Id3",
                        Name = "Name3",
                        Path = "Path3"
                    },
                new MediaFolder
                    {
                        Id = "Id4",
                        Name = "Name4",
                        Path = "Path4"
                    },
                new MediaFolder
                    {
                        Id = "Id5",
                        Name = "Name5",
                        Path = "Path5"
                    },
                new MediaFolder
                    {
                        Id = "Id6",
                        Name = "Name6",
                        Path = "Path6"
                    }
            };

        var target = new List<MediaFolder>
            {
                new MediaFolder
                    {
                        Id = "Id1",
                        Name = "Actualizado en el objeto",
                        Path = "Path1"
                    },
                    //Id2 eliminado
                new MediaFolder
                    {
                        Id = "Id3",
                        Name = "Name3",
                        Path = "Actualizado tambien"
                    },
                new MediaFolder
                    {
                        Id = "Id4",
                        Name = "Name4",
                        Path = "Path4"
                    },
                new MediaFolder
                    {
                        Id = "Id5",
                        Name = "Name5",
                        Path = "Path5"
                    },
                new MediaFolder
                    {
                        Id = "Id6",
                        Name = "Name6",
                        Path = "Path6"
                    },
                     new MediaFolder
                    {
                        Id = "Id7",
                        Name = "Nuevo Item 7",
                        Path = "Nuevo Item 7"
                    }
            };

        var merge = source.Merge(target, (x, y) => x.Id == y.Id);

        var toUpdate = merge.Matched((x, y) => x.Name != y.Name | x.Path != y.Path)
            .ToArray();

        var toDelete = merge.NotMatchedBySource();
        var toInsert = merge.NotMatchedByTarget();

        Assert.AreEqual(2, toUpdate.Count());
        Assert.IsTrue(toUpdate.Count(x => x.Source.Id == "Id1" & x.Target.Id == "Id1") > 0);
        Assert.IsTrue(toUpdate.Count(x => x.Source.Id == "Id3" & x.Target.Id == "Id3") > 0);

        Assert.AreEqual("Id7", toInsert.First().Id);
        Assert.AreEqual("Id2", toDelete.First().Id);


text:
Q: How to pass parameter form rake file to model? I have have a rake task .
and this is my code on it
i have a method called terminate_conference(args)
  task :terminate_conference, [ :unique ] => :environment do |t, args|
    ActiveRecord::Base.transaction do
      begin
        abort "no unique" unless args[:unique]
        rake.str << " -> #{args[:unique]}"
         rake.str << " -> #{args} -> KINGKANGKUNGKANGKING"
        unique_conference = Unique.new
        unique_conference.terminate_conference(args)
      rescue Exception => e
        ActiveRecord::Rollback
        logger.info "Error Terminating"
      end
    end
  end

and this is my model which has the function of terminate_conference(params):
  def terminate_conference(params) # params must be an Hash object

    conditions = Hash.new
    conditions[:id] = params[:id] unless !params.has_key? :id
    conditions[:unique_number] = params[:unique_number] unless !params.has_key? :unique_number

    @unique = Unique.where(conditions).take
    if @unique
    confbridge = Confbridge.where( confno: @unique.unique_number)
    unique = Unique.where( unique_number: @unique.unique_number)
    confbridge.destroy_all
    unique.destroy_all

      circle = Circle.find(@unique.circle)
      circle[:conference2_total_channels] -= 5
      circle.save!
    end
  end

for example the value of terminate_conference(12345)
how can i get to my model? terminate_conference(params)

A: rake commands load your entire application, so you should be able to access your model by simply calling MyModel.


text:
Q: plotting image on map I want to place a small image on a basemap at a specific coordinates what are the modification I need to do
def base_map(temp):
    fig = plt.figure(figsize=(360, 180), edgecolor='w')
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180, )
    draw_map(m)

    m.bluemarble()

    plt.show()

this is the final result i'm trying to do  https://i.stack.imgur.com/XHLF6.jpg

A: The relevant code snippet you need is given below, hope it helps.
# ...
# other lines of code go above

filename = "some_image.png"
lonmin, lonmax, latmin, latmax = (100.6377, 100.6447, 13.729, 13.7325) # just example
image_extent = (lonmin, lonmax, latmin, latmax)
ax = plt.gca()
ax.imshow(plt.imread(filename), extent=image_extent)
plt.show()


text:
Q: Flutter type of carousel z-index I have a problem with this design

I'm trying to make this design of carousel,
I have tried PageView and AnimatedContainer, the carousel_slider package but I don't have find what I need.
I have just make this


text:
Q: Login sencillo con SpringBoot Estoy dando mis primeros pasos con SpringBoot... Quiero hacer un servicio de Login en el cual le pones un usuario y una contraseña y si es correcto te devuelve los datos del usuario.
De momento con hacer que te devuelva los datos del usuario me conformo, pero si puedo resolver lo que quiero, lo agradecería.
El problema que tengo son 2.
No sé como enviar 2 parámetros "nombreUsuario","contraseña" por eso de momento sólo envío 1.
Controlador:
@RestController
@RequestMapping(value={"/usu"})
public class UsuController {

    @Autowired
    UsuService usuRepository;

     @RequestMapping("/")
        String home() {
            return "Servicio Usuario!";
     }

          @RequestMapping(method=RequestMethod.GET, path = "/Login/{userName}" ,  produces = MediaType.APPLICATION_JSON_VALUE)
    public Usuario Login(@PathVariable("userName") String userName) {
        Usuario tasks = usuRepository.getUsu(userName);
        return tasks;
    }

Interface:
public interface UsuService {
      public List<Usuario> getUsus() ;
      public Usuario getUsu(String name);
}

Service:
@Override
    public Usuario getUsu(String user) {
    Usuario usu;
    return usu = usuRepository.findOne(user);

    }

Repositorio
package prueba.repository;

import org.springframework.data.repository.CrudRepository;

import prueba.Usuario;

public interface UsuRepository extends CrudRepository<Usuario,String>{

}

Usuario Clase
@Entity
@Table(name="usuario")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Usuario {

     @Id
     @Column(name="id")
     private int id;

     @Column(name="name")
     private String name;

     @Column(name="email")
     private String email;

     public Usuario() {
    }
     public Usuario(int id, String name, String email) {
            this.id = id;
            this.name = name;
            this.email = email;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "usuario [id=" + id + ", name=" + name + ", email=" + email + "]";
    }

}

Ejecutar
http://localhost:8080/usu/Login/edu

Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jul 02 10:31:34 CEST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String

Ya hice una prueba devolviendo todos los usuarios y funciona.
De momento quiero que al poner Mi nombre de Usuario, me devuelva mis datos, y después haré lo del Login con contraseña.Gracias.

A: Al tratarse de un login deberias usar un POST, y en vez de recuperar un @PathVariable, puedes recuperar un @RequestBody de tipo complejo, donde incluyas tanto el Username como la Password.
@PostMapping("/login")
public Usuario Login(@RequestBody LoginRequest request) {
     request.getUsername();
     request.getPassword();
}

public class LoginRequest {
    private String username;
    private String password;
    // ...
}

A: En tu repositorio tienes
public interface UsuRepository extends CrudRepository<Usuario,String> { }

Es decir, le dices a Spring que ese repositorio va a manejar la entidad Usuario y que su identificador será un String.
Pero luego en Usuario tienes:
public class Usuario {

     @Id
     @Column(name="id")
     private int id;
     //...
}

Es decir, el id es un int (o Integer, al usar clases), lo que te obligaría a definir el repositorio como
public interface UsuRepository extends CrudRepository<Usuario,Integer> {
    Usuario findByEmail(String email);

}
Los repositorios de Spring tienen una convención con los nombres de los métodos:
ClaseEntidad findBy<nombreDelCampo>[And|Or<nombreDelSegundoCampo> (campo[,segundoCampo]);

PS:
Por otro lado, el método findOne no existe en CrudRepository desde hace un año, se cambió a findById, si estás empezando un proyecto te recomiendo actualizar las librerías.
PPS:
Lo que necesitas realmente es usar Spring Security, pero los cambios son demasiado grandes para una respuesta aquí, te recomendaría que intentases seguir un tutorial sobre el tema.


text:
Q: header("Content-Disposition: attachment) not working I have tried to export the mysql data result to excel. After click the Export button, the form will send parameter's value into doexport.php.
The result was appeared in console.

<?php
session_start(); //Start the session
include('install_lang_japanese.php');

//connect to database
$dbc=mysqli_connect(_SRV,_ACCID,_PWD,"QPL");
if(!$dbc){
   die('Connect Error: ' . mysqli_connect_error());
}

if(isset($_POST['action'])){
   switch($_POST['action']){
      case 'senddatacar':

         $start = mysqli_real_escape_string($dbc,$_POST['startdate']);
         $end = mysqli_real_escape_string($dbc,$_POST['enddate']);

         $sqlex = "SELECT * FROM table";
         $result =mysqli_query($dbc,$sqlex) or die(_ERROR30.":".mysqli_error($dbc));

         $filename="cardata".date('ymd').".xls";

         header("Content-type: application/vnd.ms-excel; name='excel'");
         header(sprintf("Content-Disposition: attachment; filename=$filename"));
         header("Pragma: no-cache");
         header("Expires: 0");

         //Then echo table
         break;
    }
mysqli_close($dbc);
}

My problem is : i don't see any file has downloaded as excel

Response Header at console :
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Disposition:attachment; filename=cardata170929.xls
Content-Length:2988
Content-Type:application/vnd.ms-excel; name='excel'
Date:Fri, 29 Sep 2017 05:02:19 GMT
Expires:0
Pragma:no-cache
Server:Apache/2.2.22 (Ubuntu)


text:
Q: Execute php script when checkbox checked I wanted to do that when my checkbox is checked, a php script whill be executed.
There is my code :

<form action="checkboxes.php" method="post">
<input type="checkbox" value="dawid" name="chk1"> 4K </input>
<input type="submit" name="Submit" value="Submit"></input>
</form>

<?php

   $bdd=new PDO("mysql:host=localhost;dbname=techtronik.pl;charset=utf8", "root");
   $wyszukiwanie = $bdd->query("SELECT * FROM procesory ");
   while($wynik = $wyszukiwanie->fetch() )
   {
    echo $wynik ['nazwaproduktu'] . ". ";
   }

?>

Can someone please help me ?
Thanks.

A: I am assuming you have basic knowledge of html, ajax, and javascript.
In your case you can use ajax call.
1) Checkbox checked
2) Call an ajax
3) Handle ajax and Run php code
4) Return to ajax
5) Success :)
Or just submit form on checkbox check then handle with php.

A: You can do it using jQuery, because it's easy solution for beginner.
Heres the sample jQuery code for your current code:
$('input[name=chk1]').click(function(){
  if($(this).is(':checked')){
    $('form').submit();
    //or your ajax request
  }
});

A: Why dont you use JavaScript/Ajax, jquery.... And call on check/ on click function


text:
Q: Why trace of $I−X(X′X)^{-1}X′$ is $n-p$ in least square regression when the parameter vector $\beta$ is of p dimensions? In the model ${y} = X \beta + \epsilon$, we could estimate $\beta$ using the normal equation:
$$\hat{\beta} = (X'X)^{-1}X'y,$$ and we could get $$\hat{y} = X \hat{\beta}.$$
The vector of residuals is estimated by
$$\hat{\epsilon} = y - X \hat{\beta}
                     = (I - X (X'X)^{-1} X') y
                     = Q y
                     = Q (X \beta + \epsilon) = Q \epsilon,$$
where $$Q = I - X (X'X)^{-1} X'.$$
My question is how to get the conclusion of $$\textrm{tr}(Q) = n - p.$$

A: $\newcommand\R{\mathbb R}$Assume that $n \le p$ and that $X$ is full-rank.
Consider the compact singular value decomposition $X = U \Sigma V^T$, where $\Sigma \in \R^{p \times p}$ is diagonal and $U \in \R^{n \times p}, V \in \R^{p \times p}$ have $U^T U = V^T V = V V^T = I_p$ (but note $U U^T$ is rank at most $p$ so it cannot be $I_n$). Then
\begin{align}
X (X^T X)^{-1} X^T
&= U \Sigma V^T (V \Sigma U^T U \Sigma V^T)^{-1} V \Sigma U^T
\\&= U \Sigma V^T (V \Sigma^2 V^T)^{-1} V \Sigma U^T
\\&= U \Sigma V^T V \Sigma^{-2} V^T V \Sigma U^T
\\&= U U^T
.\end{align}
Now, there exists a matrix $U_2 \in \R^{n \times n-p}$ such that
$U_n = \begin{bmatrix}U & U_2\end{bmatrix}$ is unitary.
We can write
\begin{align}
I - X (X^T X)^{-1} X^T
&= U_n U_n^T - U U^T
\\&= U_n \left( I_n - \begin{bmatrix}I_p & 0 \\ 0 & 0\end{bmatrix} \right) U_n^T
\\&= U_n \begin{bmatrix}0 & 0 \\ 0 & I_{n-p}\end{bmatrix} U_n^T
.\end{align}
This form shows that $Q$ is positive semidefinite,
and since it is a valid svd and the singular values are the square of the eigenvalues for a square symmetric matrix,
also tells us that $Q$ has eigenvalues 1 (of multiplicity $n-p$) and 0 (of multiplicity $p$). Thus the trace of $Q$ is $n-p$.

A: @Dougal has already given an answer, but here is another one, a bit simpler.
First, let's use the fact that $\newcommand{\tr}{\mathrm{tr}}\tr(A - B) = \tr(A) - \tr(B)$. So, we get: $$\tr(Q) = \tr(I) - \tr(X(X'X)^{-1}X').$$ Now $I$ is an $n \times n$ identity matrix, so $\tr(I) = n$. Now let's use the fact that $\tr(AB) = \tr(BA)$, that is, the trace is invariant under cyclic permutations. So, we have: $$\tr(Q) = n - \tr((X'X)^{-1}(X'X)).$$ When we multiply $(X'X)^{-1}$ with $(X'X)$, we get a $p \times p$ identity matrix, whose trace is $p$. So, we get: $$\tr(Q) = n - p.$$

A: The conclusion merely counts dimensions of vector spaces. However, it is not generally true.
The most basic properties of matrix multiplication show that the linear transformation represented by the matrix $\mathbb{H}=X(X^\prime X)^{-}X^\prime$ satisfies
$$\mathbb{H}^2 = \left(X(X^\prime X)^{-}X^\prime\right)^2=X(X^\prime X)^{-}(X^\prime X)(X^\prime X)^{-}X^\prime=\mathbb{H},$$
exhibiting it as a projection operator.  Therefore its complement
$$\mathbb{Q} = 1 - \mathbb{H}$$
(as given in the question) also is a projection operator. The trace of $\mathbb{H}$ is its rank $h$ (see below), whence the trace of $\mathbb{Q}$ equals $n-h$.
From its very formula it is apparent that $\mathbb{H}$ is the matrix associated with the composition of two linear transformations $$\mathbb{J}=(X^\prime X)^{-}X^\prime$$ and $X$ itself.  The first ($\mathbb{J}$) transforms the $n$-vector $y$ into the $p$-vector $\hat\beta$.  The second ($X$) is a transformation from $\mathbb{R}^p$ to $\mathbb{R}^n$ given by $\hat y = X\hat \beta$.  Its rank cannot exceed the smaller of those two dimensions, which in a least squares setting is always $p$ (but could be less than $p$, whenever $\mathbb{J}$ is not of full rank).  Consequently the rank of the composition $\mathbb{H}=X\mathbb{J}$ cannot exceed the rank of $X$.  The correct conclusion, then, is

$\text{tr} (\mathbb{Q}) = n-p$ if and only if $\mathbb{J}$ is of full rank; and in general $n \ge \text{tr} (\mathbb{Q}) \ge n-p$.  In the former case the model is said to be "identifiable" (for the coefficients of $\beta$).

$\mathbb{J}$ will be of full rank if and only if $X^\prime X$ is invertible.

Geometric interpretation
$\mathbb{H}$ represents the orthogonal projection from $n$-vectors $y$ (representing the "response" or "dependent variable") onto the space spanned by the columns of $X$ (representing the "independent variables" or "covariates").  The difference $\mathbb{Q}=1-\mathbb{H}$ shows how to decompose any $n$-vector $y$ into a sum of vectors $$y = \mathbb{H}(y) + \mathbb{Q}(y),$$ where the first can be "predicted" from $X$ and the second is perpendicular to it.  When the $p$ columns of $X$ generate a $p$-dimensional space (that is, are not collinear), the rank of $\mathbb{H}$ is $p$ and the rank of $\mathbb{Q}$ is $n-p$, reflecting the $n-p$ additional dimensions of variation in the response that are not represented within the independent variables.  The trace gives an algebraic formula for these dimensions.

Linear Algebra Background
A projection operator on a vector space $V$ (such as $\mathbb{R}^n$) is a linear transformation $\mathbb{P}:V\to V$ (that is, an endomorphism of $V$) such that $\mathbb{P}^2=\mathbb{P}$.  This makes its complement $\mathbb{Q}=1-\mathbb{P}$ a projection operator, too, because
$$\mathbb{Q}^2 = \left(1 - \mathbb{P}\right)^2 = 1 - 2\mathbb{P} + \mathbb{P}^2 = 1-2\mathbb{P}+\mathbb{P} = \mathbb{Q}.$$
All projections fix every element of their images, for whenever $v\in \text{Im}(\mathbb{P})$ we may write $v = \mathbb{P}(w)$ for some $w\in V$, whence $$w = \mathbb{P}(v) = \mathbb{P}^2(v) = \mathbb{P}(\mathbb{P}(v)) = \mathbb{P}(w).$$
Associated with any endomorphism $\mathbb{P}$ of $V$ are two subspaces: its kernel $$\text{ker}(\mathbb{P}) = \{v\in v\,|\, \mathbb{P}(v)=0\}$$ and its image $$\text{Im}(\mathbb{P}) = \{v\in v\,|\, \exists_{w\in V} \mathbb{P}(w)=v\}.$$  Every vector $v\in V$ can be written in the form $$v = w+u$$ where $w\in \text{Im}(\mathbb{P})$ and $u\in \text{Ker}(\mathbb{P})$.  We may therefore construct a basis $E \cup F$ for $V$ for which $E \subset \text{Ker}(\mathbb{P})$ and $F \subset \text{Im}(\mathbb{P})$.  When $V$ is finite-dimensional, the matrix of $\mathbb{P}$ in this basis will therefore be in block-diagonal form, with one block (corresponding to the action of $\mathbb{P}$ on $E$) all zeros and the other (corresponding to the action of $\mathbb{P}$ on $F$) equal to the $f$ by $f$ identity matrix, where the dimension of $F$ is $f$.  The trace of $\mathbb{P}$ is the sum of the values on the diagonal and therefore must equal $f\times 1 = f$.  This number is the rank of $\mathbb{P}$: the dimension of its image.
The trace of $1-\mathbb{P}$ equals the trace of $1$ (equal to $n$, the dimension of $V$) minus the trace of $\mathbb{P}$.
These results may be summarized with the assertion that the trace of a projection equals its rank.


text:
Q: Converting to SalesForce datetime format in Mule-3.8.4 using DataWeave 1.0 I am trying to convert a datetime column in a CSV to a salesforce datetime format to do an upsert. I tried expression like below in mule-3.8.4 dataweave1.0 but I am getting an error.
I tried the following:
First Try
Test_Date: "1/14/19 6:31 PM" as :localdatetime { format: "M/dd/yy h:mm a" } as :localdatetime { format: "YYYY-MM-DD'T'hh:mm:ssZ" })

Expected Output : 2019-01-14T06:31:00Z
Actual Output : Mon Jan 14 18:31:00 EST 2019
After Upsert in Salesforce, it looks like this: 2019-01-14T00:00:00.000+0000. It is not saving the time.

Second Try
Test_Date: "1/14/19 6:31 PM" as :localdatetime { format: "M/dd/yy h:mm a" } as :localdatetime { format: "YYYY-MM-DD'T'hh:mm:ss" })

Expected Output : 2019-01-14T06:31:00
Actual Output : Mon Jan 14 18:31:00 EST 2019
After Upsert in Salesforce, it looks like this: 2019-01-14T00:00:00.000+0000. It is still not saving the time.
What is the problem?

A: To format a date, the format pattern reading left to right, needs to match your expected output. So for your example:
2019-01-14T06:31:00Z
yyyy-MM-dd'T'HH:mm:ssZ
y is for year
M is for Month(lowercase m is for minute
d is for day
H is for hour in 24 hr format. (Lowercase would be 12 be format)
S is for milliseconds
And Z is time zone
There's more you can configure for time zone and milliseconds if needed.
Here are the salesforce date format info:
https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/datafiles_date_format.htm
More date format info:
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

A: Have you tried sending it to Salesforce as a String? Once something is of type LocalDateTime, there is no further formatting it. The formatting is solely for the purpose of parsing a String into a LocalDateTime or formatting the output of a LocalDateTime to a String. For example:
"1/14/19 6:31 PM"
  as :localdatetime { format: "M/dd/yy h:mm a" }         // This parses the string as LocalDateTime
  as :localdatetime { format: "YYYY-MM-DD'T'hh:mm:ssZ" } // This doesn't do anything, it's already LocalDateTime

If you want to take one String representing a datetime and format it to a different String representing the same datetime, you could do this:
...
%var inputFormat  = "M/dd/yy h:mm a"
%var outputFormat = "yyyy-MM-dd'T'HH:mm:ss"
---
"1/14/19 6:31 PM"
  as :localdatetime { format: inputFormat  } // Used to parse the input string
  as :string        { format: outputFormat } // Used to format the output string

Output of that last script should be "2019-01-14T18:31:00"

A: Finally below code worked.
Mule Dataweave converted the following format(yyyy-MM-dd'T'HH:mm:ss.SSSZ) to java.util.Calendar Object.
Test_Date: "1/22/19 6:31 PM" as :localdatetime { format: "M/dd/yy h:mm a" } as :datetime { format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ" })
This is how the Payload looks after Transform Message in DataWeave(above step):
Test_Date=java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=0,WEEK_OF_YEAR=13,WEEK_OF_MONTH=5,DAY_OF_MONTH=22,DAY_OF_YEAR=84,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=18,MINUTE=31,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Output after Upsert in SalesForce : 2019-01-22T18:31:00.000+0000


text:
Q: correct use of the MVC and Singleton Swift I have a couple of apps which have been approved by Apple but i'm trying to understand the MVC pattern and in particular the Singleton class. I'm now modifying my code to follow this pattern. I have tried the Singleton class but i'm missing something. Values in the sharedInstance are available in my Model Class but I cant find the answer to this simple question;
I have a class called 'Data', do I create the singleton class and make it a subclass of 'Data' or do I make the 'Data' class a Singleton and private all my functions? My main problem is understanding how to pass data between classes without using a Segue.

A: First of all, segues are for passing data between view controllers and not simple objects.
And regarding your question about singletons, here's how I do it:
class MyClass {

    // Swift's let is lazy-initialized and is thread safe.
    static let sharedSingleton = MyClass()

    private init() {}

    private func printSomething(){
        println("Something")
    }
}

And to use it:
MyClass.sharedSingleton.printSomething()


text:
Q: How does satisfying the Euler-Lagrange equation put a Classical Path on-shell? I am thinking of what the Euler-Lagrange equation,
$$
\frac{d}{dt}\left(\frac{\partial L}{\partial \dot{x}}\right) - \frac{\partial L}{\partial x} = 0
$$
 specifically represents in satisfying the conditions to put a particle "on-shell" in terms of the Classical Action (1).
I know that $\frac{\partial L}{\partial \dot{x}} = p$ I also know that putting a particle "on-shell" is equivalent to stating, in natural units, $E^2 = p^2 + m^2$ (2). In this context, what physical quantities do, the following represent?
$$
\tag{1}
\frac{\partial L}{\partial \dot{x}}
$$
$$
\tag{2}
\frac{d}{dt}\left(\frac{\partial L}{\partial \dot{x}}\right)
$$
and
$$
\tag{3}
\frac{\partial L}{\partial x}
$$
References

*

*The Euler–Lagrange Equations and Noether's Theorem, Springer, (top of page 26)

*On-Shell and Off-Shell, Wikipedia


text:
Q: How do I fix the encoding of the quotes? I am using the free plan of the wordpress.com platform to host reference information on a small site. The goal is to be able to copy the code from the site page and place it in your own IDE, such as VSCode. Since the plan is free, all Wordpress features have been cut to a minimum, including the installation of plugins. It is possible to use only standard blocks such as HTML, Code, Classic Editor, etc. When it became necessary to publish highlighted code, I did not find anything better than to copy it from my code editor and convert it to HTML, then insert it into Wordpress standard HTML block. And for the first time everything was fine, i.e. I was able to copy a block of highlighted code from a page on my site and paste it into the VSCode code editor. And the code was displayed in the same way as on the page. But suddenly, everything changed and the following problems arose: the single quotes character (') began to display as an opening single quote (') and a closing single quote ('), which makes the code inoperable and needs to be edited, which is extremely inconvenient:

describe('Examples for Querying commands', () => {
  before('Navigate to querying page', () => {
    cy.visit('https://example.cypress.io/commands/querying');
  });
  // Скопируйте интересующий вас пример и вставьте его здесь
});

Double quotes began to display incorrectly on the site itself. Instead of ("), they began to display as (»):

cy.get('[data-test-id=»test-example»]')

What could such a metamorphosis be connected with? It happened after the next resave of the edited page. The single quote character is encoded on the page as &apos replacing it with the symbol (') itself does nothing either. You can watch it here: https://kitchensinkcypress.wordpress.com/%d0%bf%d0%be%d0%b8%d1%81%d0%ba-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%be%d0%b2/. The site is under construction. Please tell me how I can overcome it?

A: I am not sure if I can treat this as an answer, but it would be an answer if this is Wordpress bug. I found out that the reason of the issue is page update. Steps to reproduce:

*

*Create html snippet for the highlighted code example.

*Save it into html file, open the file in browser and ensure that all characters are displayed properly.

*Create HTML block on the page and insert there the content of the mentioned html file.

*Open the page in browser and insure that the code is displayed properly.

*Copy the code snippet from the page and paste it into VSCode editor. Ensure that the code is displayed properly.

*Now make any changes anywhere on the web page except of the mentioned HTML block and press Save button.

Expected result: The mentioned code snippet is still displayed properly as no changes were maid inside its HTML block.
Actual result: The snippet has been corrupted. Double quotes (") is turned into (»), single quotes are displayed as opening single quote and closing single quotes if being copied from the page and pasted to VSCode editor:

cy.get('[data-test-id=»test-example»]')

which makes the code not usable. So I believe that this is a Wordpress bug as we have two different results for displaying of the same block of the html code without any user manipulation over this block.


text:
Q: When to use Docker HEALTHCHECK vs livenessProbe / readinessProbe The new ability to specify a HEALTHCHECK in a Dockerfile seems redundant with the Kubernetes probe directives. Any advice on what to use when?

A: If you use Kubernetes, I'd suggest using only the Kubernetes liveness/readiness checks because Docker healthcheck has not been integrated in the Kubernetes as of now (release 1.12). This means that Kubernetes does not expose the check status in its api server, and the internal system components can not consume this information. Also, Kubernetes distinguishes liveness from readiness checks, so that other components can react differently (e.g., restarting the container vs. removing the pod from the list of endpoints for a service), which the docker HEALTHCHECK currently does not provide.
Update: Since Kubernetes 1.8, the Docker HEALTHCHECK has been disabled explicitly in Kubernetes.

A: On Docker
the HEALTHCHECK is basically a command running recurrently during the lifespan of the container. It is used to let the Docker daemon know about the health (i.e. state) of a container.
It is not always useful in general contexts.
On Kubernetes
the liveness probe is a command running recurrently during the lifespan of the container to let the Kubelet know the container is alive and healthy (i.e. up-and-running). The liveness probe is considered successful if the command returns 0, and failed when it returns a non-zero value. If the liveness probe fails, the container is killed and restarted by the Kubelet.
the readiness probe is a command running recurrently during the lifespan of the container to let the Kubelet know if a pod is ready to receive traffic (i.e. ready to work as expected) while it is already alive.
It is useful in the sense that it provides some level of resilience by detecting unhealthy containers that will be automatically restarted.


text:
Q: "Prejudice" in a positive sentence I found some websites use "prejudice" to describe their selling points.

*

*sushi restaurant

*tea store

*industrial company - Not in content but in URL

Can I use prejudice for such positive stuff?  Or is it just a fault caused by machine translation?
FYI: The equivalent (at least they think so) word in Japanese is "こだわり" (kodawari) and it means some points that one believes it cannot be omitted.  The term can be used in both positive and negative sentences.
Only Google translation associates こだわり with prejudice.  I could not find any dictionaries do so.


text:
Q: Why are all of my files in use by a Rails app? We have a Rails (5.0.5) app that manages image files. Users place files into a networked "dropbox" via a lab PC and then "claim" them through the app, which moves them into a separate, hidden storage directory.
I'd like to periodically delete files from this dropbox, but all 240+ of the images in the directory are "in use" and can't be deleted. They can be moved between directories on the network share but not deleted.
I thought it might have been a permissions issue on the mounted network drive, but sudo lsof shows:
ruby    26542 appuser  242r   REG   0,41   757370 32483 /mnt/filestore/dropbox/SCB EXAM.JPG

And ps ax | grep 26542 shows:
26542 ?        Sl     0:02 Passenger RubyApp: /var/www/app/current (production)

To my knowledge, the app only accesses this dropbox directory to provide a list of its contents, to move single files into storage and to return files from storage. I can't reproduce the issue locally.
What might keep these files "in use" by the app? Can I fix it so that I can delete files without stopping the server?
If it helps, here is the code that lists images:
  def self.list_dropbox_images
    # returns array of hashes with keys "name" (only JPGs) and "time" (creation time)
    # File::FNM_CASEFOLD makes it case-insensitive. Nice.
    dropbox_dir.children.map { |child|
      if child.fnmatch?('*.jpg', File::FNM_CASEFOLD)
        { name: child.basename.to_s, time: File.new(child).ctime }
      end
    }.compact
  end

and the code that moves files from the dropbox to storage:
  def self.move_claimed_image(image)
    FileUtils.move(
      Rails.configuration.dropbox_dir.join(image.original_filename),
      Rails.configuration.storage_dir.join(membership_dir(image.course, image.user), "#{image.id}.jpg")
    )
  end

A: By calling File.new(child), you are opening the child file in Ruby. The open File object (and with it the actual OS file handle) will stick around until the object is eventually garbage collected, which might be a long time depending on memory pressure. Until then, the file is still opened.
To fix this, you can get the file's ctime directly without opening the file first by using File.ctime class method instead:
File.ctime(child)


text:
Q: Passing variables to function called by a callback function in Solidity, gas optimizations There are 3 functions in my smart contract, foo() is the one I'm calling, callback() I can't pass enough calldata to, and
bar() is the one that callback() executes,
bar() is the one I need to pass the arguments I'm calling the first function with.
function foo(
    address[] var1,
    address[] var2,
    uint[] var3,
    uint[] var4,
) {
    externalContract.functionThatCallsBack(var1)
}

function callback(bytes calldata var5){
    bar(var2, var3, var4)
}

function bar() {
    //this function needs to receive var2, var3 variables or even more.
}

So far, I can't figure out any other way than using state variables, instantiating a storage slot for var1, var2 etc. on deployment, then passing their desired values along with the call to the foo(). Shadowing state variables when calling foo() is a very costly operation. Is there any workaround here to use memory? It's all separate functions, but one multi-step operation, it would be a shame if 90+% of the variables had to be state variables.
After researching the topic of storage vs memory, I noticed repetitiveness of what's said about the subject as well as there not being much said when it comes to callback functions: e.g.https://ethereum.stackexchange.com/questions/112723/solidity-inline-assembly-how-to-persist-a-value-to-storage-and-access-from-any
Is there a better way to accomplish that?
And thinking in terms of pure optimization, it is widely spread advice that as many computations need to be done off-chain as possible. But what to do in such a situation, where I'd be forced to use storage and state variables, because off-chain calculations are lots and they need to be passed to my functions?
Would it be actually more gas efficient to use on-chain calls + perform some calculations on-chain rather than pass 10-15 variables in the manner I've shown above? Is it either that or on-chain calculations? Is there a cheap solution here?


text:
Q: Expected view to be called with a URL keyword argument named "pk" I'm writing a test for a Django Rest Framework view following closely the testing documentation
Here's my simple test:
def test_patient_detail_api_opens(self):
    factory = APIRequestFactory()
    view =PatientDetailApi.as_view()
    request = factory.get(reverse('api_pacjent', kwargs={'pk' :1}))
    force_authenticate(request, user=self.user)
    response = view(request)
    self.assertEqual(response.status_code, 200)

This test fails with the following message:
AssertionError: Expected view PatientDetailApi to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

I fail to understand why this is happening and how to fix this.

*

*The pk kwargs is there in the URL,

*according to the docs there's no need to add the lookup-field value explicitly if it defaults to pk,

*the view opens correctly and yet this test fails...

Can somebody please explain why this error occurs?
Here's the relevant code:
the 'main' url.py:
urlpatterns = [
    url(r'^pacjent/', include('pacjent.urls')),
]

pacjent.urls looks like this:
url(r'^api/szczegoly/(?P<pk>\d+)/$', PatientDetailApi.as_view(), name="api_pacjent"),

And PatientDetailApi is this:
class PatientDetailApi(generics.RetrieveUpdateAPIView):
    model = Patient
    serializer_class = PatientDetailsSerializer
    queryset = Patient.objects.all()

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

A: I encountered similar error when I made a mistake of using get_object method in perform_create. Read why this wrong from documentation
perform_create(self,instance):
      instance = self.get_object()

A: View functions are called with the request and the arguments from the URL. So pass them:
response = view(request, pk=1)


text:
Q: Getting Data on a table depending on another Right now I have 3 Tables
**Users**
int Id
int Username

**Pages**
int Id
string content;

**Pages_Authors**
int Id
int Pages_Id
int User_Id

I'm trying to make a SQL / Linq statement where I can get the pages depending on the Pages_Author User_Id I input it. Like If my User_Id was 2, it would get all the pages where my User_Id is 2.


text:
Q: SyncRoot for IList My code is old code which uses ArrayList to store elements of collection. I use the m_objects.SyncRoot for locking purpose before delete the object:
        lock(m_objects.SyncRoot)
        {
            m_objects.Remove(obj);

        }

The issue now is, I now want to change the type of  m_objects from ArrayList to List<T>, and I encounter problem with the above code. What is the equivalent of List<T>'s SyncRoot
?

A: I think this might be what you are looking for
List<string> list = new List<string>();
lock (((IList)list).SyncRoot)
{
}

Found at C# Generics Recipes—Replacing the ArrayList with Its Generic Counterpart

A: As far as I understand the concept the SyncRoot is just an object used to lock. It is there just to save you from creating an object to lock. So it has to be the same to do
Object m_objectsLock = new Object();

lock(m_objectsLock)
{
    m_objects.Remove(obj);

}

You have to be sure to use m_objectsLock everywhere where the SyncRoot is used.

A: As far as I understand the SyncRoot concept is outdated and wasn't used much anyway.
Most people went with a lock(){} block instead.
public class SomeClass {
  private readonly object listLock = new object();
  private readonly List<string> yourList = new List<string>();

  public void DeleteItem(string item) {
    lock (listLock) {
      yourList.Remove(item)
    }
  }
}


text:
Q: How to fully utilize all Spark nodes in cluster? I have launched a 10 node cluster with the ec2-script in standalone mode for Spark. I am accessing data in s3 buckets from within the PySpark shell but when I perform transormations on the RDD, only one node is ever used. For example the below will read in data from the CommonCorpus:
bucket = ("s3n://@aws-publicdatasets/common-crawl/crawl-data/CC-MAIN-2014-23/"
          "/segments/1404776400583.60/warc/CC-MAIN-20140707234000-00000-ip-10"
          "-180-212-248.ec2.internal.warc.gz")

data = sc.textFile(bucket)
data.count()

When I run this, only one of my 10 slaves processes the data. I know this because only one slave (213) has any logs of the activity when viewed from the Spark web console. When I view the the activity in Ganglia, this same node (213) is the only slave with a spike in mem usage when the activity was run.
Furthermore I have the exact same performance when I run the same script with an ec2 cluster of only one slave. I am using Spark 1.1.0 and any help or advice is greatly appreciated.

A:
...ec2.internal.warc.gz

I think you've hit a fairly typical problem with gzipped files in that they cannot be loaded in parallel. More specifically, a single gzipped file cannot be loaded in parallel by multiple tasks, so Spark will load it with 1 task and thus give you an RDD with 1 partition.
(Note, however, that Spark can load 10 gzipped files in parallel just fine; it's just that each of those 10 files can only be loaded by 1 task. You can still get parallelism across files, just not within a file.)
You can confirm that you only have 1 partition by checking the number of partitions in your RDD explicitly:
data.getNumPartitions()

The upper bound on the number of tasks that can run in parallel on an RDD is the number of partitions in the RDD or the number of slave cores in your cluster, whichever is lower.
In your case, it's the number of RDD partitions. You can increase that by repartitioning your RDD as follows:
data = sc.textFile(bucket).repartition(sc.defaultParallelism * 3)

Why sc.defaultParallelism * 3?
The Spark Tuning guide recommends having 2-3 tasks per core, and sc.defaultParalellism gives you the number of cores in your cluster.


text:
Q: Angular pass parameter from Template to Controller and from Controller to service I have a code that use Resources to create and list using APIRest, I need pass a Id from template to controller and from controller to service.
This is my code:
Template.html

        <form name="myForm">
            <input type="text" id="userName" ng-model="industrialist.user" placeholder="User name"/>
            <input type="text" id="jobName" ng-model="industrialist.job" placeholder="Job name"/>
            create new user
        </form>

            [[industrial.job.name]]

app.js
var cliConsApp = angular.module('cliConsApp',['uTrans', 'cliConsApp.controllers', 'cliConsApp.services' ]).
    config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    }
);;

services.js
var services = angular.module('cliConsApp.services', ['ngResource']);

services.factory('IndustrialistsFactory', function ($resource) {
    return $resource(
        '/app_dev.php/api/v1/constructionprivateinformations/:id/industrialists',
        {id: '@id'},
        {
            query: { method: 'GET', isArray: true },
            create: { method: 'POST'}
        }
    )
});

controllers.js
var app = angular.module('cliConsApp.controllers', []);

app.controller('industrialistCtrl', ['$scope', 'IndustrialistsFactory',

    function ($scope, IndustrialistsFactory) {

        $scope.init = function (id) {

            $scope.id=id;
            $scope.industrialists= IndustrialistsFactory.query({},{id: $scope.id});

            $scope.createNewUser = function (id) {
                IndustrialistsFactory.create($scope.industrialist, {id: $scope.id});
                $scope.industrialists = IndustrialistsFactory.query({id: $scope.id});

            }
        }
}]);

I have the problem in CreateNewUser because service not recive id and url not is correct.
How I can do it ?

A: I see a major problem with your code. You have declared the models not directly inside the controller but inside the init function. This limits their scope and breaks the expressions like ng-click="createNewUser()". Move them out:
app.controller('industrialistCtrl', ['$scope', 'IndustrialistsFactory',
    function ($scope, IndustrialistsFactory) {
        $scope.id = "";

        $scope.industrialists = [];

        $scope.createNewUser = function (id) {
            // update the models here
        }

        $scope.init = function (id) {
            // update the models here
        }
}]);


text:
Q: LaCie NAS failed - Recover Raid 5 From bad device here is my problem: I have a 5disk (Seagate 2To) RAID5 working with a NAS LaCie 5big. Each disk is still working but the NAS device has failed and it refuses to boot with HDD inside (LaCie helpdesk don't want to help me). And I badly need to recover my data from my RAID. I don't how to do. I've connected my disk to my PC, each of them is recognized but then ... I'm lost. I know the order of the drives in the RAID, but that's all, I 'don't know the format, of the way the RAID was managed by LaCie and can't find information about that in Help/manual provided by LaCie.
*LaCie device failure
*5 out of 5 drives working
*format unkown
LSBLK

sdb       8:16   0   1,8T  0 disk

*

*├─sdb1    8:17   0     1M  0 part

*├─sdb2    8:18   0   1,8T  0 part

*├─sdb3    8:19   0   934K  0 part

*├─sdb4    8:20   0     1M  0 part

*├─sdb5    8:21   0   250M  0 part [SWAP]

*├─sdb6    8:22   0   7,9M  0 part

*├─sdb7    8:23   0  15,7M  0 part

*├─sdb8    8:24   0 823,7M  0 part

*├─sdb9    8:25   0   855M  0 part

*└─sdb10   8:26   0   7,9M  0 part

FDISK

Disk /dev/sdb: 2000.4 GB, 2000398934016 bytes
255 heads, 63 sectors/track, 243201 cylinders, total 3907029168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

*

*Device Boot      Start         End      Blocks   Id  System

*/dev/sdb1               1  3907029167  1953514583+  ee  GPT

PARTED

Model: ATA ST2000DL003-9VT1 (scsi)
Disk /dev/sdb: 2000GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

*

*Number  Start   End     Size    File system     Name     Flags

*5      0,00GB  0,26GB  0,26GB  linux-swap(v1)  primary

*6      0,27GB  0,28GB  0,01GB                  primary

*7      0,28GB  0,30GB  0,02GB  ext3            primary

*8      0,30GB  1,16GB  0,86GB  ext3            primary

*9      1,16GB  2,06GB  0,90GB  ext3            primary

*10      2,06GB  2,07GB  0,01GB                  primary

*1      2,07GB  2,07GB  0,00GB                  primary

*3      2,07GB  2,07GB  0,00GB                  primary

*4      2,07GB  2,07GB  0,00GB                  primary

*2      2,07GB  2000GB  1998GB                  primary

MDADM Produces (2 out of 5 drives plugged)

mdadm --scan --examine >> /etc/mdadm/mdadm.conf

*

*definitions of existing MD arrays

*ARRAY /dev/md/4 metadata=1.0 UUID=02ddd768:323b4b87:e56926a1:e03b01f2
name=LaCie-5big:4

*ARRAY /dev/md3 UUID=88db5732:95381109:3d186b3c:53958f34

*ARRAY /dev/md0 UUID=e77c7ed4:72479a3e:3d186b3c:53958f34

*ARRAY /dev/md1 UUID=9d2ffd1b:c2b6746f:3d186b3c:53958f34

*ARRAY /dev/md2 UUID=6c40830c:b9cf3361:3d186b3c:53958f34
Guess it's Fake Raid?

A: Okay according to those threads :

*

*Tom's Hardware forum - recover mirrored raid device failure

*Mike Taulty's blog - recover Lacie 2Big

*

*I need xfsprogs, cause Lacie main partition are XFS formated.

*Need to mount those partitions of each 5 drives from the RAID5

*Using mdadm assemble the raid back

I guess few step are missing I'll keep on looking for a workaround and edit this answer


text:
Q: mount 2 different directory to the same local directory What will happen if two different directories will be mounted on the same local directory? i would like to know if its possible, and if so, why?
thank you

A: you can but only last mount is active (so you don"t see or access files from the previous one)...
but It will always be a bad idea .... source of error, confusion & so on....


text:
Q: K means formula in argmin $$
\underset{m_1,m_2,\dots,m_k}{\operatorname{arg\,min}} \sum_{i=1}^n \underset{j=1,2,\dots,k}{\min} \| \mathbf{x}_i - m_j \|^2
$$
I found this equation but I forgot the source,
but what I remember is that this equation can solve k-means problem
can you help me elaborate on the formula? so I can understand if the formula is right or not

A: This formula doesn't "solve" $k$-means, it's just an high-level mathematical representation of the problem you are trying to solve. $k$-means is the whole algorithm using expectation-maximization to minimize the given loss function. Commonly, the  improved versions of the algorithm, like $k$-means++, are used instead because they give better performance and time complexity guarantees.
The loss function used by $k$-means can be written in different ways. For example, Wikipedia uses
$$
\underset{S}{\operatorname{arg\,min}} \sum_{j=1}^k \sum_{\mathbf{x} \in S_j} \| \mathbf{x} - m_j\|^2
$$
For each of the $1, 2, \dots, k$ clusters $S_j$ containing the $\mathbf{x}$ points, the loss is the sum of squared errors between the points within the cluster $\mathbf{x} \in S_j$ and cluster's mean $m_i$, i.e. the part
$$
\sum_{\mathbf{x} \in S_j} \| \mathbf{x} - m_j \|^2
$$
we sum the within-cluster squared error to get the total loss. Squared error is used, because minimizing squared error leads to finding the mean. The formula you refer to is a little bit different, but says the same thing
$$
\underset{m_1,m_2,\dots,m_k}{\operatorname{arg\,min}} \sum_{i=1}^n \underset{j=1,2,\dots,k}{\min} \| \mathbf{x}_i - m_j \|^2
$$
Notice that the above formula uses single sum, but over all the $n$ samples. It says that we are looking for smallest means $m_1,m_2,\dots,m_k$ such that it is minimized. There is also this part that differs from the first one
$$
\underset{j=1,2,\dots,k}{\min} \| \mathbf{x}_i - m_j \|^2
$$
Notice that if you take points $x_i \in S_j$ those points would be the closest to the $j$-th cluster mean $m_j$, rather than to other's cluster mean (otherwise they would be assigned to a different cluster). This is the same as saying that we take the smallest of the distances between $\mathbf{x}_i$ and means of all the clusters. So both versions of the formula say the same thing.
As said above, the formulas tell you nothing how to efficiently find the minimum, just that this is the minimum we are aiming to find.


text:
Q: Падение производительности при разных конфигурациях запуска Проект C# UWP Windows 10
Есть БД SQLite, в основной таблице примерно 3000 записей. При загрузке записей к ним догружаются данные из других таблиц. Данные загружаются с разными фильтрами по времени (UnixTimeStamp):
[Indexed]
public long TransDateStamp { get; set; }

*

*При запуске в режиме Debug - все работает нормально.

*В режиме Release - скорость падает.

*При запуске пакета Appx - опять все нормально

*При запуске загруженного приложения из магазина - скорость падает.

Замеры времени производил программно через TimeSpan, ниже таблица измерений на ПК и Мобильном телефоне:

У кого есть идеи - почему такое происходит?
UPD: Причину в принципе выяснил, виновата галочка "Компилировать с использованием цепочки". Если ее выключить, то производительность конфигурации Release нормализуется. Однако, до сих пор не понятно, почему при установке из локального пакета работает нормально, а из магазина нет...
UPD2 Если собрать пакет приложения без этой галочки, то в магазин его отправить не удастся, т.к. он не пройдет сертификацию "Supported API" - Error
UPD3 Гугление по теме наводит на мысль что виноваты анонимные типы которые (если верить MSDN) имею very poor perfomance в среде .NET Native. Теперь вопрос в том как от них избавиться? например такой код:
var query = from item in Transaction.TransactionsHistory(Filter)
                        where !item.isDeleted
                        orderby item.Date descending, item.Created descending
                        group item by item.displayGroupName into g
                        select new { GroupName = g.Key, Items = g };

С таким вот анонимным типом:

UPD4 В общем никакие манипуляции не дали желаемого результата.
MSDN говорит:

Avoid using anonymous types in LINQ queries on UWP. Deploying a UWP
  application to the app store requires your application to be compiled
  with .NET Native. Queries with anonymous types have poor performance
  on .NET Native or may crash the application.

У себя в коде не использовал ни одного anonymous типа, начинаю грешить на SQLiteWrapperUWP-PCL. Пробовал заменить его на BuildIt.Data.Sqlite - получил проседание скорости еще в 1.5 раза. Буду пробовать EF7

A: Итак, после долгих поисков, решение было найдено:
Для проекта использовался враппер который рекомендуется практически в каждой статье связанной с UWP и SQLite: SQLite.Net-PCL - который и являлся источником проблемы.
Эта библиотека является форком sqlite-net-pcl - который показывает одинаковую скорость работы как в среде CIL так и в .NET Native (хотя в CIL незначительно уступает в скорости первому, что компенсируется очень быстрой работой в .NET Native).
P.S. EF7 - еще не готов для использования. Кишит багами, практически неработоспособен в среде .NET Native, хотя и показал крайне высокую скорость работы и удобство использования (по сравнению с предыдущими двумя библиотеками).