I cannot retrieve my current longitude and latitude in google maps

Question: I am using the following code to get the lat and lang of my current location but it gives me null value in CameraPosition.. any idea why ?
   private void moveMapToMyLocation() {

    LocationManager locMan = (LocationManager) MapsActivity.this.getSystemService(Context.LOCATION_SERVICE);

    Criteria crit = new Criteria();

    Location loc = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    CameraPosition camPos = new CameraPosition.Builder()

            .target(new LatLng(loc.getLatitude(), loc.getLongitude()))

            .zoom(12.8f)

            .build();

    CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);

   mMap.moveCamera(camUpdate);

}

Comment: Show your full code. And make sure GPS is `Enable` on your device.
Answer: Use this method this will be work fine in your case
private void initMap() {

        try {
            // Loading map
            initilizeMap();

            // Changing map type
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setZoomControlsEnabled(false);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);
            googleMap.getUiSettings().setCompassEnabled(true);
            googleMap.getUiSettings().setRotateGesturesEnabled(true);
            googleMap.getUiSettings().setZoomGesturesEnabled(true);

            if (locationManager == null) {
                locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            }
            if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (isGPSEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
                } else if (isNetworkProviderEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
                }
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                } else {
                    if (isNetworkProviderEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.NETWORK_PROVIDER;
                    } else if (isGPSEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.GPS_PROVIDER;
                    } else {

                        alertDialog = Util.showOkDialog(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Env.currentActivity != null) {
                                    if (Env.currentActivity instanceof LocationActivity) {
                                        try {
                                            gotoSettings();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                                if (alertDialog != null) {
                                    alertDialog.dismiss();
                                    alertDialog = null;
                                }

                            }
                        }, this.getResources().getString(R.string.location_service_validation));

                    }

                    location = locationManager.getLastKnownLocation(provider_info);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }

                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(latitude, longitude))
                        .title(getFullAddressLine(this));
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

                googleMap.addMarker(marker);
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(latitude,
                                longitude)).zoom(15).build();
                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Answer: Try this probably this should work for you.
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (loc != null) {
            onLocationChanged(loc);
        } else {
            loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (loc != null)
                onLocationChanged(loc);
        }

onLocationChanged will be called when the location has changed.And for this you will have to implement LocationListener(Interface).
Once you have implemented the LocationListener, you will get an override method called onLocationChanged.
Through this method you will get latitude and longitude.
@Override
public void onLocationChanged(Location location) {
    double dLatitude = location.getLatitude();
    double dLongitude = location.getLongitude();
    LatLng currentLatLng = new LatLng(dLatitude, dLongitude);

}


Como escutar mudanças reativas em dois controles de formulário ao mesmo tempo no angular

Question: Estou com um pequeno problema no angular.
Ao digitar em um campo de formulário, eu estou inserindo mudanças em outro campo. Porém quando tendo usar em dois formulários ao mesmo tempo o console mostra o seguinte erro:
core.mjs:6461 ERROR RangeError: Maximum call stack size exceeded
Meu código:
ngOnChanges(): void {
      this.createForm();
      this.setProposedPercentage();
      this.setProposedPercentageByNewSalary()

  }

createForm(): void {
    this.myForm= this.formBuilder.group({
      newSalary: [0],
      currentSalary: [0],
      proposedPercentage: [0],
    });
  }

calculateProposedPercentage(newSalary: number, currentSalary:number): void {
    let value = newSalary - currentSalary;
    let result = (value / currentSalary) *100;
    this.myform.get('proposedPercentage').setValue(result);
  }

  calculateNewSalaryByProposedPercentage(currentSalary:number, proposedPercentage: number,  newSalary: number): void {
    let value = currentSalary * (proposedPercentage/100);
    let result = value + newSalary;
    this.myform.get('newSalary').setValue(result);
  }

  setProposedPercentage(): void {
    merge(
      this.myform.get('newSalary').valueChanges,
    ).pipe(takeUntil(this.unsubscribeNotifier)).subscribe(
      () => {
        const currentSalary = this.myForm.get('currentSalary').value;
        const newSalary = this.myForm.get('newSalary').value;

        if (currentSalary && newSalary) {
          this.calculateProposedPercentage(newSalary, currentSalary);
        }
      }
    );
  }

  setProposedPercentageByNewSalary(): void {
   merge(
      this.myform.get('proposedPercentage').valueChanges,
    ).pipe(takeUntil(this.unsubscribeNotifier)).subscribe(
      () => {
        const currentSalary = this.myForm.get('currentSalary').value;
        const newSalary = this.myForm.get('newSalary').value;
        const proposedPercentage = this.myForm.get('proposedPercentage').value;

        if(currentSalary){
          this.calculateNewSalaryByProposedPercentage(currentSalary, proposedPercentage, newSalary)
        }
      }
    );
  }

Comment: Só corrigindo pessoal é em dois controles de formulário ao mesmo tempo e não em dois formulários.
Answer: Consegui encontrar uma solução para o problema:
Adicionei o operador distinctUntilChanged() na chamada reativa e adicionei uma propriedade no resultado do formulário:
O código ficou assim:
calculateProposedPercentage(newSalary: number, currentSalary:number): void {
    let value = newSalary - currentSalary;
    let result = (value / currentSalary) *100;
    this.myform.get('proposedPercentage').setValue(result, {emitEvent : false});
  }

  calculateNewSalaryByProposedPercentage(currentSalary:number, proposedPercentage: number,  newSalary: number): void {
    let value = currentSalary * (proposedPercentage/100);
    let result = value + newSalary;
    this.myform.get('newSalary').setValue(result, {emitEvent : false});
  }

  setProposedPercentage(): void {
    merge(
      this.myform.get('newSalary').valueChanges,
    ).pipe(distinctUntilChanged()).subscribe(
      () => {
        const currentSalary = this.myForm.get('currentSalary').value;
        const newSalary = this.myForm.get('newSalary').value;

        if (currentSalary && newSalary) {
          this.calculateProposedPercentage(newSalary, currentSalary);
        }
      }
    );
  }

  setProposedPercentageByNewSalary(): void {
   merge(
      this.myform.get('proposedPercentage').valueChanges,
    ).pipe(distinctUntilChanged()).subscribe(
      () => {
        const currentSalary = this.myForm.get('currentSalary').value;
        const newSalary = this.myForm.get('newSalary').value;
        const proposedPercentage = this.myForm.get('proposedPercentage').value;

        if(currentSalary){
          this.calculateNewSalaryByProposedPercentage(currentSalary, proposedPercentage, newSalary)
        }
      }
    );
  }

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Stuggling to understand ideal powers

Question: In my current algebraic number theory course we have defined the multiplication of 2 ideals as the smallest ideal containing all products of elements of both,
[i.e: let I and J be ideals of a ring R, then
IJ:={$\sum_1^k a_ib_i : a_i\in I , b_i\in J$} where k depends on R ]
we haven't however, formally defined ideal powers, by which I mean ideals of the form $I^x$ where x is an integer.
However, using the first, informal definition, it seems to me that all products of elements from I will just again form I
i.e. using the formal definition, and taking x = 2 I find that
$I^2$ = II = {$\sum_i^k a_ib_i : a_i\in I , b_i\in I$} = {$\sum_1^k c_i : c_i\in I$} = {$d : d\in I$} = I
and clearly extending this definition to higher powers results in the same thing?
Thanks for any clarification!
Comment: The equality between the first and the second line is not true in general. Not every element in $I$ can be written as a product of two elements in $I$. For example, the element $2$ in the ideal $2\Bbb Z$ of $\Bbb Z$ cannot be written as a product of two elements in $2\Bbb Z$. So the transition from the first to the second line is "is a subset of", which can be proper in some cases.
Comment: thank you! sorry I was still in the editing process before posting, but I assume you mean $I^2$ =/= $II$ ? and if so, do you know of a recognized definition of $I^2$ or is this something specific to my course? thanks again
Comment: $I^2$ is precisely $I\cdot I$. My point is that $I^2$ contains (sums of) products of elements of $I$, which may be a proper subset of $I$. Now that you have changed the formatting, the crucial point is the third equality sign. All the rest is fine.
Comment: got you, thanks so much, you are a star!
Answer: The third equality sign in your chain of equalities is, in fact, only $\subseteq$.
There is no reason to expect that every sum of elements in $I$ can be expressed as a sum of products of two elements of $I$.
To pick an analogy from group theory and sidestep the added complexity of the sums needed for products of ideals: for an abelian group $G$ (say, for example, the multiplicative group of positive rationals) the subset $H=\{x^2\mid x\in G\}$ turns out to be a subgroup of $G$. But, of course, not every rational is the square of a rational, so $H$ is a proper subgroup of $G$.
It's simple to give examples of ideals to convince you of the inequality too, and the one given by zarathustra in the comments is hard to improve upon:  $I=2\mathbb Z\lhd \mathbb Z$ is an ideal, and every product of two elements in $I$ is divisible by $4$, so $I^2\neq I$.

Stuggling to understand ideal powers


Does this variant on Rolle's theorem have a name?

Question: The following seems to be true:

Suppose $f : (a,b) \rightarrow \mathbb{R}$ is continuously differentiable. Then $$|x \in (a,b):f(x) = 0| \leq |x\in (a,b):f'(x) = 0|+1.$$
(By $|x \in X : P|$, I just mean the number of $x \in X$ satisfying $P$. This can be viewed as shorthand for the more long-winded $|\{x \in X : P\}|$.)

I'm having trouble formalizing the details, but the proof is basically by Rolle's theorem. Since $f$ is continuous, there are two cases:

The zeroes of $f$ are isolated from each other.
There exists a non-empty open interval on which $f$ is zero.

