text:
Q: why have an NullPointerException that I execute the request? I calculate the sum of to variable getting from 2 request, the result is recovered but when I want to exploit it an NullPointerException is thrown:
 public List<Object[]> buildQuery4SConsistencyCheck(Societe societe,ParamSociete paramSociete,Date
 periode) throws TechnicalNGEException {

    String sql="select SUM(INTERNAL_AMOUNT) from (select   vR.montant_valorise as INTERNAL_AMOUNT"
            + " from sigma02.valorisation_location vR inner join sigma02.eds  soc on
                  vR.societe=soc.id_eds "
            + "inner join sigma02.chantier  ch on vR.compte_de_recette=ch.id_eds"
            + " inner join sigma02.edsm on  vR.id_edsm=edsm.id_edsm inner join sigma02.eds  "
            + "edsR on vR.compte_de_recette=edsR.id_eds where vR.montant_facture !=0 and
                   vR.statut_traitment "
            + "like 'F' and vR.societe = 11 and vR.date_piece='2018-1-31' union all select "
            + " vDep.montant_valorise as INTERNAL_AMOUNT  FROM sigma02.valorisation_location"
            + " vDep inner join sigma02.eds soc on vDep.societe=soc.id_eds "
            + "inner join sigma02.eds as edsDep on vDep.chantier_materiel=edsDep.id_eds "
            + "inner join sigma02.chantier as chDep on vDep.chantier_materiel=chDep.id_eds"
            + " inner join sigma02.edsm on vDep.id_edsm=edsm.id_edsm  WHERE vDep.montant_facture<>0"
            + " and vDep.statut_traitment='F' and vDep.societe=11 and vDep.date_piece='2018-1-31'  )
     as somme";
     List<Object[]> result = null;
        try {
            SQLQuery query = session.createSQLQuery(sql);
            result =  query.list();

        } catch (HibernateException e) {
            bloqException(e);
        }

        return result;

}

in this line where the exception is thrown:
 @Autowired
private ValorisationLocationDAO valorisationLocationDAO;
 Object[]   c=
 valorisationLocationDAO.buildQuery4SConsistencyCheck(societe,paramSociete,periode).get(0);

After debbuggin I get this in result:
[93648.40, null, null, null, null, null, null, null, null, null]

this is the error :
  Caused by: java.lang.NullPointerException
at com.nge.sigma.reprise.util.BatchLogger.log(BatchLogger.java:205) [sigma-
 reprise-0.0.14-SNAPSHOT.jar:]
at com.nge.sigma.reprise.util.BatchLogger.logDebug(BatchLogger.java:193)
[sigma-reprise-0.0.14-SNAPSHOT.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_221]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.8.0_221]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.8.0_221]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.8.0_221]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) [spring-aop-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at com.sun.proxy.$Proxy447.logDebug(Unknown Source)

A: Where is the Exception? There is no NullPointerException.
It looks you are getting confused between variables having null value and NullPointerException which is expected as you are returning  SUM(INTERNAL_AMOUNT); a single value whose value is 93648.40. Other variables are null as expected.

A: It's was a cast problem, I change the return type of the methode to int
 public int buildQuery4SConsistencyCheck(Societe societe,Date periode) throws
 TechnicalNGEException {
    String sql="select SUM(INTERNAL_AMOUNT) from (select   vR.montant_valorise as
    INTERNAL_AMOUNT"
        + " from sigma02.valorisation_location vR inner join sigma02.eds  soc on
              vR.societe=soc.id_eds "
        + "inner join sigma02.chantier  ch on vR.compte_de_recette=ch.id_eds"
        + " inner join sigma02.edsm on  vR.id_edsm=edsm.id_edsm inner join sigma02.eds  "
        + "edsR on vR.compte_de_recette=edsR.id_eds where vR.montant_facture !=0 and
               vR.statut_traitment "
        + "like 'F' and vR.societe = 11 and vR.date_piece='2018-1-31' union all
    select vDep.montant_valorise as INTERNAL_AMOUNT  FROM
       sigma02.valorisation_location"
        + " vDep inner join sigma02.eds soc on vDep.societe=soc.id_eds "
        + "inner join sigma02.eds as edsDep on vDep.chantier_materiel=edsDep.id_eds "
        + "inner join sigma02.chantier as chDep on
           vDep.chantier_materiel=chDep.id_eds"
        + " inner join sigma02.edsm on vDep.id_edsm=edsm.id_edsm  WHERE
           vDep.montant_facture<>0"
        + " and vDep.statut_traitment='F' and vDep.societe=11 and
               vDep.date_piece='2018-1-31'  )
        as somme";
    int result =-1;
        try {
            SQLQuery query = session.createSQLQuery(sql);
                 // cast
             result = ((BigDecimal) query.uniqueResult()).intValue();

        } catch (HibernateException e) {
            bloqException(e);
        }

        return result;

}


text:
Q: MVC: How to use accomplish "partial validation" technique, displaying just a warning and validating the model? I'd need to implement the "partial validation technique" on MVC, evaluating some conditions. The problem is that the validation result, just in some cases, should just display a warning, allowing to validate the model, while on the base of other conditions should return an error. Is it possible?
I am starting from this answer to implement the partial validation:
      public class DontValidateEmailAttribute : ActionFilterAttribute
         {  public override void OnActionExecuting(ActionExecutingContext filterContext)
                 {
                    var modelState = filterContext.Controller.ViewData.ModelState;
                    var incomingValues = filterContext.Controller.ValueProvider;
                    var key = modelState.Keys.Single(x => incomingValues.Equals("Email"));
                    modelState[key].Errors.Clear();
                  }
          }

As I already stated, I need to **display the validation result (for example an email address suggestion) but clear any error regarding the validated attribute
Is this the right direction, or I should use other techniques, like validation dictionaries, etc?
UPDATE
I noticed that this question is related to this one, which is still open.

A: Removing the ModelState entries doesn't seem very neat to me.
If your validation rules aren't numerous, you could inherit your own validation attributes from the standard ones (like WeakRequiredAttribute) that put their validation messages into some other collection (not ModelState's Errors).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need good tutorial for TabActivity I am working on a TabActivity.
I need to learn more detail about it.
There are tutorial regarding this. But all of them are brief.
I want DETAIL. So, if you know such site, give me the address.

Shaiful

A: When I was working on tabs I followed these tutorials
http://www.androidpeople.com/android-tabhost-tutorial-part-1/
http://www.androidpeople.com/android-tabhost-tutorial-part-2/


text:
Q: Get a headervalue of a websocket request using twisted and sockjs I have a sockjs server which is behind haproxy. Now i need to now a clients ip address but using self.transport.getPeer() i get the ip of my haproxy. Haproxy adds a X-Forward-For header to the request with the ip of the original client in it.
How can i get the original http request which has been sent to the server in my protocol?
class MyProtocol(LineReceiver):
    def connectionMade(self):
        # this next line only gives me the ip of my proxy
        ip = self.transport.getPeer()

class MyFactory(protocol.ServerFactory):
    protocol = MyProtocol

my_factory = MyFactory()
sockjs_factory = SockJSMultiFactory()
sockjs_factory.addFactory(my_factory, 'echo')

sockjs_service = internet.TCPServer(10000, sockjs_factory)

application = service.Application("frog32")
sockjs_service.setServiceParent(application)


text:
Q: Clone hard disk of old macbook to new macbook? I have a MacBook mid 2014 with Yosemite on it. If I buy a new MacBook, can I clone the disk from the old MacBook to the new one and have it boot up just like if it was the old one?

A: Yes.
You will need a thunderbolt cable, boot the new computer in target disk mode, and use something like Carbon Copy Cloner to do the job.
Copying via the recovery partition is also possible, but fiddlier.


text:
Q: Json array and play framework 2 with Java I'm using a route to post json to my app based on Play Framework 2 :
This is the content of the route file :
POST    /api/localfeeds             controllers.Application.addMessage()

And this is my java code :
public static Result addMessage() {
  JsonNode json = request().body().asJson();
  if(json == null) {
    return badRequest("Expecting Json data");
  } else {
        String message = json.findPath("message").getTextValue();
        String patate = json.findPath("patate").getTextValue();
        String potato = json.findPath("potato").getTextValue();
    if(message == null || patate == null || potato == null) {
      return badRequest("Missing parameter");
    } else {
    double patateD = Double.parseDouble(patate);
        double potatoD = Double.parseDouble(potato);
        return ok("Json " + json);
    }
  }
}

And finally the curl command I'm using :
curl --header "Content-type: application/json" --request POST --data '{"message": "Guillaume", "potato": "59.34324", "patate": "38.32424"}' http://localhost:9000/api/localfeeds

Now, what I want to do is passing multiple Json objects and treat them in Java, which means I want to make this work :
curl --header "Content-type: application/json" --request POST --data '[{"message": "Guillaume", "potato": "59.34324", "patate": "38.32424"}, {"message": "Guillaume2", "potato": "592.34324", "patate": "382.32424"}]' http://localhost:9000/api/localfeeds

When reading the answers on Google, all I find is that I should use JSONArray and JSONObject but I get an error in the following code :
public static Result addMessage() {
JsonNode json = request().body().asJson();
JSONArray jsonarr = new JSONArray(json);
if(json == null) {
return badRequest("Expecting Json data");
} else {
for(int i = 0; i < jsonarr.length(); i++){
    JSONObject jsonobj = jsonarr.getJSONObject(i);
    String message = jsonobj.findPath("message").getTextValue();
    String patate = jsonobj.findPath("patate").getTextValue();
    String potato = jsonobj.findPath("potato").getTextValue();
    if(message == null || patate == null || potato == null) {
    return badRequest("Missing parameter");
    } else {
        double patateD = Double.parseDouble(patate);
        double potatoD = Double.parseDouble(potato);
        return ok("jsonobj " + jsonobj);
    }
}
}
}

What am I doing wrong ?


text:
Q: How can I render img in Sanity Portable Text I used   render text ,but  i  render img it will be
this ,how to make it work