In the second case, both the LHS and RHS are $|\mathbb{R}|$, so we're done. So assume the zeros of $f$ are isolated from each other. Then we repeatedly apply Rolle's theorem to get a stationary point of $f$ for each root of $f$ beyond the first. That's the idea.
Anyway, just wondering if this result has a name? It's basically the same as Rolle's theorem, but perhaps bit easier for young people to understand and use. For instance, suppose we wish to prove that $\sqrt{2}$ refers to exactly one real number. Define $f(x)=x^2-2.$ We want to show that $f$ has precisely one root in $(0,\infty)$. We get a lower bound on the cardinality its set of roots by computing $f(0) = -2$ and $f(2) = 2$, hence by IVT, we have:
$$1 \leq |x \in (0,\infty) : x^2 -2 = 0|$$
For an upper bound, use the above theorem to get
$$|x \in (0,\infty) : x^2 -2 = 0| \leq |x \in (0,\infty) : 2x = 0|+1 = 0+1 = 1$$
Ergo:
$$|x \in (0,\infty) : x^2 = 2| = 1$$
Comment: You're wrong about the second case, by the way, but I think only for trivial reaosns: the LHS and RHS should be of continuum size in that example. You can have countably many zeroes - e.g. some kind of variant of $\sin$ on $(0,1)$.
Comment: 'Twas done for!
Comment: Goblin's theorem? ;o)
Comment: @Bernard you've made me smile :)
Comment: @goblin: (+1) for the nice question, especially for the long-winded explanation, to write a not so long-winded expression. :-)
Answer: This variant is stated as exercice V.1.12 in the book Problems and Theorems in Analysis (Tome 2) by Polya and Szego, and is there an anonymous early consequence of Rolle's theorem. So I don't think it has a well-known name.
You can state it as
$$
Z(f) \le Z(f')+1,
$$
where $Z$ gives the number of zeros of a function.
Note. Pick up a copy of Problems and Theorems in Analysis if you can. It's an accessible read and the exercices start easy in each section.
Answer: You reach a wrong conclusion. A function can be continuously differentiable and have infinitely many zeros in an open interval, without being constant in any subinterval.
Consider
$$
f(x)=\begin{cases}
0 & \text{if $x=0$} \\[6px]
x^3\sin\dfrac{1}{x} & \text{if $x\ne0$}
\end{cases}
$$
Then $f$ is everywhere differentiable and
$$
f'(x)=\begin{cases}
0 & \text{if $x=0$} \\[6px]
3x^2\sin\dfrac{1}{x}-x\cos\dfrac{1}{x} & \text{if $x\ne0$}
\end{cases}
$$
which is continuous. On the other hand, there is no interval where $f$ is constant.
If the set $Z(f)$ of zeros of $f$ is finite, say $Z(f)=\{x_0,x_1,\dots,x_n\}$, we can define $\varphi\colon Z(f)\setminus\{x_0\}\to Z(f')$ by assigning to $x_i$ an arbitrarily chosen zero of $f'$ in the interval $(x_{i-1},x_i)$, whose existence is guaranteed by Rolle's theorem. The choice can be made canonical by choosing the leftmost point of absolute maximum in $(x_{i-1},x_i)$ if $f$ assumes positive values in the interval, the leftmost point of absolute minimum otherwise (note that $f$ cannot be constant over the subinterval).
If $Z(f)$ is infinite, the situation is hairier. In the case it is countable, the set contains either an increasing or a decreasing sequence. Rolle's theorem can be easily applied in the same way as before.
What about the uncountable case?


Left angle bracket removed when sending a SOAP message from Spring-WS client on Java7 to server on Java 6

Question: This has been really frustrating for me so I'll try explain what I know and don't now. Please make sure to see my updates at the bottom of the post.
First, we have a war that uses Spring-WS to process messages. We also have a client that uses WebServiceTemplate to send messages. We deploy on Tomcat 7.
In our current dev environment, the Tomcat 7 server is using JRE 6u24. Locally, I'm running the same version when I use the client to send a SOAP message. Everything works as expected.
When I make my local JRE 7u04, I get a 500 response and the server sees the following error:
[2012-05-05 20:19:13,179] DEBUG - org.springframework.web.servlet.FrameworkServlet.processRequest(671) | Could not complete request
org.springframework.ws.soap.saaj.SaajSoapEnvelopeException: Could not access envelope: Unable to create envelope from given source: ; nested exception is com.sun.xml.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source:
        at org.springframework.ws.soap.saaj.SaajSoapMessage.getSaajVersion(SaajSoapMessage.java:260)
        at org.springframework.ws.soap.saaj.SaajSoapMessage.getImplementation(SaajSoapMessage.java:342)
        at org.springframework.ws.soap.saaj.SaajSoapMessage.<init>(SaajSoapMessage.java:117)
        at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:184)
        at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:58)
        at org.springframework.ws.transport.AbstractWebServiceConnection.receive(AbstractWebServiceConnection.java:90)
        at org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:86)
        at org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:57)
        at org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:222)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
        at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:195)
        at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:159)
        at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:141)
        at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:90)
        at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:417)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source:
        at com.sun.xml.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:127)
        at com.sun.xml.messaging.saaj.soap.ver1_2.SOAPPart1_2Impl.createEnvelopeFromSource(SOAPPart1_2Impl.java:84)
        at com.sun.xml.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:150)
        at org.springframework.ws.soap.saaj.support.SaajUtils.getSaajVersion(SaajUtils.java:155)
        at org.springframework.ws.soap.saaj.SaajSoapMessage.getSaajVersion(SaajSoapMessage.java:257)
        ... 39 more
Caused by: javax.xml.transform.TransformerException: org.xml.sax.SAXParseException: The markup in the document preceding the root element must be well-formed.
        at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:501)
        at com.sun.xml.messaging.saaj.util.transform.EfficientStreamingTransformer.transform(EfficientStreamingTransformer.java:414)
        at com.sun.xml.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:118)
        ... 43 more
Caused by: org.xml.sax.SAXParseException: The markup in the document preceding the root element must be well-formed.
        at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1231)
        at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
        at org.xml.sax.helpers.XMLFilterImpl.parse(XMLFilterImpl.java:333)
        at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:484)
        ... 45 more

I've went through a lot of potential issues. However, I think I've narrowed it down to being a SAAJ issue in some respect.
In the SaajSoapMessageFactory class for Spring-WS there is a method that begins with:
public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
        MimeHeaders mimeHeaders = parseMimeHeaders(inputStream);
        try {
            inputStream = checkForUtf8ByteOrderMark(inputStream);
            SOAPMessage saajMessage = messageFactory.createMessage(mimeHeaders, inputStream);
            postProcess(saajMessage);
            return new SaajSoapMessage(saajMessage, langAttributeOnSoap11FaultString, messageFactory);
        }