[   {
"_key": "7f16695776af",
"_type": "image",
"asset": {
"_ref": "image-709f753904446711f664b160ac205b9f9ada6b4b-960x960-png",
"_type": "reference"
}   },   {
"_key": "e6c81237bc58",
"_type": "block",
"children": [
{
"_key": "6cb2873619960",
"_type": "span",
"marks": [],
"text": ""
}
]

*

*


text:
Q: Spring Framework: The document type declaration for root element type "beans" must end with '>' This is my spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans SYSTEM "http://www.springframework.org/dtd/spring-beans-2.0.dtd" PUBLIC "-//SPRING//DTD BEAN 2.0//EN">
<beans>
    <bean id="data" class="com.blah.tests.DataProviderClass" />
    <bean id="wdcm" class="com.blah.tests.WebDriverCustomMethods"/>
</beans>

When I run my application test, this is the error I get:
    Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
 Line 2 in XML document from class path resource [spring.xml] is invalid; nested exception is org.xml.sax.SAXParseException;
 lineNumber: 2; columnNumber: 82; The document type declaration for root element type "beans" must end with '>'.

Im using Spring 3.0.7

A: Try this...
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" >

     <bean id="data" class="com.blah.tests.DataProviderClass" />
     <bean id="wdcm" class="com.blah.tests.WebDriverCustomMethods"/>

</beans>

A: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<!-- <bean/> definitions here -->

</beans>

A: Actually the DTD style is still fully supported:
http://static.springsource.org/spring/docs/3.0.x/reference/xsd-config.html

DTD support?
Authoring Spring configuration files using the older DTD style is still fully supported.
Nothing will break if you forego the use of the new XML Schema-based approach to authoring >Spring XML configuration files. All that you lose out on is the opportunity to have more >succinct and clearer configuration. Regardless of whether the XML configuration is DTD- or >Schema-based, in the end it all boils down to the same object model in the container (namely >one or more BeanDefinition instances).

according to your issue, this is maybe caused by the network, did you try to open http://www.springframework.org/dtd/spring-beans-2.0.dtd directly in the browser?(I think you will get error when you open http://www.springframework.org/dtd/spring-beans-2.0.dtd directly in the browser.)


text:
Q: Resize height of a div according to other one Is it possible to resize right div to the height of left one using just CSS?
My Example
I've tried a jQuery approach like this:
$(document).ready(function () {
   $("#right").css("height", $("#left").height());
});

This approach isn't working well because I have dynamically loaded content in the left div and jQuery approach sometimes miscalculates the height.
I also tried height:100% on the right div but it didn't work.

A: For this you can use display:table property for this. Write like this:
#left{
    margin-right: 15px;
    width: 425px;
    background-color:#11DD52;
}

#right{
    width:200px;
    background-color:#4477AA;
}
#left, #right{
  display:table-cell;
}

Check this http://jsfiddle.net/ZZBM5/

A: EDIT: If you love hacky way of doing things, @sandeep created this great workaround.
I ended up using this great jQuery resize plugin. I was hoping there is an easy CSS solution, but the couple of answers in the comments above give me additional browser compatibility issues.
This is what I've done:
$("#left").resize(function () {
    $("#right").css("height", $(this).height());
});


text:
Q: Firebase - how to detect where the onSnapshot is coming from I'm building a simple firebase app. The main textarea is linked to an entry on Firebase. When the user types, I debounce the keyup event (300ms) and I do an update on Firebase.
Every .update event triggers a onSnapshot event when it comes back from the server (which is the expected behaviour of Firebase). My problem is that it disturbs the user while they type. Because there is a delay between the time the request goes to the server and when it comes back. When it comes back the user has already typed more text and the content of the textarea is different that when the .update was fired.
Here's my code and a jsFiddle that illustrates the problem:
var textareaElement = document.querySelector('textarea');

// Initialize Firebase
var config = {
  apiKey: "XXX",
  authDomain: "XXX",
  projectId: "XXX",
};
firebase.initializeApp(config);
const db = firebase.firestore();
const doc = db.collection("notes").doc('XXX');

// This is debounced
const update = function(){
    doc.update({
    text: textareaElement.value,
    updated_at: firebase.firestore.FieldValue.serverTimestamp()
  })
}

// Update the server when we change the client
textareaElement.addEventListener('keyup', _.debounce(update, 300));

// Listen for changes from the server
doc.onSnapshot(function(doc){
    textareaElement.value = doc.data().text
});

jsFiddle
https://jsfiddle.net/x6h80keb/2 (type at a normal pace and you will see what I mean)
jsFiddle - without serverTimestamp()
https://jsfiddle.net/x6h80keb/6/
I found that removing the call to the serverTimestamp() function helps a lot. It looks like it's responsible for the delay of the request. It makes the "bug" almost unnoticeable, but it still happens sometimes, when the request takes a bit longer to execute.
The only solution I can think of would be to detect the initiator of the update. Whenever a onSnapshot event is triggered, we could look into the doc object, and tell if the change has been made from this client or from another one. But there isn't such a feature apparently.
Any ideas how I could overcome this problem ?
EDIT:
I ended up increasing the debounce delay. Instead of updating after 300ms, I wait a few seconds. This way the user typing can not be disturbed. I'll also freeze the textarea during the .update.

A: This is because the contents of the written document may be different than what the user has typed in since the document was updated.
Rethink this code:
doc.onSnapshot(function(doc){
    textareaElement.value = doc.data().text
});

This is going to overwrite whatever the user has typed since the debounce triggered and the document was updated with their progress.  It will be especially painful on networks with high latency.
Consider instead not rewriting the entire textarea on each document change, and instead showing an indicator for the sync status of their typing.  Is their typing in sync or not?  That's all the user needs to know.  You don't need to overwrite their typing on a regular basis.


text:
Q: What's the coefficient of $z^m$ in  $\Pi_{k=1}^{n}(z-e^{ik\pi})$? Consider the following question:

What's the coefficient of $z^4$ where
$$\Pi_{k=1}^{7}(z-e^{ik\pi}), \quad
z\in{\bf C}$$

I am wondering whether there is some "trick" for solving the problem above quickly, instead of simply expanding the product or using the Taylor expansion. More generally,

What's the coefficient of $z^m$ where
$$\Pi_{k=1}^{n}(z-e^{ik\pi}), \quad
z\in{\bf C}$$

What's the topic to which the above question is related in complex analysis and where such formula might appear?

A: As mentioned above, $e^{ik} \in \{-1,1\}$. Therefore, your product is $(z^2-1)^{n/2}$ when $n$ is even and $(z^2-1)^{(n-1)/2}(z-1)$ if $n$ is odd. Expanding and using binomial coefficients you can get a closed form for the result.

A: You can use contour integration and Cauchy's formula to solve the problem as follows:
If we integrate around a contour, we pick up information about the residues of our function.  Therefore, if we want to convert information about $z^4$ into information contained in residues, we divide by $z^5$.  Then, by integrating over over any circle containing $0$, we obtain the desired result.
Of course, this is probably slower than just using the binomial theorem.


text:
Q: boost::shared_ptr is it safe to use it in multiple threads? I was trying to find the answer for some time but I failed.
Lets assume that we have a shared_ptr created from one thread. Then we pass this shared_ptr to another 2 threads (using some queue for example). So from this moment there are 2 copies of the original shared_ptr, pointing to the same raw pointer.
Both owner threads will take their copies of this shared_ptr from the queue. Then they will pass it to another thread or will destroy it.
Question is - is it safe? Will the raw pointer destroyed correctly (there will be no race to reference counter?)

A: The C++ standard has almost no guarantees regarding thread safety. The reference count of std::shared_ptr is the only exception: it's guaranteed to behave as an atomically accessed variable. I believe this is codified in this phrase in §20.7.2.2/4:

Changes in use_count() do not reflect modifications that can introduce data races.

boost::shared_ptr offers the same guarantees:

shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" … simultaneously by multiple threads. Different shared_ptr instances can be "written to"… simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

A: The boost docs state:

Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

(emphasis mine)
So the crux here is whether you copy the boost::shared_ptrs between threads or not.  If you create copies (the "safe" way to use shared_ptrs) you don't have any worries about thread-safety.  If however you pass the shared_ptr by reference or pointer, and hence are using the actual same shared_ptr in different threads, you would have to worry about thread-safety, as described in the docs.

A: I would like to post my comment for the reference counting  in the boost shared pointer in the multiple threads use cases. The comment is to answer the question that "is there any race condition in the boost shared pointer reference counting?"
My simple answer is "No" at least after boost 1.35 for most mainstream compiler. The boost implementation called "add_ref_copy" defined in the boost/detail/shared_count.hpp. This function will invoke the corresponding atomic function defined for individual compiler. For example, the windows version will call "BOOST_INTERLOCKED_INCREMENT" to increment the count in the atomic way (see details in detail\sp_counted_base_w32.hpp). And the Linux gcc for X86 will call atomic_increment(… ) (see details in detail\sp_counted_base_gcc_x86.hpp). Each individual compiler implemented the thread-safe mechanism to make sure the reference counting update in an efficient way. Some piece of code are even written in assembly.
Now there is a caveats in my simple answer. You really need to make sure your compiler is included in the boost's blessed list for multiple thread-safe reference counting. If you are not sure you can define "BOOST_SP_USE_PTHREADS" which drives boost to use the pthread library to make reference count update atomically (by including boost/detail/sp_counted_base_pt.hpp for pthread solution).


text:
Q: Reverse implication of Hilbert's Basis Theorem I have been looking over multiple proof regarding Hilbert's basis theorem. Namely, if $R$ is a commutative noetherian ring, then $R[x]$ is also notherian.
I understand, for the most part, the construction of this proof. My question is, can Hilbert's basis theorem be written as an if and only if statement? In other words, is it true that if $R[x]$ is noetherian then $R$ is also noetherian? If it can be, then I have an idea on how to prove it, but I would like some feedback.
Proof:
Let $R[x]$ be noetherian. Let $$\phi: R[x] \rightarrow R$$ be the homomorphism of rings where $$\phi(f) = f(0).$$
It follows then that $\phi(R) = R$. In other words, $\phi$ is onto. Now, it is not hard to check that the image of a noetherian ring is noetherian. Thus $R$ is noetherian. $\square$
My question is, is my proof is correct? Furthermore, if it is correct, how come a lot of standard algebra texts don't state this theorem as an if and only if?

A: Your proof is correct! I think the reason algebra texts don't state Hilbert's Basis Theorem as a biconditional is that this direction is much more obvious (and less often useful). I also have one nitpick: you should say "the homomorphism" instead of "a homomorphism" because you are clearly singling out a unique map.


text:
Q: Finding $\iint_D \nabla \cdot F \; \mathrm{d}A$ I want Finding $\iint_D \nabla \cdot F \; \mathrm{d}A$.
Normally I have dealt with $\nabla F$ for $F(x,y,z)=xyz$ sort of cases, where I just then derive it in terms of $x,y,z$ for my $i,j,k$.
Here though, I have $F(x,y) = xy\boldsymbol{i}+x^2\boldsymbol{j}$.
What do I do to find $\nabla \cdot F$ here, use whatever example you wish, just please make it of type $F(x,y) = xy i + xy j$ with whatever $x$ and $y$ you want.

A: For $F:\mathbb{R}^{2}\rightarrow \mathbb{R}^{2}$
$\begin{eqnarray}\nabla\cdot F&=&(\frac{\partial}{\partial x}, \frac{\partial}{\partial y})\cdot(f_{1}(x,y), f_{2}(x,y))^{t}\\
&=& \frac{\partial f_{1}}{\partial x}+ \frac{\partial f_{2}}{\partial y} \end{eqnarray}$
where in the first line is the inner product of those vectors.
In your case
$\begin{eqnarray}\nabla\cdot F&=&(\frac{\partial}{\partial x}, \frac{\partial}{\partial y})\cdot(xy, x^{2})^{t}\\
&=& y+ 0 \end{eqnarray}$
I hope it helps you :-)


text:
Q: Biholomorphic but not isomorphic complex affine surfaces? Suppose $X$ and $Y$ are smooth affine surfaces over $\mathbb C$. Suppose there is a biholomorphism $f: X\to Y$. Does it follow that $X$ and $Y$ are isomorphic as affine surfaces (i.e. there exists an algebraic isomorphism $g: X\to Y$)?
What if we additionally know that $X$ and $Y$ are rational surfaces?

A: Let $\overline{C}$ be a complex projective curve of genus $g>0$.  Let $C\subset \overline{C}$ be the open affine complement of one (closed) point $p$.  The composition $\text{Pic}^0(\overline{C})\to \text{Pic}(\overline{C})\to \text{Pic}(C)$ is an isomorphism.  Let $L$ be any nontrivial (geometric) rank $1$ vector bundle over $C$.  This is affine, since $C$ is affine and the projection morphism from $L$ to $C$ is affine.  This projection morphism equals the image of the Albanese morphism of $L$ (this is a birational invariant for complex projective manifolds, thus extends unambiguously to complex quasi-projective manifolds).  The relative tangent bundle of this projection morphism is the pullback from $C$ of a unique invertible sheaf, namely the invertible sheaf associated to $L$.  Thus, the relative tangent bundle of the Albanese morphism is not trivial.  Hence $L$ is not isomorphic to $\mathbb{A}^1\times C$.  Yet the underlying complex manifolds are biholomorphic.

A: Update: Note that this fails to provide the required example since the second algebraic structure is not affine as desired. However, I am not deleting this answer as yet.
The moduli of flat line bundles over a curve $X$ of genus $g$ is parametrized holomorphically by $\left(\mathbb{C}^*\right)^{2g}$. This uses the topological description of such a line bundle in terms trivialisation on the universal cover. This yields one algebraic structure given by $(\mathbb{G}_m)^{2g}$. In particular, this has no morphisms to an Abelian variety.
On the other hand, a line bundle with a flat connection has degree 0. Different flat connections on a line bundle differ by a holomorphic $1$-form on $X$. This shows that the algebraic moduli space of flat connections on a line bundle over $X$ is an affine space torsor $T$ for $H^0(X,\Omega^1_X)$ over $\mathrm{Pic}^0(X)$. In other words, $T\to \mathrm{Pic}^0(X)$ is a bundle of $\mathbb{A}^g$'s.
Thus $T$ and $(\mathbb{G}_m)^{2g}$ are two different algebraic structures (since one maps to $\mathrm{Pic}^0(X)$ and the other does not) for the same underlying holomorphic manifold of dimension $2g$. The original question (for surfaces) is answered by taking $g=1$.
@aglearner has asked how we see that there is an algebraic moduli space for flat connections of a fixed dimension $r$ over a smooth projective variety $X$. The most comprehensive reference is the work of Simpson here and here. However, there ought to be easier to read explanations when $X$ is a curve and $r$ is 1, but I could not find them!


text:
Q: Open Windows Explorer directory, select a specific file (in Delphi) I have a procedure to open a folder in Windows Explorer that gets passed a directory path:
procedure TfrmAbout.ShowFolder(strFolder: string);
begin
   ShellExecute(Application.Handle,PChar('explore'),PChar(strFolder),nil,nil,SW_SHOWNORMAL);
end;

Is there a way to also pass this a file name (either the full file name path or just the name + extension) and have the folder open in Windows Explorer but also be highlighted/selected? The location I am going to has many files and I need to then manipulate that file in Windows.

A: Yes, you can use the /select flag when you call explorer.exe:
ShellExecute(0, nil, 'explorer.exe', '/select,C:\WINDOWS\explorer.exe', nil,
  SW_SHOWNORMAL)

A somewhat more fancy (and perhaps also more reliable) approach (uses ShellAPI, ShlObj):
const
  OFASI_EDIT = $0001;
  OFASI_OPENDESKTOP = $0002;

{$IFDEF UNICODE}
function ILCreateFromPath(pszPath: PChar): PItemIDList stdcall; external shell32
  name 'ILCreateFromPathW';
{$ELSE}
function ILCreateFromPath(pszPath: PChar): PItemIDList stdcall; external shell32
  name 'ILCreateFromPathA';
{$ENDIF}
procedure ILFree(pidl: PItemIDList) stdcall; external shell32;
function SHOpenFolderAndSelectItems(pidlFolder: PItemIDList; cidl: Cardinal;
  apidl: pointer; dwFlags: DWORD): HRESULT; stdcall; external shell32;

function OpenFolderAndSelectFile(const FileName: string): boolean;
var
  IIDL: PItemIDList;
begin
  result := false;
  IIDL := ILCreateFromPath(PChar(FileName));
  if IIDL <> nil then
    try
      result := SHOpenFolderAndSelectItems(IIDL, 0, nil, 0) = S_OK;
    finally
      ILFree(IIDL);
    end;
end;

A: The answers at delphi.lonzu.net and swissdelphicenter offer a simpler solution to this. I've only tested it on Windows 10, 1909,, but the gist of it is:
uses ShellApi, ...
...
var
   FileName : TFileName;
begin
  FileName := 'c:\temp\somefile.html';

  ShellExecute(Handle, 'OPEN',
    pchar('explorer.exe'),
    pchar('/select, "' + FileName + '"'),
    nil,
    SW_NORMAL);
end;

This is simple and easy to use. Whether it works with older versions of Windows, I don't know.


text:
Q: Set initial state in react-draft-wysiwyg and update state on props change I get rawData as props in html form, so I need to begin with convertFromHTML and then create EditorState which all works fine if I navigate from /article/:articleId -> /article/:articleId/edit but If I go straight to /article/:articleId/edit then it means that articles/:articleId should fetch article first so that it can pass the data to the editor, and when the props change, I need to update the state of the editor.
import React from 'react';
import { EditorState, ContentState, convertFromHTML, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import { Box } from '@mui/material';
import '../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

type TextEditorProps = Readonly<{
  rawData: string;
}>;

export const TextEditor = ({ rawData }: TextEditorProps) => {
  const blocksFromHTML = convertFromHTML(rawData);
  const state = ContentState.createFromBlockArray(
    blocksFromHTML.contentBlocks,
    blocksFromHTML.entityMap,
  );

  const initialState = blocksFromHTML
    ? EditorState.createWithContent(state)
    : EditorState.createEmpty();

  const [editorState, setEditorState] = React.useState<EditorState>(initialState);

  const onEditorStateChange = (editorState: React.SetStateAction<EditorState>) => {
    setEditorState(editorState);
  };

  return (
    <Box component="form" noValidate autoComplete="off">
      <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onEditorStateChange={onEditorStateChange}
      />
    </Box>
  );
}

This is what I tried:
  useEffect(() => {
    const blocksFromHTML = convertFromHTML(rawData);
    const state = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap,
    );
    if (EditorState.createWithContent(state) !== editorState) {
      setEditorState(EditorState.createWithContent(state));
    }
  }, [state, editorState, rawData]);

But I get this error:
Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I know why it happens but I cannot see how to fix it.

A: const WYSIWYGEditor = ({ input, meta }) => {
  const blocksFromHTML = convertFromHTML(input.value);
  const content = ContentState.createFromBlockArray(
    blocksFromHTML.contentBlocks,
    blocksFromHTML.entityMap,
  );
  const raw = convertToRaw(content);
  const [contentState, setContentState] = useState(raw);
  const onEditorStateChange = (contentState) => {
    setEditorState(contentState);
    return input.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())));
  };
  return (
    <div className="editor">
      <Editor
        defaultContentState={contentState}
        onEditorStateChange={onEditorStateChange}
        wrapperClassName="wrapper-class"
        editorClassName="editor-class"
        toolbarClassName="toolbar-class"
        placeholder="Write your answere here"
      />
    </div>
  );
};
export default WYSIWYGEditor;

**This is working fine for me **


text:
Q: How to test for significant difference between 2 proportions? I study linguistics, and I'm conducting a research which compares the ratio between two categories of words in 2 different text corpuses.
Let's say I have corpuses A and B. I created 2 categories of words, Let's call them C and D. I want to calculate the ratio between the count of words in category C and the count of words in category D, and see if the ratio in corpus A is significantly larger than the ratio in corpus B.
What statistical test can I use to test this hypothesis?
It's worth mentioning that the count of words in category C should theoretically depend on the count of words in category D and vice versa.
Thanks in advance

A: First, note that if the ratio of C to D is larger in corpus A, then so will be the proportion.  So you can do the standard hypothesis test for difference of proportions.
Let:
$$p_A = {C_A\over C_A + D_A}$$
$$p_B = {C_B\over C_B + D_B}$$
$$p = {C\over C + D}$$
These are the proportions of words in each corpus as well as the total for both corpuses.
Then set $$Z = {(p_A - p_B)\over p(1 - p)({1\over C_A + D_A} + {1\over C_B + D_B})}$$
If the number of words from categories C and D is large, then your test statistic should be approximately normal.  The null hypothesis is that Z = 0 and the two proportions are equal.  If you want a p-value of .05, you can reject the null hypothesis when Z > 1.645.