When I send using the client with JRE 6, the inputStream AFTER the createMessage call begins like:
[60, 101, 110, 118, 58, 69, 110, 118, 101, 108, 111, 112, 101, 32, 120, 109, 108, 110, 115, 58, 101, 110, 118, 61, 34, 104, 116

Which converts to: <env:Envelope... etc.
However, when I send using the client with JRE 7, the inputStream after the createMessage call begins like:
[101, 110, 118, 58, 69, 110, 118, 101, 108, 111, 112, 101, 32, 120, 109, 108, 110, 115, 58, 101, 110, 118, 61, 34, 104, 116

As you can see the first byte, the left angle bracket, has gone missing. I have been trying to debug down into it but I lack the com.sun.xml.internal sources to really do much effectivey.
Also of note, in JRE 6, the PushbackInputStream AFTER the checkForUtf8ByteOrderMark call actually looks like the final byte array:
[60, 101, 110, 118, 58, 69, 110, 118, 101, 108, 111, 112, 101, 32, 120, 109, 108, 110, 115, 58, 101, 110, 118, 61, 34, 104, 116, etc
But when sending using JRE 7, it looks like this:
[60, 0, 0, 0, 0, 0, 0, 0, 0, etc
Now, the method itself seems to follow the same flow, verifying that there is no BOM and then putting back what it took off to verify it (at least, so it appears to me).
So, I have two questions:
1) Does anyone know what's going on? Is there anything here that's ringing a bell?
2) How can I get the source for those com.sun.xml.internal packages?
I should note, I can run this locally on Tomcat in Eclipse and not seem to have any issues, but I know there's some funky class loading stuff probably going on there.
Update 1:
I was able to associate some source to the code and got into this method in SOAPPart1_2Impl:
   public void setContent(Source source) throws SOAPException {
        try {
            if (source instanceof StreamSource) {
                InputStream is = ((StreamSource) source).getInputStream();
                Reader rdr = ((StreamSource) source).getReader();

                if (is != null) {
                    this.source = new JAXMStreamSource(is);
                } else if (rdr != null) {
                    this.source = new JAXMStreamSource(rdr);
                } else {
                    log.severe("SAAJ0544.soap.no.valid.reader.for.src");
                    throw new SOAPExceptionImpl("Source does not have a valid Reader or InputStream");
                }
            }

Now, it takes the first path of setting the InputStream. What's very interesting is that when this is done, source has a ByteInputStream that begins as such:
[60, 0, 0, 101, 110, 118, 58, 69, 110, 118, 101, 108, 111, 112, 101, 32, 120, 109, 108, 110, 115, 58, 101, etc
I'm very confused by this. I'll will try to figure out what exactly happens to those firs three characters -- maybe there is some side effect to the checkForUtf8ByteOrderMark method.
Update 2:
Okay, now I'm really getting somewhere. I looked into that JAXMStreamSource class and that leads to a ByteOutputStream class which has a method:
public void write(InputStream in) throws IOException {
    if (in instanceof ByteArrayInputStream) {
        int size = in.available();
        ensureCapacity(size);
        count += in.read(buf,count,size);
        return;
    }
    while(true) {
        int cap = buf.length-count;
        int sz = in.read(buf,count,cap);
        if(sz<0)    return;     // hit EOS

        count += sz;
        if(cap==sz)
            // the buffer filled up. double the buffer
            ensureCapacity(count);
    }
}

On the line "int sz = in.read(buf,count,cap);" is where the two zeros after the 60 gets added. I'm still trying to figure out why and why a client, of all things, using 1.7 could have possibly had this effect.
Comment: not all of the source files are in the main download.  it's kind of annoying.  you can run the included ant scripts to download some of the secondary bundles (jaxws, jaxb, etc).
Comment: you can get the source of the jdk from the openjdk project.
Comment: @jtahlborn I did visit this page http://download.java.net/openjdk/jdk6/ and download the source there. However, I didn't find any of these internal classes, so perhaps that wasn't the right place? I did manage to find a number of these files online so I just made my own little source jar and associated it with my project. Not great, but passable.
Answer: Upgrading to 2.0.4.RELEASE somehow fixed this problem. The checkForUtf8ByteOrderMark method didn't change but something else must have changed as the stream coming in looked different after that.
Comment: We had same issue. "spring-ws 2.0.2" webservice worked over http, but didn't work over https. Upgrading on spring-ws 2.0.4 solved our issue. Thanks a lot
Answer:
maybe there is some side effect to the checkForUtf8ByteOrderMark
  method.

I think you might be right
https://jira.springsource.org/browse/SWS-750
Comment: Yes, yes, yes! Because the buf pulled off what it did, there's code in the PushbackInputStream to first add the buffer, then read in bytes. So, it reads into those three bytes then reads the rest. It was indeed a side effect! You posting this here made me look over the chain of events again and that made me reexamine it just right. I'll have to look and see if 2.0.5 has a better version of this or not.
Comment: I had seen that but after more investigating, I think not. I was a little confused as to what stream was being used, and it's actually the one in my update (sorry). So, the real issue now isn't that the 60 byte is missing, but that there's two 0 bytes in there. Thank you for trying to point me in a good direction, though.
Comment: What Spring-WS version do you use by the way?
Comment: I'm currently using 2.0.2.RELEASE. I know 2.0.5 is the latest version but I'm not sure if/when I'll be able to move up.
Comment: Actually, the more I delve, more I think it is indeed a side effect of that, haha. I'll have to extend that class or implement its interface and try some changes, I think. This has really made my mind twist.


Criando URL Amigável não sei como fazer

Question: Tenho um site e na index.php e onde se faz o cadastro e login.
Assistir algumas vídeos aulas porem todas elas fazer a explicação usando a index como exemplo para que possa pegar a url e trabalha-la com o php
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1

Tenho que tirar todo conteudo do index e colocar em um novo arquivo para que eu possa deixar o index so para verificaçoes de url????????
outra duvida e que se eu não quizer fazer da maneira acima posso optar por ficar reescrevendo o que o usuario digita e para onde ele vai somente com o htaccess? e isso mesmo? ou tem outra forma?
exemplo:
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^login(.*)$ login.php

Answer: Eu não entendi a sua pergunta muito bem, mas.
1 - crie um arquivo .htaccess.
2 - Não mecha na index com htaccess já que é a página principal.
3 - pra modificar as URL faça o seguinte.
RewriteEngine On
RewriteBase /
RewriteRule ^Nome-da-pagina-que-vc-quer?$ Nome-da-pagina-que-vc-quer-mudar.php[QSA,L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Criando URL Amigável não sei como fazer


ab = a/b = b/a, what's this symmetry called?

Question: I was playing around with numbers the other day, and I found an interesting symmetry, that I would like to know if it has any specific name assigned to it.
Let's assume the notation $n:a$ to refer to any number whose modulus $n = a$. That is, which if written with an $n$-radixed numeral system, would have a least significant digit of $a$. (If anyone knows the standard notation for expressing this, feel free to add that info.)
We can then write $10:3 \times 10:7 = 10:1$, because if we multiply any two integers with least significant decimals of $3$ and $7$ respectively, then the result will always have a least significant decimal of $1$, for example:
$$\begin{align}
33 \times 77 &= 2541\\
103 \times 97 &= 9991\\
73 \times 37 &= 2701
\end{align}$$
We can also write $\dfrac{10:3}{10:7} = 10:9$, because if we divide a number with least significant decimal of $3$, by a number with least significant decimal of $7$, then (given that it is evenly divisible), the result will always have a last decimal of $9$. For example:
$$\begin{align}
\frac{7743}{87} &= 89\\
\frac{1083}{57} &= 19\\
\frac{3353}{7} &= 479
\end{align}$$
So far, nothing weird is going on. However, the strange thing starts to happen if we use certain radixes, for example 24 instead of 10, then
$$(24:17 \times 24:23) = \left(\frac{24:17}{24:23}\right) = \left(\frac{24:23}{24:17}\right) = 24:7$$
Let us simplify the above a bit, and write it as:
$$24:\left((17 \times 23) = \frac{17}{23} = \frac{23}{17} = 7\right)$$
Let us try to test the truthness of this. By creating the numbers $24:17$ and $24:23$, and multiplying them, we can test if the product $= 24:7$.
If $24:\left(\frac{23}{17} = 7\right)$, then $24:((17 \times 7) = 23)$, and if $24:(\frac{17}{23} = 7)$, then $24:((7 \times 23) = 17)$. In order to test the above expression, let us therefore multiply the numbers:

$24:17$ and $24:23$ (the result should be $24:7$)
$24:23$ and $24:7$ (the result should be $24:17$)
$24:17$ and $24:7$ (the result should be $24:23$)

For this demonstration I will only do the multiplication once for each of the three types, above, but of course one can try as many combinations of numbers with $24$-moduluses specified above that one feels is sufficient to convince oneself that it is always true.
A number that equals $24:17$, that is, which has a $24$-modulus of $17$, must have the form $17 + 24 \times x$, where $x$ is any arbitrary integer. We can use the same method to create arbitrary numbers with any specific modulus. For this test, let's let $x = 0$. Let us use these arbitrary numbers with moduluses $17$, $7$ and $23$:
$$\begin{align}
17 + 0 \times 24 &= 17\\
7 + 0 \times 24 &= 7\\
23 + 0 \times 24 &= 23
\end{align}$$
Then let us examine if there is a symmetry between the result of them being multiplied and divided by one another.
$$\begin{align}
17 \times 7 &= 119\\
\frac{119}{24} &= 4 + \frac{23}{24}
\end{align}$$
The above shows that $24:\left(\frac{23}{17} = 7\right)$
$$\begin{align}
23 \times 7 &= 161\\
\frac{161}{24} &= 6 + \frac{17}{24}
\end{align}$$
The above shows that $24:\left(\frac{17}{23} = 7\right)$
$$\begin{align}
17 \times 23 = 391\\
\frac{391}{24} = 16 + \frac7{24}
\end{align}$$
The above shows that $24:((17 \times 23) = 7)$
Comment: I'm honestly surprised that this hasn't been brought up in three years, almost to the day, but the correct notation for "24:17" is "17 mod 24". Google "mod" or "modular arithmetic" for more details.
Comment: I am aware of this, but I decided to use a different notation because the mod notation would be too space consuming in this case ;)
Comment: I can get behind that, but if you're going to shorten it, please use the same order (i.e., 17:24, not 24:17). It's a bit difficult for me to follow because I have to remember to switch the numbers around.
Answer: You are just noticing some basic relations in the rings $\mathbb{Z}/n\mathbb{Z}$. You may not be familiar with it : it's just the formalization of your idea that for any numbers $a$ and $b$, the last digit in the $n$-adic expansion of $a+b$ and $ab$ depends only on the last digits of $a$ and $b$.
So you can think of $\mathbb{Z}/n\mathbb{Z}$ as the set $\{0,1,\dots,n-1\}$, and for any $a\in \mathbb{Z}$ you can write $[a]\in \mathbb{Z}/n\mathbb{Z}$ its residue modulo $n$. Then you get $[a+b]=[a]+[b]$ and $[ab]=[a][b]$.
Now in your example modulo $24$, you take $a=23$ and $b=17$. But $[a]=[-1]$, so quite naturally you get $[ab]=[-b]=[b/a]$ because $(-1)b=b/(-1)$. The fact that $[-b]=[a/b]=[-1/b]$ means that $[-b^2]=[-1]$, so $[b^2]=1$. And indeed, $[17^2]=[289]=[12\cdot 24+1]=[1]$.
So for any $n$, if you find $b\in \mathbb{Z}$ such that $[b^2]=[1]$ (which is always possible) and $a$ such that $[a]=[-1]$ (for instance, $a=n-1$), then you will always have $[ab]=[b/a]=[a/b]$.


rpmbuild fails for unknown reason when using --target

Question: I recently updated my dev machine from Fedora 30 to 31, but I still need to target a Fedora 30 machine.
I am trying to build a SPEC using the parameter --target f30, but I get an error for 'xargs' out of nowhere...
rpmbuild -bb ~/rpmbuild/SPECS/Project.spec --target f30
Building target platforms: f30
Building for target f30
Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.hUazCA
+ umask 022
+ cd /home/matthew/rpmbuild/BUILD
+ cd /home/matthew/rpmbuild/BUILD
+ rm -rf Project-1.9.1
+ /usr/bin/gzip -dc /home/matthew/rpmbuild/SOURCES/Project-1.9.1.tar.gz
+ /usr/bin/tar -xof -
+ STATUS=0
+ '[' 0 -ne 0 ']'
+ cd Project-1.9.1
+ /usr/bin/chmod -Rf a+rX,u+w,g-w,o-w .
+ RPM_EC=0
++ jobs -p
+ exit 0
Executing(%build): /bin/sh -e /var/tmp/rpm-tmp.TnKydD
+ umask 022
+ cd /home/matthew/rpmbuild/BUILD
+ cd Project-1.9.1
+ RPM_EC=0
++ jobs -p
+ exit 0
Executing(%install): /bin/sh -e /var/tmp/rpm-tmp.GIPsyB
+ umask 022
+ cd /home/matthew/rpmbuild/BUILD
+ '[' '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}' '!=' / ']'
+ rm -rf '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}'
++ dirname '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}'
+ mkdir -p /home/matthew/rpmbuild/BUILDROOT
+ mkdir '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}'
+ cd Project-1.9.1
+ mkdir -p '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}/opt/Project'
+ cp -a README.md __dump__ __files__ __scripts__ __wheels__ apps dbms dbtools graph.png loc manage.py meta program requirements.txt rgs static veh '/home/matthew/rpmbuild/BUILDROOT/Project-1.9.1-1.fc31.%{_arch}/opt/Project'
+ /usr/lib/rpm/check-buildroot
xargs: invalid number for -P option
Usage: xargs [OPTION]... COMMAND [INITIAL-ARGS]...
Run COMMAND with arguments INITIAL-ARGS and more arguments read from input.

Mandatory and optional arguments to long options are also
mandatory or optional for the corresponding short option.
  -0, --null                   items are separated by a null, not whitespace;
                                 disables quote and backslash processing and
                                 logical EOF processing
  -a, --arg-file=FILE          read arguments from FILE, not standard input
  -d, --delimiter=CHARACTER    items in input stream are separated by CHARACTER,
                                 not by whitespace; disables quote and backslash
                                 processing and logical EOF processing
  -E END                       set logical EOF string; if END occurs as a line
                                 of input, the rest of the input is ignored
                                 (ignored if -0 or -d was specified)
  -e, --eof[=END]              equivalent to -E END if END is specified;
                                 otherwise, there is no end-of-file string
  -I R                         same as --replace=R
  -i, --replace[=R]            replace R in INITIAL-ARGS with names read
                                 from standard input; if R is unspecified,
                                 assume {}
  -L, --max-lines=MAX-LINES    use at most MAX-LINES non-blank input lines per
                                 command line
  -l[MAX-LINES]                similar to -L but defaults to at most one non-
                                 blank input line if MAX-LINES is not specified
  -n, --max-args=MAX-ARGS      use at most MAX-ARGS arguments per command line
  -P, --max-procs=MAX-PROCS    run at most MAX-PROCS processes at a time
  -p, --interactive            prompt before running commands
      --process-slot-var=VAR   set environment variable VAR in child processes
  -r, --no-run-if-empty        if there are no arguments, then do not run COMMAND;
                                 if this option is not given, COMMAND will be
                                 run at least once
  -s, --max-chars=MAX-CHARS    limit length of command line to MAX-CHARS
      --show-limits            show limits on command-line length
  -t, --verbose                print commands before executing them
  -x, --exit                   exit if the size (see -s) is exceeded
      --help                   display this help and exit
      --version                output version information and exit

Report bugs to <email@example.com>.
+ /usr/lib/rpm/redhat/brp-ldconfig
+ /usr/lib/rpm/brp-compress
+ /usr/lib/rpm/brp-strip /usr/bin/strip
+ /usr/lib/rpm/brp-strip-comment-note /usr/bin/strip /usr/bin/objdump
+ /usr/lib/rpm/brp-strip-static-archive /usr/bin/strip
xargs: invalid number for -P option
Usage: xargs [OPTION]... COMMAND [INITIAL-ARGS]...
Run COMMAND with arguments INITIAL-ARGS and more arguments read from input.

Mandatory and optional arguments to long options are also
mandatory or optional for the corresponding short option.
  -0, --null                   items are separated by a null, not whitespace;
                                 disables quote and backslash processing and
                                 logical EOF processing
  -a, --arg-file=FILE          read arguments from FILE, not standard input
  -d, --delimiter=CHARACTER    items in input stream are separated by CHARACTER,
                                 not by whitespace; disables quote and backslash
                                 processing and logical EOF processing
  -E END                       set logical EOF string; if END occurs as a line
                                 of input, the rest of the input is ignored
                                 (ignored if -0 or -d was specified)
  -e, --eof[=END]              equivalent to -E END if END is specified;
                                 otherwise, there is no end-of-file string
  -I R                         same as --replace=R
  -i, --replace[=R]            replace R in INITIAL-ARGS with names read
                                 from standard input; if R is unspecified,
                                 assume {}
  -L, --max-lines=MAX-LINES    use at most MAX-LINES non-blank input lines per
                                 command line
  -l[MAX-LINES]                similar to -L but defaults to at most one non-
                                 blank input line if MAX-LINES is not specified
  -n, --max-args=MAX-ARGS      use at most MAX-ARGS arguments per command line
  -P, --max-procs=MAX-PROCS    run at most MAX-PROCS processes at a time
  -p, --interactive            prompt before running commands
      --process-slot-var=VAR   set environment variable VAR in child processes
  -r, --no-run-if-empty        if there are no arguments, then do not run COMMAND;
                                 if this option is not given, COMMAND will be
                                 run at least once
  -s, --max-chars=MAX-CHARS    limit length of command line to MAX-CHARS
      --show-limits            show limits on command-line length
  -t, --verbose                print commands before executing them
  -x, --exit                   exit if the size (see -s) is exceeded
      --help                   display this help and exit
      --version                output version information and exit

Report bugs to <firstname.lastname@example.com>.
error: Bad exit status from /var/tmp/rpm-tmp.GIPsyB (%install)

RPM build errors:
    Bad exit status from /var/tmp/rpm-tmp.GIPsyB (%install)

Using the very verbose -vv option with 'rpmbuild' didn't provide anything useful. Any ideas what the issue could be?
Even when targeting f31 (the platform itself) specifically, the build fails, but when not adding a target such that it defaults to f31, it succeeds.
Answer: The target option is for architecture. And even that works only if you do some other low level magic. You should do:
rpmbuild -bs ~/rpmbuild/SPECS/Project.spec
# this will produce Project.src.rpm
mock -r fedora-30-x86_64 Project.src.rpm

And it will does not matter whether you are on F30 or 31 or on CentOS.
Comment: Can't believe I didn't come across this through my web searches... Hopefully others will come here for the answer instead of wasting there time elsewhere. Thanks! PS: The parameter in the `mock` command should read 'fedora-30-x86_**64**'.


asp:Menu hover makes "Security Information" pop up, how do I fix?

Question:
I hover over my menu and a submenu expands, then this bad boy comes accross the screen. Is there something I can do in my website to prevent this?
IE6
aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Templates/MyPage.master" AutoEventWireup="true"
    CodeFile="Tasks.aspx.cs" Inherits="UI_MyPage_Tasks" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

                <asp:Menu ID="menu1" runat="server" OnMenuItemClick="menu1_MenuItemClick" />

                <cc:CustomUserControl ID="cuc1" runat="server" />

aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VAC.Data;

public partial class UI_Patient_Tasks : BasePage
{
    MyDB db = new MyDB();
    private MenuItem UserRole1MenuItem { get { return GetMenu(Common.Role.UserRole1); } }
    private MenuItem UserRole2MenuItem { get { return GetMenu(Common.Role.UserRole2); } }

    private MenuItem GetMenu(string roleName)
    {
        int roleID = (from r in db.Roles where r.RoleName == roleName select r.RoleID).First();
        MenuItem main = new MenuItem(roleName + " Menu");
        foreach (CustomObject co in (from c in db.CustomObjects where c.RoleID == roleID orderby c.SortOrder select c))
            main.ChildItems.Add(new MenuItem(co.Description, co.CustomObjectID.ToString()));
        return main;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            menu1.Items.Clear();
            if (User.IsInRole(Common.Role.UserRole1))
                menu1.Items.Add(UserRole1MenuItem);
            if (User.IsInRole(Common.Role.UserRole2))
                menu1.Items.Add(UserRole2MenuItem);
        }
    }
    protected void menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        int id;
        if (int.TryParse(e.Item.Value, out id))
        {
            cuc1.CustomObjectID = id;
        }
    }
}

    </asp:Content>

Comment: Ok the only http references I could find were in my sitemaps.
`` let me delete this.
Comment: You should probably post some markup code for your menu.
Comment: @Bill MaGriff, try running something like Fiddler http://www.fiddlertool.com/fiddler/ whilst it's happening, it should tell you exactly what item(s) are trying to come down as http
Comment: @Rob, all I see are the locked HTTPS requests
Comment: No requests for *anything* over http at all? That is odd :=/ Even when you receive the warning dialog box and click "yes"?
Comment: Yup, there seems to be no difference between clicking yes or no. The site is still fully functional, just annoying.
Comment: So when clicking Yes, or No, you still get no requests made that you can see through Fiddler for resources that are non-secure?
Comment: All the requests are HTTPS. When the menu hover occurs no requests are made.
Comment: @Biff, I'm afraid I'm at a loss then. Given that it's IE6, it's possible it's making a request for a local resource like "about:blank" as a placeholder of some description. You may just have to put it down to "known issue in IE6" if your client can stomach that, or try alternative menu controls if they won't
Comment: Ugh, another IE6 "gotcha". Thanks for your insight Rob.
Answer: It looks like you're serving your site over ssl (i.e. https://) but serving some of the content, almost certainly something in the menu - such as an image over http://, hence you're receiving the "mixed mode" warning.
Review the markup for your menu and look for any http:// URLs in the .aspx page (or possibly your codebehind if you build the menu dynamically) where there should be https:// or vice-versa.
Answer: Make sure all images or external resources are referenced via https.
Answer: Hooray I found a fix.
The problem is in the PopOut_Show function. MS does some weird child frame thing.
I deleted it and it all works well!


How should I clean my fingerboard without damaging my violin?

Question: The other day I was teaching some 5 and 6 year old friends about my violin, and they drew the bow all over the fingerboard, making the strings sticky. I don't want to damage my violin while cleaning it, but it's hard to work with and I do need to keep practicing.
My violin did not come with anything to clean it with, and before now, it hasn't gotten so dirty that I had any trouble wiping it off with whatever was handy. My present situation seems to call for water (which I am worried would damage my violin) or some kind of cleaner. As to the latter, I do not know what kinds to use and not to use, and I would rather be safe and ask before I act.
Comment: My mother cleans her violins finger board with eucalyptus oil.
Answer: If the goal is to remove the rosin residue on your strings, you can remove it with a soft dry cloth, without any other product.
Put the cloth on the string, one at a time, then by snapping two fingers together firmly go back and forth across the length of the string.
This sould produce a somewhat high shriek from the strings and will put them out of tune. It is not dangerous.
Same goes for the fingerboard itself, if the rosin is not too ingrained in it, rubbing with a cloth might do it.
Otherwise, you can go to a luthier and ask for something to clean your violin, the ones I know each have their own recipe for that and normally give it or sell it really cheaply.
Also, as relevantly commented by Sergio, do not use any alchool in the process. This will badly damage the varnish, maybe even affect the sound.
Comment: NIce answer, `+1`. Might be usefull refering that alcohol related products are a _no no_, just so people don't even get tempted.
Answer: When I was a kid I had this violin cleaner and polish set from Shar. Maybe you could look into that cleaner stuff to get rosin off. Looking at Sharmusic's website they seem to have a lot of cleaning supplies. I'd be interested to hear feedback from anyone else who has used that.
Personally I have used rubbing alcohol on the fingerboard because a teacher suggested I use it on the chinrest to deal with my violinist hickey possibly getting infected. And I accidentally got rubbing alcohol on the varnish on the back of my violin, which of course took a layer of varnish off in the shape of a square. Embarrassing. And I think the rubbing alcohol might have damaged the fingerboard. So that's my experience with it.
Answer: Indeed there are the so-called "instrument polishes" but if in dire need and willing to try something on a NON-shellac finished instrument ( careful there! ) you could try ..non-alcoholic furniture wipes. There are some that do not contain alcohol or leave residue- an acquaintance uses them to gently wipe the neck every week (ok, a hard worker, gives lessons every day so the violin gets dirty a lot) by passing a rolled up wet furniture wipe underneath the strings.
Me, I have a totally un-violin-like beast made out of resin and composites , finished with nitro (yes, an electric abomination) but it still has an ebony fretboard. Using the same furniture wet wipes, not pressing down too hard, and cleaning up afterwards with a microfiber cloth did nothing bad to my particular instrument in 12 years now.
My friend uses a lower, student-grade violin for teaching and only gets the master-built one out in concerts. I do not know how she services the high quality instrument, but the same wet furniture wipes worked perfectly on her other, teaching- grade violin also with non-shellac finish.


Julia MLJ not loading correctly

Question: I'm at the install/testing phase of Julia and attempting to run the Iris example MLJ Example of training a model using the Julia MLJ.  I think I have it installed properly but am getting this error.  What have I done incorrectly? Thx. J
<code>julia> Tree = @load DecisionTreeClassifier pkg=DecisionTree
DecisionTreeClassifier(
    max_depth = -1,
    min_samples_leaf = 1,
    min_samples_split = 2,
    min_purity_increase = 0.0,
    n_subfeatures = 0,
    post_prune = false,
    merge_purity_threshold = 1.0,
    pdf_smoothing = 0.0,
    display_depth = 5,
    rng = Random._GLOBAL_RNG()) @726

julia> tree = Tree()
ERROR: MethodError: no method matching (::MLJDecisionTreeInterface.DecisionTreeClassifier)()
Closest candidates are:
  (::Supervised)(::Tuple{AbstractMatrix{T} where T, Any}) at /home/name/.julia/packages/MLJBase/8HFqb/src/composition/learning_networks/arrows.jl:25
  (::Supervised)(::Tuple{AbstractNode, AbstractNode}) at /home/name/.julia/packages/MLJBase/8HFqb/src/composition/learning_networks/arrows.jl:21
  (::Supervised)(::Tuple{AbstractNode, Any}) at /home/name/.julia/packages/MLJBase/8HFqb/src/composition/learning_networks/arrows.jl:22
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[24]:1
</code>
Answer: I found the problem, old and un-updateable versions of some packages.  So I moved copies of ~/.julia/environments/v1.6/Manifest.toml and Project.toml to another directory for storage, restarted julia, reinstalled the packages MLJ and MLJDecisionTreeInterface, and this time got the most recent versions.  Now the code runs fine.

Julia MLJ not loading correctly


Removing Invalid Characters From XML File Before Deserialization

Question: I have some XML I am receiving from a server that sometimes has some invalid characters that I would like to remove before deserialization. I have no control over the XML file I receive so I need to check for the invalid characters myself.
Sample XML.....
<PrintStatus>N</PrintStatus>
<CustomerPO> >>>> pearl <<<<< </CustomerPO>
<Description>PO# pearl</Description>
<BranchID>4</BranchID>
<PostDate>
   <Date>01/13/2015</Date>
</PostDate>
<ShipDate>
   <Date>01/13/2015</Date>
</ShipDate>

As you can see, the customer po section has the invalid characters I need to remove.  This sometimes occurs only in certain elements that include user typed data.
Here is my Response code.....
//configure http request
HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.Method = "POST";

//prepare correct encoding for XML serialization
UTF8Encoding encoding = new UTF8Encoding();

//use Xml property to obtain serialized XML data
//convert into bytes using encoding specified above and get length
byte[] bodyBytes = encoding.GetBytes(Xml);
httpRequest.ContentLength = bodyBytes.Length;

//get http request stream for putting XML data into
Stream httpRequestBodyStream = httpRequest.GetRequestStream();

//fill stream with serialized XML data
httpRequestBodyStream.Write(bodyBytes, 0, bodyBytes.Length);
httpRequestBodyStream.Close();

//get http response
HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
StreamReader httpResponseStream = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.ASCII);

//extract XML from response
string httpResponseBody = httpResponseStream.ReadToEnd();
httpResponseStream.Close();

//ignore everything that isn't XML by removing headers
httpResponseBody = httpResponseBody.Substring(httpResponseBody.IndexOf("<?xml"));

//deserialize XML into ProductInquiryResponse
XmlSerializer serializer = new XmlSerializer(typeof(MyResponseClass));
StringReader responseReader = new StringReader(httpResponseBody);

//return MyResponseClass result
return serializer.Deserialize(responseReader) as MyResponseClass;

Does anyone happen to have any suggestions to check the XML?  Should I just check the elements I am concerned with right before the xml string gets deserialized? Or is there a better way?
Comment: If it has invalid characters, then it is not XML. Maybe the service owners don't know they are sending garbage. You should tell them so they have a chance of fixing their bug.
Comment: that content should be in [CData](http://www.w3schools.com/xml/xml_cdata.asp) section..can you change it on the server or request for it? I dont think you should be removing that!
Comment: Thanks for the responses. I agree John. I tried getting it fixed many times at the source but no luck. I have no choice but to check and remove the characters myself.
Answer: A general fix for your problem would be to recursively descend the XML, parsing as you go and comparing to the schema for that node.  At any point if the input differs from the input expected from the schema, or is malformed in some way, allow an error handler to run to fix the input stream, rolling back to the most recent good state and proceeding forward with the fixed input.
The .Net XmlTextReader class is not flexible enough to do this.  However, if you know in advance that from the schema that certain XML Elements cannot have children, then the following will read an XML input stream, and upon encountering an element whose fully qualified name matches the known names of leaf nodes, and "escape" the text of all such nodes:
public enum XmlDoctorStatus
{
    NoFixNeeded,
    FixMade,
    FixFailed
}

public class XmlDoctor
{
    internal class XmlFixData
    {
        public string InitialXml { get; private set; }
        public string FixedXml { get; private set; }
        public int LineNumber { get; private set; }
        public int LinePosition { get; private set; }

        public XmlFixData(string initialXml, string fixedXml, int lineNumber, int linePosition)
        {
            this.InitialXml = initialXml;
            this.FixedXml = fixedXml;
            this.LineNumber = lineNumber;
            this.LinePosition = linePosition;
        }

        public bool ComesAfter(XmlFixData other)
        {
            if (LineNumber > other.LineNumber)
                return true;
            if (LineNumber == other.LineNumber && LinePosition > other.LinePosition)
                return true;
            return false;
        }
    }

    internal class XmlFixedException : Exception
    {
        public XmlFixData XmlFixData { get; private set; }

        public XmlFixedException(XmlFixData data)
        {
            this.XmlFixData = data;
        }
    }

    readonly HashSet<XName> childlessNodes;

    public string OriginalXml { get; private set; }

    public XmlDoctor(string xml, IEnumerable<XName> childlessNodes)
    {
        if (xml == null)
            throw new ArgumentNullException();
        this.OriginalXml = xml;
        this.childlessNodes = new HashSet<XName>(childlessNodes);
    }

    List<int> indices = null;
    string passXml = string.Empty;
    bool inPass = false;

    void InitializePass(string xml)
    {
        if (inPass)
            throw new Exception("nested pass");
        ClearElementData();
        TextHelper.NormalizeLines(xml, out passXml, out indices);
        inPass = true;
    }

    void EndPass()
    {
        inPass = false;
        indices = null;
        passXml = string.Empty;
        ClearElementData();
    }

    static int LineNumber(XmlReader reader)
    {
        return ((IXmlLineInfo)reader).LineNumber;
    }

    static int LinePosition(XmlReader reader)
    {
        return ((IXmlLineInfo)reader).LinePosition;
    }

    // Taken from https://stackoverflow.com/questions/1132494/string-escape-into-xml

    public static string XmlEscape(string escaped)
    {
        var replacements = new KeyValuePair<string, string>[]
        {
            new KeyValuePair<string,string>("&", "&"),
            new KeyValuePair<string,string>("\"", """),
            new KeyValuePair<string,string>("'", "'"),
            new KeyValuePair<string,string>("<", "<"),
            new KeyValuePair<string,string>(">", ">"),
        };

        foreach (var pair in replacements)
            foreach (var index in escaped.IndexesOf(pair.Key, 0).Reverse())
                if (!replacements.Any(other => string.Compare(other.Value, 0, escaped, index, other.Value.Length, StringComparison.Ordinal) == 0))
                {
                    escaped = escaped.Substring(0, index) + pair.Value + escaped.Substring(index + 1, escaped.Length - index - 1);
                }
        return escaped;
    }

    void HandleNode(XmlReader reader)
    {
        // Adapted from http://blogs.msdn.com/b/mfussell/archive/2005/02/12/371546.aspx
        if (reader == null)
        {
            throw new ArgumentNullException("reader");
        }

        switch (reader.NodeType)
        {
            case XmlNodeType.Element:
                HandleStartElement(reader);
                if (reader.IsEmptyElement)
                {
                    HandleEndElement(reader);
                }
                break;
            case XmlNodeType.Text:
                HandleText(reader);
                break;
            case XmlNodeType.Whitespace:
            case XmlNodeType.SignificantWhitespace:
                break;
            case XmlNodeType.CDATA:
                break;
            case XmlNodeType.EntityReference:
                break;
            case XmlNodeType.XmlDeclaration:
            case XmlNodeType.ProcessingInstruction:
                break;
            case XmlNodeType.DocumentType:
                break;
            case XmlNodeType.Comment:
                break;
            case XmlNodeType.EndElement:
                HandleEndElement(reader);
                break;
        }
    }

    private void HandleText(XmlReader reader)
    {
        if (string.IsNullOrEmpty(currentElementLocalName) || string.IsNullOrEmpty(currentElementName))
            return;
        var name = XName.Get(currentElementLocalName, currentElementNameSpace);
        if (!childlessNodes.Contains(name))
            return;
        var lineIndex = LineNumber(reader) - 1;
        var charIndex = LinePosition(reader) - 1;
        if (lineIndex < 0 || charIndex < 0)
            return;

        int startIndex = indices[lineIndex] + charIndex;

        // Scan forward in the input string until we find either the beginning of a CDATA section or the end of this element.
        // Patterns to match:  </Name
        //
        string pattern1 = "</" + currentElementName;
        var index1 = FindElementEnd(passXml, startIndex, pattern1);
        if (index1 < 0)
            return;  // BAD XML.
        string pattern2 = "<![CDATA[";
        var index2 = passXml.IndexOf(pattern2, startIndex);
        int endIndex = (index2 < 0 ? index1 : Math.Min(index1, index2));
        var text = passXml.Substring(startIndex, endIndex - startIndex);

        var escapeText = XmlEscape(text);
        if (escapeText != text)
        {
            if (escapeText != XmlEscape(escapeText))
            {
                Debug.Assert(escapeText == XmlEscape(escapeText));
                throw new InvalidOperationException("Escaping error");
            }
            string fixedXml = passXml.Substring(0, startIndex) + escapeText + passXml.Substring(endIndex, passXml.Length - endIndex);
            throw new XmlFixedException(new XmlFixData(passXml, fixedXml, lineIndex + 1, charIndex + 1));
        }
    }

    static bool IsXmlSpace(char ch)
    {
        // http://www.w3.org/TR/2000/REC-xml-20001006#NT-S
        // [3]      S      ::=      (#x20 | #x9 | #xD | #xA)+
        return ch == '\u0020' || ch == '\u0009' || ch == '\u000D' || ch == '\u000A';
    }

    private static int FindElementEnd(string passXml, int charPos, string tagEnd)
    {
        while (true)
        {
            var index = passXml.IndexOf(tagEnd, charPos);
            if (index < 0)
                return index;
            int endPos = index + tagEnd.Length;
            if (index + tagEnd.Length >= passXml.Length)
                return -1; // Bad xml?
            // Now we must have zero or more white space characters and a ">"
            while (endPos < passXml.Length && IsXmlSpace(passXml[endPos]))
                endPos++;
            if (endPos >= passXml.Length)
                return -1; // BAD XML;
            if (passXml[endPos] == '>')
                return index;
            index = endPos;
            // Spurious ending, keep searching.
        }
    }

    string currentElementName = string.Empty;
    string currentElementNameSpace = string.Empty;
    string currentElementLocalName = string.Empty;

    private void HandleStartElement(XmlReader reader)
    {
        currentElementName = reader.Name;
        currentElementLocalName = reader.LocalName;
        currentElementNameSpace = reader.NamespaceURI;
    }

    private void HandleEndElement(XmlReader reader)
    {
        ClearElementData();
    }

    private void ClearElementData()
    {
        currentElementName = string.Empty;
        currentElementNameSpace = string.Empty;
        currentElementLocalName = string.Empty;
    }

    public XmlDoctorStatus TryFix(out string newXml)
    {
        XmlFixData data = null;

        while (true)
        {
            XmlFixData newData;
            var status = TryFixOnePass((data == null ? OriginalXml : data.FixedXml), out newData);
            switch (status)
            {
                case XmlDoctorStatus.FixFailed:
                    Debug.WriteLine("Could not fix XML");
                    newXml = OriginalXml;
                    return XmlDoctorStatus.FixFailed;

                case XmlDoctorStatus.FixMade:
                    if (data != null && !newData.ComesAfter(data))
                    {
                        Debug.WriteLine("Warning -- possible infinite loop detected, aborting fix");
                        newXml = OriginalXml;
                        return XmlDoctorStatus.FixFailed;
                    }
                    data = newData;
                    break;  // Try to fix more

                case XmlDoctorStatus.NoFixNeeded:
                    if (data == null)
                    {
                        newXml = OriginalXml;
                        return XmlDoctorStatus.NoFixNeeded;
                    }
                    else
                    {
                        newXml = data.FixedXml;
                        return XmlDoctorStatus.FixMade;
                    }
            }
        }
    }

    XmlDoctorStatus TryFixOnePass(string xml, out XmlFixData data)
    {
        try
        {
            InitializePass(xml);

            using (var textReader = new StringReader(passXml))
            using (XmlReader reader = XmlReader.Create(textReader))
            {
                while (true)
                {
                    bool read = reader.Read();
                    if (!read)
                        break;
                    HandleNode(reader);
                }
            }
        }
        catch (XmlFixedException ex)
        {
            // Success - a fix was made.
            data = ex.XmlFixData;
            return XmlDoctorStatus.FixMade;
        }
        catch (Exception ex)
        {
            // Failure - the file was not fixed and could not be parsed.
            Debug.WriteLine("Fix Failed: " + ex.ToString());
            data = null;
            return XmlDoctorStatus.FixFailed;
        }
        finally
        {
            EndPass();
        }
        // No fix needed.
        data = null;
        return XmlDoctorStatus.NoFixNeeded;
    }
}

public static class TextHelper
{
    public static void NormalizeLines(string text, out string newText, out List<int> lineIndices)
    {
        var sb = new StringBuilder();
        var indices = new List<int>();

        using (var sr = new StringReader(text))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                indices.Add(sb.Length);
                sb.AppendLine(line);
            }
        }

        lineIndices = indices;
        newText = sb.ToString();
    }

    public static IEnumerable<int> IndexesOf(this string str, string value, int startAt)
    {
        if (str == null)
            yield break;
        for (int index = startAt, valueLength = value.Length; ; index += valueLength)
        {
            index = str.IndexOf(value, index);
            if (index == -1)
                break;
            yield return index;
        }
    }
}

Then use it like:
public static class TestXmlDoctor
{
    public static void TestFix()
    {
        string xml1 = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<MainClass>
<PrintStatus>N</PrintStatus>
<CustomerPO> >>>> pearl <<<<< </CustomerPO>
<Description>PO# pearl</Description>
<BranchID>4</BranchID>
<PostDate>
   <Date>01/13/2015</Date>
</PostDate>
<ShipDate>
   <Date>01/13/2015</Date>
</ShipDate>
</MainClass>
";
        XName[] childlessNodes1 = new XName[]
        {
            XName.Get("CustomerPO", string.Empty),
        };
        try
        {
            TestFix(xml1, childlessNodes1);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }

    public static string TestFix(string xml, IEnumerable<XName> childlessNodes)
    {
        string fixedXml;
        var status = (new XmlDoctor(xml, childlessNodes).TryFix(out fixedXml));
        switch (status)
        {
            case XmlDoctorStatus.NoFixNeeded:
                return xml;
            case XmlDoctorStatus.FixFailed:
                Debug.WriteLine("Failed to fix xml");
                return xml;
            case XmlDoctorStatus.FixMade:
                Debug.WriteLine("Fixed XML, new XML is as follows:");
                Debug.WriteLine(fixedXml);
                Debug.WriteLine(string.Empty);
                return fixedXml;
            default:
                Debug.Assert(false, "Unknown fix status " + status.ToString());
                return xml;
        }
    }
}

This with this, your XML fragment can be parsed, and becomes:
<?xml version="1.0" encoding="UTF-8"?>
<MainClass>
<PrintStatus>N</PrintStatus>
<CustomerPO> >>>> pearl <<<<< </CustomerPO>
<Description>PO# pearl</Description>
<BranchID>4</BranchID>
<PostDate>
   <Date>01/13/2015</Date>
</PostDate>
<ShipDate>
   <Date>01/13/2015</Date>
</ShipDate>
</MainClass>


How to anonymize/mask part of string in PowerBI?

Question: Say I am creating a pie chart for customer called 'Air Holland', for this customer I would like to show the overlap with other customers in a pie chart, including customers called 'Air Hungary', 'Air Ireland' and 'Air Iceland'. Due to privacy regulations of my customers I can only show partial names, e.g. the first three or four letters of their name. 'Air Holland' thus changes to 'Air xxxxxxx'
To implement this now in my pie chart, I have created a new Column CustomerNameMasked that takes the customer name, and replaces all characters but the first four with an 'x'. Ideally I would like to use CustomerName as the Legend in my pie chart, and then the CustomerNameMasked as the label, such that the pie chart is created using CustomerName, but will show the masked names.
However, as far as I know such a label is not possible, so now I have used CustomerNameMasked as my Legend column. But since these name are not unique (e.g. 'Air Hungary' and 'Air Holland' are both 'Air xxxxxxx' in the CustomerNameMasked column), different customers are taken together.
Any ideas how to create unique masked customer names? Or another work-around to ensure that my pie chart correctly shows the data per customer, but the legend shows masked names?
Comment: How about adding a unique index / displaying the Customer ID instead?
Answer: One way of preventing anonymised names from being merged in visualisations is to make sure they are not the same.

Add a calculated column:
Anonymised = "Airline " & RANKX('MyTable','MyTable'[CustomerName],,ASC,Dense)

Result:
Airline 1
Airline 2
Airline 3
...

If you prefer x's:
Add a Anonymised_Name table,
Name             Anonymised Name
"Air Holland"    "Air xxxxxxx"
"Air Hungary"    "Air xxxxxxx "
"Air Iceland"    "Air xxxxxxx  "

Use "fake space" (alt+0160 on the numpad) to prevent PowerBI from swallowing it up. Add a relationship and use this column in visualisations.
I prefer previous option as it makes it easier to distinguish and keep track of individual customers.

If you don't care whether number of "x"s matches real name:
Anonymised_Name_2 = "Air XXXXXXX" & REPT(" ",
  RANKX('MyTable','MyTable'[CustomerName],,ASC,Dense))

(again fake space alt+0160)

Depending on what you do with your report, there is a significant risk of real customer names "leaking", so ideally you would want to anonymize your data before importing it.
Comment: Just append different number of spaces and it will be unique.
Comment: Hi @user5226582, thank you for your answer. However, I already managed to create a calculated column, and my question is not so much how to create a mask. My question is rather: how to make a pie chart using the unmasked columns, while making sure I can only see masked customer names
Comment: Not sure you can. My answer explains how to create anonymised name which won't be "taken together" when you use it in visualisations.
Comment: Yeah I understand, thanks for taking your time. The first option your describe ('Airline 1' etc.) is indeed unique, but is fully anonymous which is not wanted, I still want a partial mask to be able to identify customers when you have inside-knowledge. The second option, however, does not give me unique masked customer names, so that won't help I think!
Comment: Yeah I thought of that and although I don't like it from a esthetic point of view, it might be the best work-around! Thanks!


How to close java desktop application from .bat file

Question: I have a java stand alone application. I build a jar, and I create a .exe file from this jar file.
Then I can start the application by double click on it. Now I need to create a .bat file to close the exe program. Now I build a .bat file like this:
TASKKILL /F /PID easyManagement.exe
pause

the script is executed without error but the program easyManagement is every time on.
EDIT
In task manager I can display my program like this:

This code:
TASKKILL /IM easyManagement.exe

run without error but the application is on every time.
Answer: The keys Ctrl+C and Ctrl+Z will end the running of a batch file. Check out this link: Is there a way to write Ctrl-C in a batch file?
Comment: You got it backwards - they try to kill a DESKTOP application FROM a batch script, not kill a batch script.
Comment: I don't understand what the ctrl c and ctrl z commands have to do with it?
Comment: Yes I shoudl to kill desktop application from batch script
Comment: The link explains how to stop a batch file from running, from within a batch file.
Answer: You are using a wrong parameter for the taskkill command.
The /PID expects a pid and not the name of the program you want to stop.
Use TASKKILL /IM easyManagement.exe
or TASKKILL /F /IM easyManagement.exe to force the program to stop.
The /F might cause problems in the program you want to stop.
Comment: I think that there is a problem for my program write in java. I just edit my first question


503 service unavailable debugging PHP files

Question: I have a web server with apache 2.0 installed. It comes with Zend Server install pack.
When I'm trying to debug my php files apache serves a blank page with 503 service unavailable.
Of course slow server-side code is tying up Apache requests for far too long, but I need it to wait, until my debugging comes to end.
How can I solve this problem.
Answer: Is it timing out before displaying the error, or is the 503 error coming up right away?  Try adding a set_time_limit() command at the beginning of your script  to see if that gives it time to finish.  I think the default timeout is only 30 seconds.
Comment: Thanks, Ryan.
When I call to page from a browser it launches ZendStudio debugging my PHP script (request redirects Zend Debugger module). I debug through my script and if I finish debugging in 120 seconds, I normally return to browser. When it takes more than 120 seconds browser displays 503 503 service unavailable and I can't return to page output. I have even forced 'max_execution_time = 300' 'max_input_time = 600' in php.ini and 'TimeOut = 500' in httpd.conf.
No matter it is Opera, IE of Firefox.
Spent two days googling it, no right answer till now.

Sergey.
Comment: @Ryan Hamilton: The right command to remove timeout is `set_time_limit(0);`


Dynamically Caclulated Values with Entity Field Query

Question: Is there any way to query by dynamically calculated values using Entity Field Query? Take the following:
I want to query where the sum of field_some_number and a user-provided variable are greater than or equal to 5. Right now I'm only able to do the following:
$my_variable = -7;
$query->fieldCondition('field_some_number', 'value', 5, '>=');

But obviously this doesn't include my user-provided variable. How can I calculate this on the fly? Could hook-query-alter help me with this? I have not been able to figure out how to properly implement it. I'm using this with the Restful-Drupal module.
Answer: I don't think Entity Query supports expression.

In your case, I think you might not even need it as you can workaround.
$value_to_compare = 5 - $user_provided_value;
$query->fieldCondition('field_some_number', 'value', $value_to_compare, '>=');
But if you need to compute value based on columns of database table, you can go ahead with db_select, where you can have addExpression for calculation.
$query->addExpression('table_columns_1 + table_columns_2', 'sum');
$query->having('sum', 5,'>=');
Comment: Makes sense, was hoping to stick with EFQ. Also, my example might not have been the best, but imagine you wanted a more complex query where `field_some_number * field_another_number >= 50`. Is there any way to combine `db_select` with EFQ or do I need a totally new query?
Comment: total new query


Are there any custom block type template naming conventions?

Question: With our ability to create custom block types and manually add additional fields in Drupal 8, is there a simple naming convention to create block--custom_block_type.html.twig to handle the layout of additional fields?
Example: using theme hook suggestions for content types: node--content_type.html.twig
Are custom block types able to be handled this way without going the module route?
Answer: Here's one way to do it, in a module or theme:
function MYMODULEORTHEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
    $suggestions[] = 'block__' . $content['#block_content']->bundle();
  }
}

Results in template suggestions like:
block--custom-block-type.html.twig
The instanceof might be overcautious, take it or leave it.
Comment: I'm surprised this functionality isn't in core.
Answer: This page gives a very good overview of drupal 8 naming conventions, also for custom blocks:
Drupal 8 - Template naming conventions
This page says about block templates:

For example, "block--block--1.html.twig" would be used for the first
  user-submitted block added from the block administration screen since
  it was created by the block module with the id of 1. Region-specific
  block templates are not available in Drupal 8.
If you had a block created by a custom module called "custom" and a
  delta of "my-block", the theme hook suggestion would be called
  "block--custom--my-block.html.twig."
Also one more example with Views, if you have a block created by views
  with a view name "front_news" and display id "block_1" then the theme
  hook suggestion would be:
  block--views-block--front-news-block-1.html.twig (notice, when you
  have underscores in a display id or in a view name - you have to
  transform them in to a single dash)
Be aware that module names are case sensitive in this context. For
  instance if your module is called 'MyModule', the most general theme
  hook suggestion for this module would be "block--MyModule.html.twig."

Hope that helps. Have a nice day.
Comment: Sorry if I'm misunderstanding, but it looks like you're asking whether you can extend Drupal's default template suggestions without using a module? The answer's yes, but you'll still need to implement [`hook_theme_suggestions_alter()`](https://api.drupal.org/api/drupal/core!modules!system!theme.api.php/function/hook_theme_suggestions_alter/8) in a theme. If you're looking for more advanced suggestions already built into core than are listed on the linked page, I think you're out of luck at this time
Comment: Very familiar with this page.  In regards to the block section, it is geared more for creating modules.  We understand this process.  What I'm looking for is whether or not we can apply .html.twig without having the need for modules.  I appreciate the response.
Comment: @Clive Yes, that is what we're looking to do. Thanks for the response.
Answer: @Cottser answer works. I just modified it to keep the right specificity using array_splice, otherwise the bundle type template gets applied later in the chain than block instance suggestions.
$suggestion = 'block__' . $content['#block_content']->bundle();
array_splice( $suggestions, 2, 0, $suggestion );

There is an issue to fix this in core for all entities
https://www.drupal.org/node/2270883
Answer: A simple/more precise usage with block type along with view mode is as below:
/**
  * Implements hook_theme_suggestions_block_alter()
  */
function hook_theme_suggestions_block_alter(&$suggestions, $variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
    $suggestions[] = 'block__' . $content['#block_content']->bundle() . '__' . $content['#view_mode'];
  }
}

Answer: Not exactly as you wish, but Yes, you just need to stare it carefully.
*Make sure you have debugging mode on. Refer here to turn it on.
In my case, I have created 'Custom Block Type'
Then created two block of this block type (Just to confirm). Assigned them in a region. Then inspect any one of the block. You can see clearly in attached image, there is a template suggestion(marked red) which is common for both the block.


fitting "accumulate" data

Question: I am trying to find the best function to fit my data. I have an image where items fall inside a circular region. My x values represent the radius of a circle, as x increases, the number of items (y values) that fall into it increases. So, y values are accumulated until all of the items are included. After normalization, y always ends at 1.
A sample data looks like this:
What function should I use to get the best fit? Initially, I thought Poisson. Here But it doesn't seem correct.
Answer: I proposed the function below. The explanation of the calculus with the OP's data is given as a previous answer in : https://stackoverflow.com/questions/66110390/fitting-commutative-poisson-distribution-in-python-doesnt-seem-correct?noredirect=1#comment116891714_66110390
Answer: Another and even simpler function :

fitting "accumulate" data


Is $f$ monotone when $f$ is concave?

Question: Let $f:[1, +\infty)\rightarrow\mathbb{R}$ be a concave function. Suppose $F:[1, +\infty)\rightarrow\mathbb{R}$ is a primitive function of $f$. My questions are:

(a) What other condition is required to monotone $f$?

(b) Is $F$ concave?
I know that, suppose $f$ is differentiable on $(a, b)$. Then $f$ is concave if and only if $f^\prime$ is decreasing. Also,
$f$ is concave, then for any $x$ and $y$ in the interval and for any $\alpha \in [0,1]$

$f(\alpha x + (1 - \alpha)y) \geq \alpha f(x) + (1 - \alpha)f(y)$.
Comment: (a) the condition is that $f$ must be monotone. (b) $F$ is concave only when $f$ is monotone.
Comment: Crostul, For (a) I want to get a condition to monotone $f$.
Comment: You recieved 2 answers to your question. Is any of them what you needed? If so, you should upvote all the useful answers and accept the answer that is most useful to you.
Answer: For (a), I don't think a simple answer exists. Concavity and monotonicity are fairly unconnected properties. You can have concave monotone, concave non-monotone, non-concave monotone or non-concave non-monotone functions.
For (b), the answer is a simple no. For example, $f(x)=-3(x-5)^2$ is a concave function, however its integral, $F(x)=-(x-5)^3$, is not a concave function.
Comment: Than you. For (b) What condition is required for concave $F$?
Comment: @koohyareslami If $f$ is decreasing, then $F$ is concave.
Comment: Since $F^\prime = f$ and $f$ is decreasing, so $F^\prime$ is decreasing. Thus $F$ is concave. Is it true?
Comment: @koohyareslami Exactly.
Comment: 5xum . Thank you so much.
Answer: For a), you can use something along those lines:
$$\lim_{x \to -\infty} f^\prime(x) < 0$$
Having that and concavity $f^{\prime\prime}(x) < 0$, you can easily conclude that $f^\prime(x) < 0$, so f is a decreasing concave function.
There's also the symmetric case, which yields an increasing concave function:
$$\lim_{x \to \infty} f^\prime(x) > 0$$
Comment: Todor Markov. You mean that if $f$ is concave and $\displaystyle{\lim_{x\to\infty}}f^\prime(x)<0$, then $f$ is monotone.

Is $f$ monotone when $f$ is concave?


Excel Formula to highlight range based on date range

Question: I'm trying to figure out how to create a formula to call out an entire range where there is a date less or equal to today's date.
In this example, I have a number 600259 (Column A) where there are dates that are less than today's date. I would like my formula to mark ALL as true instead of just the rows where the dates are less than.

My current formula is:
<code>=COUNTIFS(A:A,A60,I:I,I60)
</code>
<code>=COUNTIFS(A:A,A60,I:I,"<=12/7/2023")
</code>
I know I'm close but I think I need a second set of eyes to help
Comment: Then don't test the date.
Answer: I may be misunderstanding your question but if you want to mark all dates in the past (less than today) try doing this instead
<code>=IF(A1 >= TODAY(),TRUE)
</code>
where A1 is the date you want to check
you can then count the ones that are true with:
<code>=COUNTIF(A:A,TRUE)
</code>
A being your date column
if you want to you can combine them both into:
<code>=COUNTIF(A:A,">="&TODAY())
</code>
Hope this helps
EDIT: after you explanation I believe this is what you're looking for:

Using the formulas from above you'll need to add a few new columns either in this sheet or an auxiliary one.
An ID column, a COUNT column and a IF column but you can merge this last pair
For the count column you'll need:
<code>=COUNTIFS(I:I,">="&TODAY(),H:H,K3)
</code>
where I is the date column and H is the ID column
for the if you'll just need:
<code>=IF(L3>0,TRUE)
</code>
where L3 is the count right beside it
you can merge this two into:
<code>=IF(COUNTIFS(I:I,">="&TODAY(),H:H,K3)>0,TRUE)
</code>
Comment: Sorry should have been more specific. the Date column is column I. ID numbers which each have a range of dates. If any of those dates within that same ID number are less than today's date I want them all to say TRUE. Otherwise all to say False. Hopefully that helps but your answer does give me some ideas.
Comment: @Deke fair enough, I just don't understand exactly how the IDs work with the date, do you want to make a function that checks if any of the dates within a single ID are in the past to label that ID as "TRUE"?
Comment: Yes that is exactly what I'm trying to do.
Comment: Exactly what I was hoping for thanks for your help! I think I was stuck on the countifs too much


Can I use Log Loss to solve a non-linear Classification task?

Question: Assume the following data, where the yellow points represent class $1$ and the purple points represent class $2$. I would like to know, if it is possible to build a linear classifier (sigmoid) by transforming the data accordingly?

To get some intuition for the log loss in combination with the sigmoid function, I have tried to classify the data by adding only $1$ dimension for the bias.
Data :
func = lambda x: np.sin(x) - 0.5 * x ** 3
x1 = np.linspace(-1.5, 1.5, 100)

class1 = np.random.uniform(0.5, 1, size = 50) * 0.5
class2 = np.random.uniform(-1, -0.5, size = 50) * 0.5
class_concat = np.concatenate([class1, class2])
np.random.shuffle(x1)
np.random.shuffle(class_concat)

x2 = func(x1) + class_concat
x3 = np.ones(len(x2))
x = np.vstack([x1, x2, x3]).T
y = np.array([0 if val < 0 else 1 for val in x[:, 1]])

Model:
def sigmoid(z):

    return 1 / (1 + np.exp(-z))

def log_loss(pred, label):

    return - np.sum((label * np.log(pred)) + (1-label) * (np.log(1 - pred))) / 100

w = np.random.uniform(-0.1, 0.1, size=(3, 1))
num_epochs, lr = 500, 0.004

for _ in range(num_epochs):

    z = x @ w
    pred = sigmoid(z)
    loss = log_loss(pred, y)
    grad = -(1/100) * x.T @ (sigmoid(z) - y[:, None]) #
    w = w - lr * grad
print(f'loss after {_+1} epochs: {loss}')

As expected, using $3$ weights, ($1$ bias), I do not get good seperation:

My idea was now, to transform the data, for example by expanding it to some polynomial, and thus using more weights:
$ X = w_0 + w_1x + w_2x^2 + w_3x^3 .... w_{n}x^n$. In theory, I intuitively think this could work, since I allow the model a lot of flexibility for each weight to minimize the loss, but it seems hard to optimize the loss function using gradient descent. I would appreciate any input that could guide me in the right direction!
Answer: YES
The log loss corresponds to using maximum likelihood estimation for a binomial likelihood (conditional distribution) and does not care at all about the function being used to predict the probability. Logistic regression often uses log loss. Neural networks often use log loss. A logistic regression with nonlinear terms like polynomials or splines could use log loss (I think you intend to do this). It's even theoretically possible (even if challenging) to use log loss for a linear model of the probability (whereas logistic regression is a linear model of the log odds but a nonlinear model of the probability).
Comment: Interesting. But wouldn't it be problematic for example to use a constant learning rate for, for example, $30$ weights? I would like to try to decrease the loss on my own, rather than using libraries in the beginning.


Do not understand the solution to this orthogonal projection finding question

Question: There are a number of things I do not understand about this solution:

How do we know $v-x$ is colinear with the normal vector? In an earlier question, we were given that $x$ is a point in $n$-dimensional space. That is all the information we have for $x$. As far as I can understand, $v$ and $x$ are just two random points in space, so how do we know the vector between them is colinear?

So I get that $\lambda$ is the length of the orthogonal projection and $\theta$ gives the direction.But why is $\theta x+\theta_0=0$? It said '$x$ lies in the plane', but again the only info we were given was that $x$ is a point in space, so where does this come from? (In fact what does lying in the plane mean? I get how a point lies on a plane, but not lying in a plane)

Apology for these seemingly amateur questions as I am still trying to learn this stuff.

(These come from MITx 6.86x)
Answer: (1) I'm guessing that $x$ is their notation for the projection of $v$ onto the plane $\cal P$. In that case, $v - x$ would be pointing in the normal direction and hence collinear with $\theta$.
(2) Again, now that $x$, the projection of $v$ onto the plane, lies in the plane, it must satisfying the plane's equation: $\theta \cdot x + \theta_0 = 0$.


lasso coefficients larger than 1

Question: I am comparing lasso implementation in liblinear and glmnet and I can see one of the coefficients from  liblinear fit is larger than 1 , while for the same data set, glmnet coefficients are all between -1 and 1.
Since the data is normalized, I was curious if coefficients in these models can be outside the range of [-1, 1] and if not, does it mean something is wrong ? e.g the optimization has not converged ?
I appreciate more insight,
Answer: Standardizing or normalizing predictors doesn't affect the range of the coefficients, which in linear regression and most of its descendants (such as the lasso) is always $(-∞, ∞)$. You're confusing the range of the predictors with the range of the coefficients.

lasso coefficients larger than 1


Limits of Rolle theorem

Question: I would like to see a function $f:[a,b]\to\mathbb{R}$ that is differentiable in $(a,b)$ but it is not continuous at least at one of the interval boundary points $a$ or $b$. Can you show me one?
This is a curiosity that would make me to see limits of Rolle theorem, because one of its hypothesis is that the function $f$ has to be continuous in the entire closed interval $[a,b]$, even if it could be differentiable only in the open $(a,b)$.
Thank you.
Comment: What is the question?
Comment: I think the question is pretty clear: "why can we not relax the requirement of continuity on $[a,b]$ in Rolle's theorem?".
Comment: Essentially if $f$ is not continuous at both $a$ and $b$ then knowing $f(a)=f(b)$ is not helpful information.  But you need that to avoid strictly monotonic functions
Comment: The first phrase. I edit to make the question clearer.
Comment: @PatrickStevens I was truly unsure what the OP was intending to ask. The reply to my comment made even less sense. I am not sure how you have the ability to read peoples minds through what they write, but OK.
Comment: I can not understand how my simple answer "the first sentence is my question" could not make sense, but OK.
Answer: Consider $f(x) = x$ on $(0, 1]$, and $f(0) = 1$.
Comment: In first-year analysis, there are about five different counterexamples, all of them quite simple. Almost nothing you'll encounter will require really pathological counterexamples.
Comment: Who knows for what obscure reason I was imagining things incredibly more complex than that. Thank you very much. Sorry for the question that now seems very stupid to me.
Answer: Consider $f(x) = \frac{1}{x}$ in $[0, 1]$ and define $f(0) = 0.5$.
Then by the extreme value theorem - which is needed to make Rolle's Theorem work - since $f$ doesn't obtain a maximum, $f$ is not continuous on $[a,b]$.

Limits of Rolle theorem


a question on : why sin(x) = sin(180-x)

Question: I was trying to follow a proof from another question in this forum:
Why is $\sin(x) = \sin(180^{\circ}-x)$
I was following the geometric proof given by forum poster : egreg.
I could follow his proof for the cosine.
But I think the proof for the sine contains an error.
Egreg stated that from the triangle in the circle you get the following:
sin(alpha)/a = 2R
BUT when I analyzed the small triangle with angle alpha in it, I get:
sin(alpha)/a = 1/2R
It really doesn't affect the proof much at all.
But I am wondering if there was an error, or there is something wrong with my
own trig analysis.
Hope that the forum guy Egreg can reply since he is the originator of this proof.
Regards,
P
Comment: Thanks for noting; I fixed the error.
Comment: Hi Egreg, thanks for your response. BUT can you make a picture of the point A' (A prime diametrically opposite A), because I am having difficulty understanding how to construct this new triangle to show that in this new triangle we have the angle "180-alpha". Really appreciate it if you can do that. Sincerely P.
Comment: In a quadrilateral inscribed in a circle, the opposite angles always sum to 180°.
Comment: Hi Egreg, Thanks so much! Yes, that is the geometric fact that I was missing: In quadrilateral inscribed in a circle the opposite angles sum to 180 degrees! After I created the quadrilateral with A' diametrically opposite and the angle at A' being alpha prime, the proof became crystal clear!!! Thanks so much once more! Sincerely Palue
Answer: You are correct. Recall the Law of Sines, which states $\dfrac{a}{\sin A} = \dfrac{b}{\sin B} = \dfrac{c}{\sin C} = 2R$. This means $\dfrac{\sin A}{a} = \dfrac{1}{2R}$. This is probably a typo on his part; it doesn't affect the proof at all. The section of the proof you are referring to is just simply a clever proof of the Law of Sines.
Comment: Hi there, yes and thanks for the response. Yes I do recognize egregs method based on the Sine Law. BUT in Egregs re-doing the problem he made another error he now put: asin(A) = 2R. I think in that post he forgot to put the divide sign, a/sin(A) = 2R.

a question on : why sin(x) = sin(180-x)