text:
Q: Extract Xunit test class name from ITestOutputHelper object (C# ) Can I use the ITestoutputHelper injected object to get the calling class name?

A: After a great comment by @ZdeněkJelínek, I end up implementing this static extension function to ITestOutputHelper.

        public static string GetTestClassName(this ITestOutputHelper helper)
    {
            var type = helper.GetType();
            var testMember = type.GetField(FieldName, BindingFlags.Instance | BindingFlags.NonPublic);
            return((ITest) testMember.GetValue(helper)).TestCase.TestMethod.TestClass.Class.Name;
    }


text:
Q: Problema com decodificação de caracteres Estou usando uma função para limitar a quantidade de caracteres que são mostrados, algo como isso:
 function blabla ($string, $maxSize) {
    if (strlen($string) > $maxSize)
                $string = substr($string, 0, $maxSize) . ' [...]';
            return $string;
}

Só que está retornando alguns caracteres bugados como: "título" fica "T�tulo", mas quando eu não uso a função a string vem normal,sem caracteres bugados. como posso resolver isso?
Estou usando isto no header:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: Use mb_substr() ao invés de substr() manual. Uma excelente resposta em outro contexto, mas que se amolda ao seu questionamento: Problema ao usar substr em texto com PHP


text:
Q: How to change IE to Non-compatibility mode without the meta-tag I need to change IE browsers to use the latest mode, 9 or 10, but I do not have access to the header so I cannot put in the tag <meta http-equiv="X-UA-Compatible" content="IE=Edge">. I did use DOM Manipulation to add the tag to the beginning of the header tag, but since that part of the page already loads before the jquery can put it in there, it does not affect IE. Is there a way to change the mode, or to reload the header only once so it changes the mode its in.

A: How is the page hosted, do you have access to the web server configuration?
If so, you can set X-UA-Compatible as a response header.
E.g. configuring Apache would be something like this:
<IfModule headers_module>
    Header set X-UA-Compatible: IE=Edge
</IfModule>

and could be done in either Apache's httpd.conf or possibly in a .htaccess file if AllowOverride is on.
If you don't have access to web server configuration, you could try to set the same header from whatever language/framework you use to serve the pages.


text:
Q: VS code SSH tunnel I have question about ssh tunnel in VS code. I am using for connecting to remote machine Remote - SSH extension. My setup now is: putty for connecting to server, in Putty after it is created Tunnel to next point.
PUTTY -> someIP -> polaris:22 (tunnel)
Putty create tunnel to polaris on localhost:4000. After it, I can use VS code with remote SSH to localhost:4000 and it working fine.
Is in this extension some possibility to create SSH tunnel directly without using putty? :)

A: I got the answer from https://superuser.com/questions/1528212/vscode-ssh-with-multiple-hops
In my case I'm using VSCode in windows to connect to several linux machines from the organization net and from outside the organization via an ssh tunnel.
In my configuration file remoteSsh.configFile I have the following configuration.
Host machineName1 (to connect from inside organization)
  HostName [machineName1.organization_internal_extension]
  Port [portNumber for ssh]
  User [Username]
  IdentifyFile [local path to ssh key]
  ForwardAgent yes
  ForwardX11 yes
  ForwardX11Trusted yes

Host machineName2 (to connect from inside organization)
  HostName [machineName2.organization_internal_extension]
  Port [portNumber for ssh]
  User [Username]
  IdentifyFile [local path to ssh key]
  ForwardAgent yes
  ForwardX11 yes
  ForwardX11Trusted yes

Host tunne_machineName1 (to connect from outside organization)
  HostName [machineName1.organization_internal_extension]
  Port [portNumber for ssh]
  User [Username]
  IdentifyFile [local path to ssh key]
  ForwardAgent yes
  ForwardX11 yes
  ForwardX11Trusted yes
  ProxyJump machine_tunnel

Host tunne_machineName2 (to connect from outside organization)
  HostName [machineName2.organization_internal_extension]
  Port [portNumber for ssh]
  User [Username]
  IdentifyFile [local path to ssh key]
  ForwardAgent yes
  ForwardX11 yes
  ForwardX11Trusted yes
  ProxyJump machine_tunnel

Host machine_tunnel( machine to jump)
  HostName [machineName.organization_internal_extension]
  Port [portNumber for ssh on tunnel machine]
  User [Username]
  IdentifyFile [local path to ssh key]
  ForwardAgent yes
  ForwardX11 yes
  ForwardX11Trusted yes

The X11 forward is not mandatory.
Hope this helps

A: Put the following information into your local machine's /.ssh/config:
Host [1]
    HostName [2]
    User [3]
    Port [4]

Substitute [1], [2], [3], and [4] with a host name you prefer, the IP address of the host, the user name you log in the remote server, and the localhost port assigned to you.
For example,
Host VM1000
    HostName 123.45.678.9
    User root
    Port 4000

Then you can just click the Remote Explorer icon in VS Code and click the VM1000 entry to connect your local machine to the remote server.
Hope this resolve your connection problem.


text:
Q: Storing user authentication responses with DotNetOpenAuth Just getting my head round DotNetOpenAuth and need clarification on something so hope someone can advise.
Looking at the samples (OpenIdProviderWebForms) at the provider end after successful login, the user is presented with the confirmation page asking you to confirm (decide.aspx). If you click 'Yes', ideally I would like it to store this so that the next time the user does not see this page.
My question is, would this typically be something the provider would have to add into the code to store it in their own database for example? Or are there some tools, techniques or provisions already in DotNetOpenAuth to do this that I've missed. The only thing I can find around this is CustomStore.
You advice is appreciated.

A: Remembering the user's choice is something the provider should store in its database.  DotNetopenauth supports this but it does require work on your end to decide to go ahead and respond positively.


text:
Q: How do I make a project that uses protocol buffers? I'm trying to build the address-book example on Google's protocol buffers.
This is my Makefile
CFLAGS = -O3
CPP = g++
MSGS = addressbook.pb.o
LIBS=-lprotobuf

%.pb.o: %.proto
        protoc --cpp_out=./ $<
        $(CPP) $(CFLAGS) -c $*.pb.cc -o $@

%.o: %.cpp
        $(CPP) $(CFLAGS) -c $< -o $@

main: $(MSGS) main.o
        $(CPP) $^ -o test $(LIBS)

clean:
        rm test *.pb.* *.o

I run make main. It correctly does:
protoc --cpp_out=./ addressbook.proto
g++ -O3 -c addressbook.pb.cc -o addressbook.pb.o
g++ -O3 -c main.cpp -o main.o
g++ addressbook.pb.o main.o -o test -lprotobuf

However, I'm getting a bunch of linking errors, they all seem like I'm not linking to -lprotobuf, which I clearly am.
Sample error:
/usr/bin/ld: addressbook.pb.o:addressbook.pb.cc:(.text+0x3fca): more undefined references to `google::protobuf::internal::ArenaStringPtr::Mutable[abi:cxx11](google::protobuf::internal::ArenaStringPtr::EmptyDefault, google::protobuf::Arena*)' follow
/usr/bin/ld: addressbook.pb.o: in function `tutorial::Person::Person(tutorial::Person const&) [clone .cold]':
addressbook.pb.cc:(.text.unlikely+0x1fe): undefined reference to `google::protobuf::internal::ThreadSafeArena::SpaceAllocated() const'
/usr/bin/ld: addressbook.pb.o: in function `tutorial::AddressBook::AddressBook(tutorial::AddressBook const&) [clone .cold]':
addressbook.pb.cc:(.text.unlikely+0x22c): undefined reference to `google::protobuf::internal::ThreadSafeArena::SpaceAllocated() const'
/usr/bin/ld: addressbook.pb.o: in function `google::protobuf::RepeatedPtrField<tutorial::Person_PhoneNumber>::~RepeatedPtrField()':
addressbook.pb.cc:(.text._ZN6google8protobuf16RepeatedPtrFieldIN8tutorial18Person_PhoneNumberEED2Ev[_ZN6google8protobuf16RepeatedPtrFieldIN8tutorial18Person_PhoneNumberEED5Ev]+0x4e): undefined reference to `google::protobuf::internal::ThreadSafeArena::SpaceAllocated() const'
/usr/bin/ld: addressbook.pb.o: in function `google::protobuf::RepeatedPtrField<tutorial::Person>::~RepeatedPtrField()':
addressbook.pb.cc:(.text._ZN6google8protobuf16RepeatedPtrFieldIN8tutorial6PersonEED2Ev[_ZN6google8protobuf16RepeatedPtrFieldIN8tutorial6PersonEED5Ev]+0x2f): undefined reference to `google::protobuf::internal::ThreadSafeArena::SpaceAllocated() const'
/usr/bin/ld: addressbook.pb.o: in function `google::protobuf::UnknownFieldSet* google::protobuf::internal::InternalMetadata::mutable_unknown_fields_slow<google::protobuf::UnknownFieldSet>()':
addressbook.pb.cc:(.text._ZN6google8protobuf8internal16InternalMetadata27mutable_unknown_fields_slowINS0_15UnknownFieldSetEEEPT_v[_ZN6google8protobuf8internal16InternalMetadata27mutable_unknown_fields_slowINS0_15UnknownFieldSetEEEPT_v]+0x37): undefined reference to `google::protobuf::Arena::AllocateAlignedWithCleanup(unsigned long, std::type_info const*)'
/usr/bin/ld: addressbook.pb.o: in function `google::protobuf::internal::GenericTypeHandler<tutorial::Person_PhoneNumber>::Merge(tutorial::Person_PhoneNumber const&, tutorial::Person_PhoneNumber*)':
addressbook.pb.cc:(.text._ZN6google8protobuf8internal18GenericTypeHandlerIN8tutorial18Person_PhoneNumberEE5MergeERKS4_PS4_[_ZN6google8protobuf8internal18GenericTypeHandlerIN8tutorial18Person_PhoneNumberEE5MergeERKS4_PS4_]+0xc2): undefined reference to `google::protobuf::internal::ArenaStringPtr::Set(google::protobuf::internal::ArenaStringPtr::EmptyDefault, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, google::protobuf::Arena*)'

A: There's no way we can help with the information provided.  Please show (a) the make command line you invoked, (b) the linker command that make invoked, and (c) the FIRST few errors that were generated by that command.
I'm not sure what the problem is because I'm not familiar with protobuf.  However, your makefile is quite odd; I recommend you rewrite it like this:
CFLAGS = -O3
CPP = g++
LIBS=-lprotobuf

%.pb.cc: %.proto
        protoc --cpp_out=./ $<

%.pb.o: %.pb.cc
        $(CPP) $(CFLAGS) -c $< -o $@

%.o: %.cpp
        $(CPP) $(CFLAGS) -c $< -o $@

main: main.o addressbook.pb.o
        $(CPP) $^ -o test $(LIBS)

clean:
        rm test *.pb.*

and see if that works any better.  If that doesn't work then it must be something incorrect about your code; at the least it doesn't seem like a makefile or linker invocation problem.


text:
Q: Error installing Spacy ERROR: Command errored out with exit status 1: I'm trying to install Spacy on a Windows machine of 32 bits. I have python 3.8.
I get this error when I try to install Spacy (output is too long, I'll insert a fragment)

(base) C:\Users\User>pip install spacy --no-cache-dir
Collecting spacy
  Downloading spacy-2.3.2.tar.gz (5.9 MB)
     |████████████████████████████████| 5.9 MB 3.3 MB/s
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\user\anaconda3\python.exe' 'c:\users\user\anaconda3\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\User\AppData\Local\Temp\pip-build-env-zhupmafd\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'cython>=0.25' 'cymem>=2.0.2,<2.1.0' 'preshed>=3.0.2,<3.1.0' 'murmurhash>=0.28.0,<1.1.0' thinc==7.4.1
       cwd: None
  Complete output (430 lines):
  Collecting setuptools
    Using cached setuptools-50.1.0-py3-none-any.whl (784 kB)
  Collecting wheel
    Using cached wheel-0.35.1-py2.py3-none-any.whl (33 kB)
  Collecting cython>=0.25
    Using cached Cython-0.29.21-cp38-cp38-win32.whl (1.6 MB)
  Collecting cymem<2.1.0,>=2.0.2
    Using cached cymem-2.0.3.tar.gz (51 kB)
  Collecting preshed<3.1.0,>=3.0.2
    Using cached preshed-3.0.2.tar.gz (167 kB)
  Collecting murmurhash<1.1.0,>=0.28.0
    Using cached murmurhash-1.0.2.tar.gz (35 kB)
  Collecting thinc==7.4.1
    Using cached thinc-7.4.1.tar.gz (1.3 MB)
  Collecting blis<0.5.0,>=0.4.0
    Using cached blis-0.4.1.tar.gz (1.8 MB)
  Collecting wasabi<1.1.0,>=0.0.9
    Using cached wasabi-0.8.0-py3-none-any.whl (23 kB)
  Collecting srsly<1.1.0,>=0.0.6
    Using cached srsly-1.0.2.tar.gz (192 kB)
  Collecting catalogue<1.1.0,>=0.0.7
    Using cached catalogue-1.0.0-py2.py3-none-any.whl (7.7 kB)
  Collecting numpy>=1.7.0
    Using cached numpy-1.19.1-cp38-cp38-win32.whl (10.9 MB)
  Collecting plac<1.2.0,>=0.9.6
    Using cached plac-1.1.3-py2.py3-none-any.whl (20 kB)
  Collecting tqdm<5.0.0,>=4.10.0
    Using cached tqdm-4.48.2-py2.py3-none-any.whl (68 kB)
  Building wheels for collected packages: cymem, preshed, murmurhash, thinc, blis, srsly
    Building wheel for cymem (setup.py): started
    Building wheel for cymem (setup.py): finished with status 'error'
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\user\anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-4jggcsja\\cymem\\setup.py'"'"'; __file__='"'"'C:\\Users\\User\\AppData\\Local\\Temp\\pip-install-4jggcsja\\cymem\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\User\AppData\Local\Temp\pip-wheel-chusorxt'
         cwd: C:\Users\User\AppData\Local\Temp\pip-install-4jggcsja\cymem\

I have tried:

*

*pip install spacy

*conda install -c conda-forge spacy

*pip install spacy --no-cache-dir
Nothing works! What do I need to do?

A: Spacy has dropped support for 32 bit and so you'll need to use 64 bit Python.


text:
Q: Protected member conflict with overloading operator I have the following classes:
class Base {
protected:
    int myint;
};

class Derived : public Base {
public:
    bool operator==(Base &obj) {
        if(myint == obj.myint)
            return true;
        else
            return false;
    }
};

But when I compile it, it gives the following errors:

int Base::myint is protected within this context

I thought that protected variables are accessible from the derived class under a public inheritance. What is causing this error?

A: Derived can access protected members of Base on all instances of Derived only. But obj isn't an instance of Derived, it's an instance of Base - so access is forbidden. The following would compile fine, since now obj is a Derived
class Derived : public Base {
public:
    bool operator==(const Derived& obj) const {
        return myint == obj.myint;
    }
};


text:
Q: Iterating through an array by returning a set of 6 elements in jQuery $.each loop I am iterating through an array of 12 objects, every time I iterate through it by pressing the button under a class of .more, I have to return a block of 6 elements and I am confused as to how I can achieve this. This is my code so far:
HTML
<template>

      <button class="more btn btn-primary md">See More</button>

</template>

JS:
import $ from 'jquery'

$(document).ready(function () {
    const objects = [
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/791/791d4f7e1811fc18b008e31b047a54a6/3e03093c347a4555d92807d3256f0a7e.png",
            "description": "Some description",
            "link": "Some link"

        },
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/b4e/b4e9551322feee132949ffbd60f05397/aee8267040ae839cb0bf672ab5970bda.png",
            "description": "Some description",
            "link": "Some link"
        },
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/e99/e99743d644ded41e802a1741e832b4b4/77d8a8e4af7fab0a1f84d9a9c6cb48cf.png",
            "description": "Some description",
            "link": "Some link"
        },
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/d05/d05042d4e116ba8ad2c4f29bbb45fa00/69c29b1afc93a6c7423fed01a3ac6c63.jpg",
            "description": "Some description",
            "link": "Some link"
        },
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/252/25299d51a4b47cd7d2b8babeb0658a68/c45aa13e7282b1e9628ffea8ed9dfb20.png",
            "description": "Some description",
            "link": "Some link"
        },
        {
            "title": "Some Title",
            "img": "https://248006.selcdn.ru/main/iblock/3a5/3a5a20dc5c2df3fe6db3ccd499880eb3/61a581933fe2134ecec44e432d7c6f31.png",
            "description": "Some description",
            "link": "Some link"

        },
        {
            "title": "Another Title",
            "img": "https://248006.selcdn.ru/main/iblock/3a5/3a5a20dc5c2df3fe6db3ccd499880eb3/61a581933fe2134ecec44e432d7c6f31.png",
            "description": "Some description",
            "link": "Another link"

        },
        {
            "title": "New Title",
            "img": "https://248006.selcdn.ru/main/iblock/3a5/3a5a20dc5c2df3fe6db3ccd499880eb3/61a581933fe2134ecec44e432d7c6f31.png",
            "description": "Some description",
            "link": "Newer link"

        },
        {
            "title": "New Title",
            "img": "https://248006.selcdn.ru/main/iblock/218/218adba31af31ec25cfd345a94974fa1/e37024d8cbd416964bbe075ea53ecf8f.png",
            "description": "Some description",
            "link": "Newer link"

        },
        {
            "title": "Lorem",
            "img": "https://248006.selcdn.ru/main/iblock/3a5/3a5a20dc5c2df3fe6db3ccd499880eb3/61a581933fe2134ecec44e432d7c6f31.png",
            "description": "Some description",
            "link": "Newer link"

        },
        {
            "title": "Some title",
            "img": "https://248006.selcdn.ru/main/iblock/282/282214a04b2c627ecf552efdb71c38f7/c0dbdfdcf4c2901099855f157324f21d.png",
            "description": "Some description",
            "link": "Newer link"

        },
        {
            "title": "Some title",
            "img": "https://248006.selcdn.ru/main/iblock/a9c/a9c6702dcb9b98c0ae79f68d2801a09b/288c49908d4e0e1a97b528615bdc801a.png",
            "description": "Some description",
            "link": "New link"

        },

    ];
    var i = 0;

    $('.more').on('click', function () {
        $.each(objects, function(index, value){

            $('.cards').append('
' + '' + '

' + '

' + '' + '' + '
');
            $('.cards .card-' + index + " h4").html('
' + value.title + '
');
            $('.cards .card-' + index + " a").html('' + value.link + '');

            $('.cards .card-' + index + " p").html('
' + value.description + '
');

            $('.cards .card-' + index + " img").attr("src", value.img);
            objects.slice(i, i + 6);

        });
    });
    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

    for (var z = 0; z < arr.length; z += 4) {
    console.log("Working with: " + arr.slice(z, z + 4));
    }
});

I tried implementing a counter of i, but every time it returns the same objects without iterating through an array fully. It's kind of hard to explain, excuse my English.

A: First of all do not use this idea on click.
$('.cards .card-' + index + " img").attr("src", value.img);

On each click the index start from zero so you get duplicate card-1 card-2 and so on (Mega buggy).

If you want to add unique index class for each card use extra variable (Not related to index of each function).
  let card_index = 1;

  $('.more').on('click', function () {
    $.each(objects.slice(start_at, cursor), function(index, value){
      $('.cards').append('
' + value.title + '
');

One solution
slice(start, end)

Use slice and on each click update the start and end points (Like "cursor" idea).

$(document).ready(function () {
  const objects = [
    {
      "title": "object 1",
    },
    {
      "title": "object 2",
    },
    {
      "title": "object 3",
    },
    {
      "title": "object 4",
    },
    {
      "title": "object 5",
    },
    {
      "title": "object 6",
    },
    {
      "title": "object 7",
    },
    {
      "title": "object 8",
    },
    {
      "title": "object 9",
    },
    {
      "title": "object 10",
    },
    {
      "title": "object 11",
    },
    {
      "title": "object 12",
    },
    {
      "title": "object 13",
    },
    {
      "title": "object 14"
    },
    {
      "title": "object 15"
    }
  ];

  let start_at = 0;
  let cursor = 2; /* how much items to load on each click */
  let steps_size = cursor;
  let card_index = 1;

  $("#steps_size").text(steps_size);

  /* deafult cards */
  function load(){
    $.each(objects.slice(start_at, cursor), function(index, value){
      $('.cards').append('
' + value.title + '
');
    });/* end each */
    /* update cursors */
    start_at = start_at + steps_size;
    cursor = start_at + steps_size;

    /* if no more objects */
    if(start_at > objects.length){
      alert("list ends");
      $("#more").hide();
    }
    console.log("start_at: " + start_at);
    console.log("cursor: " + cursor);
  }

  load();

  $('.more').on('click', function () {
    $.each(objects.slice(start_at, cursor), function(index, value){
      $('.cards').append('
' + value.title + '
');
    });/* end each */
    /* update cursors */
    start_at = start_at + steps_size;
    cursor = start_at + steps_size;

    /* if no more objects */
    if(start_at > objects.length){
      alert("list ends");
      $("#more").hide();
    }
    console.log("start_at: " + start_at);
    console.log("cursor: " + cursor);
  });
});

  <button id="more" class="more btn btn-primary md">Load  more objects
</button>

A: You can try this. I hope the code is self explanatory.
Let me know in the comments for any query

var iteration = 1;
var itemsInIterations = 6;

    $('.more').on('click', function () {
        //Get the start index for this iteration  (It will be 0, 6, 12, 18....)
        const startFromIndex = (iteration - 1) * itemsInIterations;

        //Get the end index for this iteration (It will be 6, 12, 18 ....)
        const endToIndex = iteration * itemsInIterations;

        //Get a slice of objects for this iteration
        const iterationObjects = objects.slice(startFromIndex, endToIndex);

        $.each(iterationObjects, function(index, value){

            $('.cards').append('
' + '' + '

' + '

' + '' + '' + '
');
            $('.cards .card-' + index + " h4").html('
' + value.title + '
');
            $('.cards .card-' + index + " a").html('' + value.link + '');

            $('.cards .card-' + index + " p").html('
' + value.description + '
');

            $('.cards .card-' + index + " img").attr("src", value.img);
        });

        //Increment the iteration by 1 for next iteration
        iteration++;
    });


text:
Q: Set Theory : Proof regarding subsets and relative complement I'm trying to prove the following logical equivalency :
( A ⊂ B ) ≡  A \ B = ∅
My solution : If A ⊂ B, then x ∈ A → x ∈ B
Lets define the relative complement as a set A \ B  := { x ∣ x ∈ A and x ∉ B }
There is no x that fulfills this condition. Therefore ( A ⊂ B ) → A \ B = ∅. Now lets show that   ( A \ B = ∅ ) → ( A ⊂ B ). Lets prove this by contradiction. Assume that ( A \ B = ∅ ) is true. We can write this as a statement :
There is no  x  ∣ x ∈ A and x ∉ B
Now lets assume that the negation of ( A ⊂ B ) is true. This is written as :
∃ x ∈ A and x ∉ B.
This is clearly a contradiction, which means the implication is always true. We have now proven that ( A ⊂ B ) ≡  A \ B = ∅. Correct?

A:
Since this set is not defined for any $x \in A$, it means this set is always identical to the empty set $\emptyset$.

It doesn't really make sense to say the set $A\setminus B$ is not defined for any $x \in A$. I think what you mean to say is that the condition "$x \in A$ and $x \notin B$" is not satisifed for any $x$. Therefore no $x$ can be an element of $A \setminus B$.
Now all this shows is that $A \subset B \Rightarrow (A \setminus B = \emptyset)$. But you also need to show the other direction: start by supposing $A\setminus B = \emptyset$, and use this to show that $A \subset B$. Then you will have shown the equivalence between the two.


text:
Q: Let address link open hide section in JavaScript I am new in JS so my question is it possible if I have many sections and I can open them when click on button (they are display: none; by default and opens when click on menu button on same page). I need to create links that if someone enters in address box then that sections opens... but how to make that if its display: none; by address? Maybe i am wrong and you can suggest some better method ?

          Sākumlapa /
     Par Skolu /
     IEPIRKUMI

Uz doto momentu nav aktuālu iepirkumu!

function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}

A: You're making it complicated, because of it(instead of using if..else) there is a method for classList, which lets you toggle the class of the element you want. The method is toggle().
Later you can create a class named .show which will change the display of your element to block when the class is given to the element.
Reminder : Don't ever use var, use let & const which are the newest syntax. (ecma-script 6)

function myFunction() {
  const container = document.getElementById('sectionIepirkumi');

  container.classList.toggle('show');
};

document.querySelector('button').addEventListener('click', myFunction);
.show {
  display: block !important;
}
<button type='button'>Click</button>

          Sākumlapa /
     Par Skolu /
     IEPIRKUMI

Uz doto momentu nav aktuālu iepirkumu!


text:
Q: Numbering not every line with lineno How it is possible to number not every line with lineno?
For example only every fifth line.
There are no hints in the manual.

A: Page 2 of my copy of the manual mentions the modulo option: "Print line numbers only if they are multiples of five".
\documentclass{article}

\usepackage[modulo]{lineno}
\linenumbers

\usepackage{lipsum}

\begin{document}

\lipsum[1]

\end{document}


text:
Q: (Closed)WCF with Dictionary I found my mistake. I use NHibernate lazy loading. And serializer can't serialize RoleProxy.
How to get object with Dictionary field from WCF service?
When i try to do it, i get this exception:

The underlying connection was closed: The connection was closed
  unexpectedly.

Stack trace:

Server stack trace:     at
  System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
  webException, HttpWebRequest request, HttpAbortReason abortReason)
  at
  System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)    at
  System.ServiceModel.Channels.RequestChannel.Request(Message message,
  TimeSpan timeout)    at
  System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs)    at
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)    at
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
Exception rethrown at [0]:     at
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    at
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    at
  UserManagmentStudio.DataService.IDataService.GetUser()    at
  UserManagmentStudio.DataService.DataServiceClient.GetUser() in
  C:\Users\d.kolpakov\documents\visual studio
  2010\Projects\UserManagmentStudio\UserManagmentStudio\Service
  References\DataService\Reference.cs:line 64    at
  UserManagmentStudio.Controllers.UsersController.Index(UserFilter
  filter, String dataType) in C:\Users\d.kolpakov\documents\visual
  studio
  2010\Projects\UserManagmentStudio\UserManagmentStudio\Controllers\UsersController.cs:line
  29    at lambda_method(Closure , ControllerBase , Object[] )    at
  System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
  controller, Object[] parameters)    at
  System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
  controllerContext, IDictionary2 parameters)    at
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
  controllerContext, ActionDescriptor actionDescriptor, IDictionary2
  parameters)    at
  System.Web.Mvc.ControllerActionInvoker.<>c_DisplayClass15.b_12()
  at
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
  filter, ActionExecutingContext preContext, Func`1 continuation)

Service interface:
  [ServiceContract]
    public interface IDataService
    {
        [OperationContract]
        User GetUser();
    }

User.cs:
   [DataContract(IsReference = true)]
    public class User : IValidatableObject
    {
        [DataMember]
        private readonly IDictionary<Role,AccessLevel> roles = new Dictionary<Role,AccessLevel>();

        public virtual IDictionary<Role,AccessLevel> Roles
        {
            get { return roles; }
        }

.....

    }

Role.cs:
[DataContract(IsReference = true)]

       public class Role
        {
    private readonly IDictionary<User, AccessLevel> users = new Dictionary<User, AccessLevel>();

            [DataMember]
            public virtual Int32 Id { get; set; }

            [DataMember]
            public virtual String Name { get; set; }

            public virtual IDictionary<User,AccessLevel> Users
            {
                get { return users; }
            }
    }

AccessLevel.cs:
   [DataContract(IsReference = true)]
    public class AccessLevel
    {
        [DataMember]
        public virtual Int32 Id { get; set; }

        [DataMember]
        public virtual String Value { get; set; }
    }

A: Try changing the IDictionary to a read-write Dictionary property. In a data contract you have to specify an implementation, otherwise the deserializer doesn't know how to construct the object, I think

A: [DataContract]
    public class User : IValidatableObject
    {
        [DataMember]
        public Dictionary<Role,AccessLevel> Roles
        {
            get; set;
        }
    }

[DataContract]
public class Role
     {
        [DataMember]
        public Int32 Id { get; set; }

        [DataMember]
        public String Name { get; set; }

        [DataMember]
        public Dictionary<User,AccessLevel> Users
        {
           get;set;
       }
}

A: Read-only variables can not be passed to/form a service, as they are not serializable. so you should add a set for User.Roles property.


text:
Q: Use the type returned by a function as information Over time I become used to use the type of the returned value of a function as a piece of additional information.
For example:
A function that is supposed to return or an array if the arguments are correct and can find a result, can pass a specific enum when arguments are incorrect or the expected result cannot be found.
Then I can test the type to sort the behaviour of the receiving code.
I can't always use a typed function in the same way because the value that I reserve to explain what's wrong removes a possible valid result.
I can see some other benefits and the main is that testing the type of the returned value is a very separated operation from the normal flow of the code and it seems more methodical to me.
Also, the segmentation now possible increases the flexibility of the code.
So, I'm quite sure that I write less code and, once one gets used, the code is readable.

*

*Is it acceptable?

*I'm going to work with an agency on some projects, can I ask if I can use this approach or is it against the best practices?

A: In strongly/statically typed languages, this is generally discouraged, as the static type information is used to determine the legal operations on the results, with opportunities to do type inference and to eliminate certain runtime checks on the returned values.
Dynamically typed languages (such as Python or Smalltalk) allow returning different types to express exceptional conditions, but this may lead to nasty bugs when a caller forgets to check the return value and treats it as the wrong type, so this style is generally frowned upon.
Rust (just an example that I've made myself familiar with recently) has wrappers like Option<> and Result<> which allow programmers to express the notion of "no result" or "error" in a type-safe way. The compiler can verify that you always handle both cases when dealing with values of these types, and that in each branch you only deal with the correct value.

A: The problem that you have is:

*

*You do not ensure a proper separation of concerns, since you combine error notification (exceptional situation) with returning a result.

*It's not fully in line with the principle of least astonishment (POLA):  if the user is used to get a result, it might come as a surprise when the result is very different from expectations.  If the types differ only rarely,  it's a serious source of errors.

*It's not a common language idiom.   In many language,  you may return a nil or a nullptr or something similar to express the absence of result.  You could argue that this null value is also of a different type, since it usually cannot be processed the same way. But such idioms are in line with POLA when it's a common idiom.

*Lastly,  one could claim that this is a kind of infringement of the interface segregation principle, since you require to using context to depend on more return types than strictly needed.

For all these reasons I'd advise against it.

A: There are some communities where this or similar things are fairly common. For example, in C, many functions that can normally only return positive integers will return an error code as a negative integer in case of failure. For example, printf returns the total number of characters written (which can never be negative, obviously). However, its return type is not typed as unsigned int but as int, and it returns a negative number in case of failure.
I am pretty sure I have seen the exact thing you describe done in some dynamic language, but I can't come up with an example right now.
However, there are almost always better alternatives.
If your language has something like conditions (CommonLisp, Dylan, Clojure, …) or exceptions (ECMAScript, PHP, Python, Ruby, …), then you can use those.
If your language supports multiple return values, then you can use an extra return value for the error. For example, in Go, it is idiomatic to return the error as an extra return value:
func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // implementation
}

And the caller would use it like this:
n, err := Sqrt(-1)
if err != nil {
    log.Fatal(err)
}
// Do something with `n`

In languages with lightweight syntax for tuples or records, and destructuring assignment, you can easily "fake" support for multiple return values (e.g. TypeScript):
function sqrt(n: number): { result?: number, error?: string } {
  if (n < 0) {
    return { error: `Argument must be non-negative but you passed ${n}!` };
  }
  // implementation
}

const { result, error } = sqrt(-1);
if (error) {
  // handle error
}

In more verbose languages like Java, you can still build a simple result type, although it starts to get a little wordy:
record DoubleResult(double result, Throwable error);

DoubleResult sqrt(double d) {
    if (d < 0d) {
        return new DoubleResult(0d, new ArgumentException("Bla bla"));
    }
    // implementation
}

var dr = sqrt(-1d);

if (dr.error != null) {
    // handle error
}

However, my personal favorite is the following: If you are using a statically typed language with parametric polymorphism, you can build an Error type, something like this:
sealed trait Try[+T] {
  val isSuccess: Boolean
  val isFailure: Boolean

  // @returns the result value if successful or the default value if failed
  def getOrElse[U >: T](default: => U): U

  // execute `f` with the result if success
  def foreach[U](f: T => U): Unit

  // transform result using `f` if success
  def map[U](f: T => U): Try[U]

  // transform result using `f` if failure
  def recover[U >: T](f: Throwable => U): Try[U]
}

final case class Failure[+T](exception: Throwable) extends Try[T] {
  override val isSuccess = false
  override val isFailure = true

  override def getOrElse[U >: T](default: => U) = default
  override def foreach[U](f: T => U) = ()
  override def map[U](f: T => U) = this.asInstanceOf[Failure[U]]

  override def recover[U >: T](f: Throwable => U) = Success(f(exception))
}

final case class Success[+T](value: T) extends Try[T] {
  override val isSuccess = true
  override val isFailure = false

  override def getOrElse[U >: T](default: => U) = value
  override def foreach[U](f: T => U) = f(value)
  override def map[U](f: T => U) = Success[U](f(value))

  override def recover[U >: T](f: Throwable => U) = this
}

This is an Error type which you might typically find in a functional language, but there is nothing inherently tied to functional programming about it. In fact, the sketch above is completely OO, using subtyping and method overriding.
The idea behind this type is that it has an abstract superclass that defines operations both for processing the result if it exists, and for handling the failure if it happens. Then, it has two concrete subclasses, one for the successful case, and one for the failure case.
And we are using simple method overriding, so that the Success class overrides or implements all the failure handling methods as no-ops, and the Failure class handles all the success handling methods as no-ops.
The real trick though, is that this class implements also a collection-style interface: it has foreach and map, etc. In the success case, it behaves like a collection with one element, and in the failure case, it behaves like an empty collection.
So, in many cases, I don't even need to check whether it was successful or not! If I want to transform the result, I can simply call map, because map on an empty collection is a no-op.
We can implement additional collection methods, I just didn't show them in the sketch. E.g. flatten, which will flatten a nested tower of Trys into a single level of Try which is either the last Error if there was at least one, or a Success containing the value. Similarly, we can implement flatMap.
I can pass this object on to a different method, and that method can simply call map as well. Only the method that actually wants to handle the error and get rid of the Try wrapper around the value needs to actually know about the error.
The fact that this is essentially a collection, means that all the things that we know about collections, all the methods in the standard library that deal with collections, can be applied to this. We can simply transparently treat it as a collection and it will automatically "do the right thing". We only need to care about the error at the place where we actually care about the error.
I have avoided the "M" word for now, but you might have already spotted that this is a monad (well, not quite, I left out the flatMap method in the sketch). Several languages nowadays have special syntax sugar for monadic operations, e.g. C#, Visual Basic.NET, Scala, and Haskell. In those languages, dealing with Errors using an Error Monad is very simple.
Such an error type is nowadays built into the standard libraries of many languages. For example, Scala has scala.util.Try, Rust has std::result::Result, Elm has Result, and so on.
These work best in languages that have monad comprehensions and pattern matching, but those features are not necessary. In some cases (e.g. Rust) there is special syntax for dealing with result types.


text:
Q: Oracle asm disk string profile string vs param string Oracle Database ASM disk string profile string vs param string ?
ASMCMD [+] > dsget
profile: /dev/disk*
parameter: /dev/disk*

Do we need to set both of them ?
what is consequence of setting one in these two ?
Thanks

A: asm_diskstring can be set in the ASM parameterfile and in the GPnP profile as well. Grid Infrastructure needs to know where to search for ASM disks before starting ASM and reading the ASM parameterfile, the GPnP profile makes that possible.
dsget
dsget
        Retrieves the discovery diskstring value that is
        used by the Oracle ASM Instance and its clients

Synopsis
        dsget [ --normal | --profile [ -f ] | --parameter ]

Description
        The options for the dsget command are described below.

        --normal        - Retrieves the discovery string from the Grid Plug
                          and Play (GPnP) profile and the one that is set in
                          the Oracle ASM instance. It returns one row each for
                          the profile and parameter setting. This is the
                          default setting.

        --parameter     - Retrieves the ASM_DISKSTRING parameter setting of
                          the Oracle ASM instance.

        --profile       - Retrieves the discovery string from the GPnP
                          profile.

        -f              - If -f is specified, retrieves the discovery string
                          from the local GPnP profile.  This parameter
                          can only be specified if --profile is specified.

Examples
        The following example uses dsget to retrieve the current discovery
        diskstring value from the GPnP profile and the ASM_DISKSTRING parameter.

        ASMCMD [+] > dsget
        profile: /devices/disk*
        parameter: /devices/disk*


text:
Q: Modify PHP session using session id If a session id is stored can it be used to alter session data such as an array variable?
I am working on a project for a login system in PHP where the login authentication comes from an out-of-band source (mobile app or browser extension).
The browser page will use JavaScript to continuously request the login state from the server.  The user will scan a QR Code on the page for example, and their phone will post their authentication by API to the server.
I would then like to alter the $_SESSION data associated with the session on the page that was issued with that specific QR Code.  I can know the session id which issued that specific QR Code which data was returned by the mobile QR Code scan, but can I use the session id to modify the session data, so as to set the SESSION state to logged in?
I have looked through the PHP manual for a function that would allow this to modify another session but didn't find anything. (https://www.php.net/manual/en/ref.session.php)

A: in view set textbox value with $_SESSION id,
and when action, update data SESSION with id to database.

A: What you do is you set your session_id to the id data you want to edit then change the session values.
 session_id('the id you have');
    session_start();
    $_SESSION['anydata'] = 'whatever you want';


text:
Q: naming objects by variables I am in a situation that I need to make objects in runtime that are named by value of a string, but I can't do that:
cin>>input;
className "input"= new className;

How can I do that?

I think it is possible to achieve by using maps. Is it true?

A: As you said, you can achieve your goal by using std::map (or std::unordered_map)
map<string, className*> aMap;//map a string to a className pointer/address
cin>>input;
aMap[input] = new className; //input is mapped to a className pointer

Then you can treat aMap[input] as a className*. e.g.
To call a className method, you can:
aMap[input]->aClassNameMethod();

A: The object oriented way would be to make name a member of that class and use the input to construct the class.
#include <string>
#include <iostream>

class Foo
{
    std::string myName;
public:
    // Constructor assigning name to myName.
    Foo(const std::string name) : myName(name) {}

    std::string GetMyName() const
    {
        return myName;
    }
};

int main()
{
    std::string input;
    std::cin >> input;
    Foo f(input);
    std::cout << f.GetMyName();
}

Also read about new in C++: Why should C++ programmers minimize use of 'new'?


text:
Q: tsc with tsconfig does nothing. What am I doing wrong? My directory has 2 files:  a tsconfig.json with simply {} and a hello.ts with a line that says console.log('help!!');.
When I run tsc hello I get the additional hello.js as expected.
If I delete hello.js and run tsc intending to pick up my configuration I get nothing. No error message, no hello.js.  I'm sure I'm missing something easy!
NOTE: My hypersimple tsconfig is just for purposes of this discussion. I have tried several options including the simple one created with tsc --init. I don't want to include files specifically but have tsc pick up all the files in my folder as documented.


text:
Q: USB transfers very slow (kB/s range only) However When plugging my USB 2.0 flash drive into the USB 3.0 port of one of my laptops running W8 Im only getting around 2.5 kB/s! sometimes if its a larger transfer it will trail of to nothing at all!!
The strange thing is when I plug it into a W7 laptop's USB 2.0 port transfers run at expected speeds (i.e. I dont notice it being overly slow but I didnt look at the numbers).
Neither of the laptops have the USB performance set for speed rather than safe removal, nor do I want them to be as I have found the gain in speed to be minimal yet the payoff in damaged drives does indeed rise quite a lot.
Even when it is transferring, looking at the windows transfer visualisation, it shows continues peaks (the peaks still only being a few kB/s) and drop offs instead of a rise and then a continuous(-ish) level till a final fall-off that one would expect.
Neither disk manager nor device manager (or event logs) show any issue with the drive r anything else.
Sometimes the speed increases if I push down on the end of the protruding USB drive, but other times that seems to slow it... A current transfer of mainly .c files is running at only 637 bytes/s!
Any knowledge on how to fix this? Thanks
P.S. Yes I have looked at a lot of the other Q's regarding slow USB transfers - they all (as far as I could make out) concern minor increases in the MB/s range.

A: You also have to take into account the nature of the data you are writing.  Writes to a flash-based disk have (at least) two steps: 1) Receiving the data to the drive's buffer RAM (limited by bus speed) and 2) Writing the data from RAM to FLASH (limited by write cycle time).
Usually receiving the data is very fast unless your machine or USB bus is very busy with other things -- MB/Sec is typically very large.   However, actually writing each transfer inside the chip takes a fixed amount of time, so if you are writing thousands of small files vs one large file, the large file transfer is largely bound by bus speed and drive RAM buffer size, but the small files will be largely bound by flash cycle time.
As a test, try writing, say, 1GB of a large file (say, a zip of some large folder) vs the same amount of data in small files.  You will likely see a huge difference.


text:
Q: How to find driver id by i2cget I Get the list of detected peripherals on the specific I2C - 4:
# i2cdetect -y 4

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:                         -- -- -- -- -- -- -- --
10: UU -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: 70 71 -- -- -- -- -- --

How can I find drivers id about devices on this bus (i2c-4)?


text:
Q: I want to rename the classname after compiling a .java file in cmd Is there a command to do this? For example, in C#, you can rename the .exe file after compiling by using the /out: [name-of-file].exe.

A: The name of a `.java` file must be the same as the name of the public class defined inside of it.
Once a `.java` is compiled into a `.class`, the name of the class file must also remain the same as the public class's name. This cannot be changed without renaming the class in the `.java`, renaming the `.java` to be the same as the new class name, and then recompiling into a `.class`.
C# does not have this restriction, and allows you to name your `.cs` whatever you like, regardless of the name of the class defined inside of it.


text:
Q: type inference and string literals, how to do it? How do I get this to compile?
Code
object Playground2 {

  trait Client[S,A] {
    def wrap[S,A](v: A): (S,A)
  }

  class TestClient extends Client[String, Int] {
    override def wrap[String,Int](v: Int): (String, Int) = ("cache 2.00", v)
  }
}

Error type mismatch;  found   : java.lang.String("cache 2.00")  required: String

A: Here's a version of the code that compiles:
object Playground2 {

  trait Client[S,A] {
    def wrap(v: A): (S,A)
  }

  class TestClient extends Client[String, Int] {
    override def wrap(v: Int) = ("cache 2.00", v)
  }
}

You duplicated the types again in the wrap function and you did not need to as they were already defined on the trait itself.


text:
Q: Take maps Lat/Long on centre point of screen Does anyone know how to take map coordinates from centre point of the screen?
There are several different answers but they're all for Google Maps -
Flutter: how to get location coordinates of point in the center of screen
I am using HERE maps.
Thank you

A: As indicated in the user guide simply get it by calling:
hereMapController.camera.state.targetCoordinates

In HERE's terminology the target specifies the point at which the camera looks. By default, it's looking at the center of the map view, unless it was changed with a principal point.
When the map is panned or moved programmatically, the camera still looks at the center of the map view, so the values are updated each time.


text:
Q: Поток с независимой скоростью выполения от программы Создаю поток CreateThread и через него обновляю содержимое элемента в программе. Но скорость обновление очень мала, 1 раз в 15 секунд. Как сделать поток не зависимым от программы?
По просьбам желающих подробней все опишу:
Если создать поток он будет выводить сообщение с большой скоростью таким образом:
char *dwThrdParam = "Hello!";
    DWORD dwThreadId;
    HANDLE hThread = CreateThread(0, 0, UpdateList, dwThrdParam, 0, &dwThreadId);
    .......
DWORD WINAPI UpdateList(LPVOID lParam)
{
int c = 0;
for (;;)
{
        UpdateProcessList(listView, Process);

        char b[20];
        sprintf_s(b, "%s, %d\n",(char*)lParam, c);
        OutputDebugString(b);
        c++;
}
return 0;
}

Но когда в цикле не потока!!! А программы я начинаю писать код, который уменьшает количество проходов цикла с нескольких тысяч до 30 раз в секунду, то поток начинает выводить сообщение раз в 15 секунд. Вот код цикла программы:
VSync.Begin(30);
        while (globalRunning)
        {
            if (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
            {
                TranslateMessage(&message);
                DispatchMessage(&message);
            }

            VSync.End(false);
        }

VSync основан на sleep. Интересная особенность если начать перемещать окно за заголовок, то скорость потока увеличивается во много раз
Для тех кто уверен что в расчете дело:
char buffer[256];
LVITEM lvi;
memset(&lvi, 0, sizeof(lvi));
lvi.mask = LVIF_TEXT | LVIF_TEXT;

for (int i = 0; i < 10; i++)
{
        lvi.iItem = i;

        lvi.iSubItem = 0;
        ListView_InsertItem(listView, &lvi);
        sprintf_s(buffer, "%d", i);
        ListView_SetItemText(listView, currentItem, lvi.iSubItem, buffer);
}


text:
Q: StringIndexOutOfBoundsException when converting char[] read from BufferedReader in Android I'm trying to read JSON-Strings through a socket connection in an Android app, but suddenly started getting StringIndexOutOfBoundsExceptions that I can't explain(blocked out some identifiers in the package name):
java.lang.StringIndexOutOfBoundsException: length=10000; regionStart=0; regionLength=-1
    at java.lang.StringFactory.newStringFromChars(StringFactory.java:218)
    at **.***********.SocketHandler.listenForMessages(SocketHandler.java:48)

where (starting at line 45) SocketHandler.listenForMessages() reads
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
char[] buffer = new char[READ_BUFFER];
int messageLength = reader.read(buffer, 0, READ_BUFFER);
String message = new String(buffer, 0, messageLength);

I haven't touched that part of the code - which worked without problems a few weeks ago - when I suddenly got this Exception even when upping the READ_BUFFER to way bigger than the received messages should be (10k here).
The indicators
length=10000; regionStart=0; regionLength=-1

make me assume the problem stems from reading an empty message, but I can't figure out why the problem didn't arise sooner then. Any help?

A: Try replacing this:
int messageLength = reader.read(buffer, 0, READ_BUFFER);

With this:
int messageLength = reader.read(buffer, 0, buffer.Length);

A: regionLength=-1

I think you are hitting an end of file.

Returns:
      The number of characters read, or -1 if the end of the stream has been reached

The docs


text:
Q: Multiple queries into one query I am trying to combine multiple queries into one. Any one have any ideas?
SELECT In_year, count(In_year) AS Num_Of_Year
FROM INTERNSHIP
GROUP BY In_year;
SELECT In_qtr, count(In_qtr) AS Num_Of_Qtr
FROM INTERNSHIP
GROUP BY In_Qtr;
SELECT In_location, count(In_location) AS Num_Of_Location
FROM INTERNSHIP
GROUP BY In_location;
If I run each of these queries by themselves, I get what I am looking for in the result.  My problem is I cannot figure out how to combine these 3 queries into 1, I tried to combing them, but ended up getting the wrong output.  Thanks!

A: Maybe the UNION clause and organizing it a bit can do the trick:
SELECT 'Year' As Topic, In_year As Value, count(In_year) AS Count
FROM INTERNSHIP
GROUP BY In_year

UNION ALL

SELECT 'Qtr' As Topic, In_qtr As Value, count(In_qtr) AS Count
FROM INTERNSHIP
GROUP BY In_Qtr

UNION ALL

SELECT 'Location' As Topic, In_location As Value, count(In_location) AS Count
FROM INTERNSHIP
GROUP BY In_location;

That's the only way to show it in a single query, because the three SELECT will have different number of rows, so you can't add the colums in natural form.

A: We can use the INTERNSHIP table as a driving list to connect the other "group by" SQLs:
select
   t1.In_year, y.Num_Of_Year,
   t1.In_qtr, q.Num_Of_Qtr,
   t1.In_location, l.Num_Of_Location
FROM
  (select distinct In_year, In_qtr, In_location from INTERNSHIP)  t1
   join (SELECT In_year, count(In_year) AS Num_Of_Year FROM INTERNSHIP GROUP BY In_year) y on t1.In_year = y.In_year
   join (SELECT In_qtr, count(In_qtr) AS Num_Of_Qtr FROM INTERNSHIP GROUP BY In_Qtr) q on t1.In_Qtr = q.In_Qtr
   join (SELECT In_location, count(In_location) AS Num_Of_Location FROM INTERNSHIP GROUP BY In_location) l on t1.In_location = l.In_location


text:
Q: Error while using @angular compiler in Angular 5 and AOT-Build i am using the Angular Compiler to compile components in runtime. This Code works fine, but if I want to use AOT-Prerendering the Component wont work, because Angular does not load the Compiler in AOT-Build.
I've read about some Workarounds that wont Work in Angular5+ anymore.
Do you have any solutions for this problem?
Best Regards

    export class RuntimeCompilerComponent {
      template: string = "";
      @ViewChild('dynamicComponent', { read: ViewContainerRef }) container: ViewContainerRef;
      constructor(private compiler: Compiler) { }

      //Ruft die addComponent Methode auf
      createComponent() {
        this.addComponent(this.template, null);
      }

      // Komponente wird dynamisch erzeugt und geladen
      // Sollten sich die properties ändern muss ggf. die Changedetection manuell aufgerufen werden.
      private addComponent(template: string, properties: any = {}) {
        @Component({ template })
        class TemplateComponent { }
        @NgModule({
          imports: [
            AppModule,
            CommonModule,
            ReactiveFormsModule,
            FormsModule,
            BrowserModule,
          ], declarations: [TemplateComponent]
        })
        class TemplateModule { }
        const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
        const factory = mod.componentFactories.find((comp) =>
          comp.componentType === TemplateComponent
        );
        const component = this.container.createComponent(factory);
        Object.assign(component.instance, properties);
      }
    }

A: You can make this work with a few tricks. I ran into the same problem last year, and was able to find a fix. I was using dynamically generated angular components in my style-guide. Here's a working example, which works with AOT compilation in Angular 7:
https://github.com/johncrim/angular-dynamic-styleguide
The README.md for that project provides some additional info on the problems I came up against and how I figured out the fixes.


text:
Q: MySQL Secondary Indexes If I'm trying to increase the performance of a query that uses 4 different columns from a specific table, should I create 4 different indexes (one with each column individually) or should I create 1 index with all columns included?

A: One index with all 4 values is by my experience the fastest. If you use a where, try to put the columns in an order that makes it useful for the where.

A: An index with all four columns; the columns used in the WHERE should go first, and those for which you do == compare should go first of all.
Sometimes, giving priority to integer columns gives better results; YMMV.
So for example,
 SELECT title, count(*) FROM table WHERE class = 'post' AND topic_id = 17
    AND date > @@BeginDate and date < @@EndDate;

would have an index on: topic_id, post, date, and title, in this order.
The "title" in the index is only used so that the DB may find the value of "title" for those records matching the query, without the extra access to the data table.
The more balanced the distribution of the records on the first fields, the best results you will have (in this example, say 10% of the rows have topic_id = 17, you would discard the other 90% without ever having to run a string comparison with 'post' -- not that string comparisons are particularly costly. Depending on the data, you might find it better to index date first and post later, or even use date first as a MySQL PARTITION.

A: Single index is usually more effective than index merge, so if you have condition like f1 = 1 AND f2 = 2 AND f3 = 3 AND f4 = 4 single index would right decision.
To achieve best performance enumerate index fields in descending order of cardinality (count of distinct values), this will help to reduce analyzed rows count.
Index of less than 4 fields can be more effective, as it requires less memory.
http://www.mysqlperformanceblog.com/2008/08/22/multiple-column-index-vs-multiple-indexes/