Q:

Adobe illustrator: basic editing questions (break apart)

I have some experience with Flash/Gimp/Photoshop, but now I have to edit an FXG file (an asset for a Flex app) in Adobe Illustrator and can't do even the two basic things, shown in the screenshot below:

I need to double the size of the clubs symbol in the middle while maintaining its central alignment
I need to change the indices in the corners (by different text)

but I can't even select the clubs symbol or the indices! Whenever I click and drag - I select and move everything. Do I need to break apart like in Flash editor? Can't find it in the Adobe Illustrator menu.
UPDATE:
Thank you Scott, this has worked after the Ungroup.
I wonder though, why can't I select anything in the layers window (I realized after some time that there are indeed several layers already). I click on a layer, but nothing is selected.
I'm asking, because I want to place the new text symmetrically.

A:

Select the club symbol with the Direct Selection Tool (the white arrow -- click, don't drag). Then double-click the Scale Tool in the Toolbar and enter your desired percentage for increase.
You'll need to delete the "A" and reset a new character. That type has been converted to outlines and is no longer editable text.

As for the "break apart"... There is Object > Ungroup after you've selected the objects.
Layers Question
Illustrator layers don't work like Photoshop layers. Selecting and highlighting layers in Illustrator lets you move, copy, or delete the actual layer in the Layers Panel. It does not select the objects on any particular layer.
If you want to select the objects on a layer, click the circle to the right of the layer's name. You'll see a small square highlight appear. That will indicate objects on that layer are selected.
The layer functionality difference is basically the difference between an object-oriented app like Illustrator and a raster app like Photoshop.


Q:

atOffset utilizando map

    private OffsetDateTime getDataDistribuicao() {
    return Optional.ofNullable(this.getPaginaInfoGerais())
            .map(page -> page.<HtmlTableCell>getFirstByXPath(XPATH_CEL_DATA_DISTRIBUICAO))
            .map(HtmlTableCell::getTextContent)
            .map(str -> replaceAndTrim(str))
            .map(str -> getDataDistribuicao(str))
            .map(str -> LocalDateTime.parse( str, DateTimeFormatter.ofPattern(PATTERN_DATA_HORA)))
            .map(LocalDateTime::atOffset(ZoneOffset.UTC));
}

No último map eu recebo o erro:

non static method cannot be referenced from a static context

O que fazer?

A:

O jeito que encontrei foi esse, deu certo:
    private OffsetDateTime getDataDistribuicao() {
    return Optional.ofNullable(this.getPaginaInfoGerais())
            .map(page -> page.<HtmlTableCell>getFirstByXPath(XPATH_CEL_DATA_DISTRIBUICAO))
            .map(HtmlTableCell::getTextContent)
            .map(str -> replaceAndTrim(str))
            .map(str -> getDataDistribuicao(str))
            .map(str -> LocalDateTime.parse( str, DateTimeFormatter.ofPattern(PATTERN_DATA_HORA)).atOffset(ZoneOffset.UTC))
            .orElse(null);
}


Q:

Location data (especially France)

guys. I am developing a project that requires a strict location of a user ( country, state (or department or region) and city (with postal code). The idea is that I do not want to allow user input, as people (especially french people) tend to ignore autocompletes and write all uppercase with some variations (e.g. PARIS01, PARIS, PARIS 01, LYON (Nord)), so their location data is pretty messed up. On the other hand, I have to provide a complete list of cities in all countries to be able to force them select a city and disable manual input.
Anyway, can you help me with some sources of location data ( better free or cheap) or tell me what are the advantages of expesive databases ?

A:

Few years ago I was developing some financial application that used Zip codes and addresses heavily. I bought zip code data base issued by Polish Post (one CD). I am not sure if such thing exists for France, but I believe Postal services companies' web sites could be a good place to start.


Q:

History of Embedded Software

As far as I understand it, embedded software is just software (that runs on a general purpose CPU) that has little if any user input or configuration.  Embedded software powers IP routers, cars, computer mice, etc.
My question is:
When (roughly) was the historical moment when embedded software was first considered cost-effective for some applications (rather than an equal technical solution not involving embedded software)?  Which applications and why?
Detail: Obviously there is a tradeoff between the cost of a CPU fast enough to perform X in software versus the cost of designing hardware that performs X.

A:

Embedded systems date from the Apollo moon landings.  Specifically the Apollo Guidance Computer (AGC) - widely held to be one of the first examples of embedded systems.
Commercially in the early 1970's early microprocessors were being employed in products, famously the 4-bit Intel 4004 used in the Busicom 141-PF.  Bill Gates and Paul Allen saw the potential for embedded microprocessors early with their pre-Microsoft endeavour the Traf-O-Data traffic survey counter.
So I would suggest around 1971/72 at the introduction of the Intel 4004 and the more powerful 8-bit 8008.  Note that unlike the more powerful still Intel 8080 which inspired the first home-brew microcomputers and the MITS Altair, the 4004 and 8008 were barely suitable for use a general purpose "computer" as such, and therefore embedded computing systems pre-date general purpose microcomputers.
I would dispute your characterisation of what an embedded system is; if you were asking that question here's my answer to a similar question.


Q:

Value at Risk for portfolio with different maturities

I am new to StackExchange and relatively new to quantitative finance.
I work at a commodity trading company and we have an extensive portfolio of futures and options on commodities (traded on the CME, EEX and NZX). We are trying to implement a Value at Risk model in order to quantify the risk on our outstanding positions. In order to do this I am using the historical method. Namely, for each instrument I have 200 historical time series data points. From those I compute the daily returns (in absolute dollar value). This leaves me with 199 returns. For options I multiply the daily dollar returns of the underlying by the delta of the option in question and add 1/2*gamma*returns**2. I add all the returns calculated in this way leaving me with 199 total portfolio returns. From here it is easy to pick the lowest 5 percentile.
But here comes the kicker. I attached a picture below in order to convey more understanding and hopefully foster a better response. Assume I have a portfolio with 3 futures. One matures at the end of February, one at the end of March, and one at the end of April.

If I want to calculate the 20-day VaR, so how much we could loose by the 20th of February (assuming today is the 31st of January), then I follow the procedure I described above with the historical returns of the 3 futures. I will get a 1 day VaR which I multiply by sqrt(20) to get the 20-day VaR. Simple enough. Now our CFO says that if we need to calculate the 49-day VaR (leading us to the 20th of March) we should somehow take into account the fact that Future 1 matures at the end of February and that from the 1st of March to the 20th of March the risk is only 'given' by Future 2 and 3.
My question is, is this somehow possible to do with VaR? Is this correct? I recall reading somewhere that an assumption of VaR is that the portfolio's composition does not change over the holding period.
If someone could help clear up this doubt it would be immensely helpful. Thank you in advance!
EDIT 11/02/2020:
If VaR is indeed not the proper method for my question could someone suggest a possible alternative way of tackling the problem? Thank you!

A:

That is not the traditional representation of VaR. Normally, a VaR measure reflects the current risk exposure of the portfolio and measures its loss based on market movements, i.e. via an instantaneous shock to those positions, whether those market movements are supposed to reflect 1-day, 5-day, 50-day or 1-year, for example.
Generally VaR does not account for evolution of trades, i.e. new trading and existing maturities. For example suppose you have a large position in the Feb contract, hedged by an equivalent position in the March contract, giving rise to a reasonably small risk exposure overall. This might be typical of the trading style you employ, but historically you have never left the March contract 'naked' after the Feb contract expires: it has always been closed simultaneously as Feb matured. If the March contract was left 'naked' your VaR might increase 10-100 times, but by closing simultaneously you reduce it to zero.
Therefore VaR, as a model, is not required to make these assumptions. For some trading portfolios, where the liquidity of the positions as they expire is difficult to re-hedge, these concerns (as an additional risk consideration outside of VaR) can be useful, but they are not common, fairly nuanced, and not well known. I have for example used a statistical process for use in fixing risk of LIBOR exposures as they roll off on a daily basis, but this risk has always been excluded from my VaR calculations.
EDIT
Essentially a better characterisation of risk is to calculate the 1d-horizon VaR for every day in the next say 180 days (6m) using a forward forecast portfolio, and then statistically aggregate the values. E.g assume the PnL over the next 180 days is the sum of 180 (daily) random variables whose variance has been individually assessed via portfolio risk forecasting.


Q:

python / opencv3 double thresholding (up and down)

I'm new to python and opencv. I want to load an image (grayscale) and do some special thresholding. I want to keep brightness values between 20-30 as is and make zero (or 255) all other pixel's values. I mean pixels with brightness value below 20 and over 30.
I made some tests with inrange but no luck. I also tried the following but it only does half the job:
ret,img = cv.threshold(img,30,255,cv.THRESH_BINARY)

Any suggestion?

A:

You can use the cv2.inrange() module. The minimum and maximum value can be placed for any image.
In your case since you are using a single-channeled image you can perform something like this:
masked = cv2.inRange(im, 20, 30)
cv2.imshow('masked',masked)

In your question you have mentioned that cv.threshold() does half the job. You need to do it twice and subtract the resultant to get the full job done!
ret1, img1 = cv2.threshold(im, 20, 255, cv2.THRESH_BINARY)
ret2, img2 = cv2.threshold(im, 30, 255, cv2.THRESH_BINARY)
cv2.imshow('double_threshold', img1 - img2)


Q:

Linkedlist remove method erroe

when i try to remove element there is an error, i have uploaded the error in the image section. any help to fix? of any other way to get the code fixed and working smoothly and it it works while deleting the middle element not the first or second
duplication issue ,fixed using iterator. hatsooff to stack overflow .
all good
import java.util.*;

public class EarthquakeList {
private ArrayList<EarthquakeNode> records;

public EarthquakeList() {
   records = new ArrayList<EarthquakeNode>();

}

public boolean isempty() {
      return true;
}

public void add(String EarthquakeLo,String EarthquakeDt, double EarthquakeSgth, int EarthquakeDu) {
   EarthquakeNode en = new EarthquakeNode(EarthquakeLo, EarthquakeDt, EarthquakeSgth, EarthquakeDu);
   records.add(en);
}

public boolean remove(String EarthquakeLo,String EarthquakeDt) {
   boolean flag= false;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {
               records.remove(earthquake);
               flag=true;

           }
       }
   }
   return flag;
 }

 public EarthquakeNode search(String EarthquakeLo,String EarthquakeDt) {
   EarthquakeNode node= null;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {

               node=earthquake;
           }
       }
   }
   return node;
}

public boolean clear() {

   int count=records.size();
   for(EarthquakeNode earthquake: records)
   {
       count=count-1;
       records.remove(earthquake);

   }
   if(count==0)
   {
   System.out.println("already empty");
   return false;}

   else
   System.out.println("every thing is removed");
   return true;
}

public boolean isempty(String EarthquakeLo,String EarthquakeDt) {
   boolean flag= false;
   for(EarthquakeNode earthquake: records)
   {
       if(earthquake.getLocation().equalsIgnoreCase(EarthquakeLo))
       {
           if(earthquake.getDate().equals(EarthquakeDt))
           {
               flag=true;
           }
       }
   }
   return flag;
}

public void print() {
   for(EarthquakeNode earthquake: records)
   {
       System.out.println( earthquake.getLocation() +" - "
              + earthquake.getDate()+ " - "
               + earthquake.getStrength() + " on rector scale"+
               "-" + earthquake.getDuration() + "mins");
   }

}

}

A:

You need to use an Iterator to safely remove from a collection while iterating over it.
public boolean remove(String earthquakeLo, String earthquakeDt) {
   boolean flag= false;
   Iterator<EarthquakeNode> iterator = records.iterator();
   while(iterator.hasNext()) {
      EarthquakeNode earthquake = iterator.next();
      if(earthquake.getLocation().equalsIgnoreCase(earthquakeLo)) {
           if(earthquake.getDate().equals(earthquakeDt)) {
              iterator.remove();
              flag=true;
           }
      }
   }
   return flag;
 }


Q:

Is perpetual virginity or remaining unmarried superior to marriage?

In Hinduism, is perpetual virginity or remaining unmarried a higher state of life than marriage?

A:

Yes, if you're willing to do it, lifelong Brahmacharya has great benefits, at least for Brahmanas.  Here is what this  of the Manu Smriti

But if (a student) desires to pass his whole life in the teacher's house, he must diligently serve him, until he is freed from this body. A Brahmana who serves his teacher till the dissolution of his body, reaches forthwith the eternal mansion of Brahma.... (A perpetual student) must, if his teacher dies, serve his son (provided he be) endowed with good qualities, or his widow, or his Sapinda, in the same manner as the teacher. Should none of these be alive, he must serve the sacred fire, standing (by day) and sitting (during the night), and thus finish his life. A Brahmana who thus passes his life as a student without breaking his vow, reaches (after death) the highest abode and will not be born again in this world.

But it's certainly not a required Dharma; the next chapter of the Manu Smriti describes the procedure for a Brahmachari to become a Grihasti:

The vow (of studying) the three Vedas under a teacher must be kept for thirty-six years, or for half that time, or for a quarter, or until the (student) has perfectly learnt them. (A student) who has studied in due order the three Vedas, or two, or even one only, without breaking the (rules of) studentship, shall enter the order of householders. He who is famous for (the strict performance of) his duties and has received his heritage, the Veda, from his father, shall be honoured, sitting on a couch and adorned with a garland, with (the present of) a cow (and the honey-mixture).
   Having bathed, with the permission of his teacher, and performed according to the rule the Samavartana (the rite on returning home), a twice-born man shall marry a wife of equal caste who is endowed with auspicious (bodily) marks.

A:

Yes, it is superior. Although in Hinduism faithfully following the path of a married person is way of dharma, scripture says brahmacharya, especially lifelong celibacy, is superior.
The Mahanarayana Upanishad says (78.12):

Brahma Hiranyagarbha considers that sannyas is the means to liberation. Hiranyagarbha is indeed the Supreme. The Supreme alone is Hiranyagarbha (although he is a personality). Certainly those austerities set forth above are inferior [other austerities listed in the preceding verses of this section]. Sannyasa [monks who have taken vows of celibacy] alone surpasses all. To him who thus knows the all-transcending excellence of sannyas precious knowledge is imparted.

and at the end of his commentary on this verse, Swami Vimalananda states:

Sri Sankaracarya at Brahma Sutra III.4.20 (Available here - https://www.wisdomlib.org/hinduism/book/brahma-sutras/d/doc62753.html) refers to this passage as the conclusive authority behind the practice of sannyas. The illustrious acarya is the most outstanding prototype of a Sannyasin. His example and teachings on the monastic tradition as the pattern of sannyas to be followed by others entering the path. A very large section of Hindus believe that sannyasa represents the perfection in religious life which is attained through the gradual progress in spirituality achieved by fulfilment of the condition laid down for the other three stages of life. Sayana states that while the qualities and practices of different aspirants described in the eleven clauses from the beginning of the Section [of this section of the Mahanarayana Upanishad] were made by human beings--learned and wise though they might be--the transcendence of sannyas over all of them is a pronouncement made by Brahma himself--the first-born-- and so it is secretly guarded precious knowledge--upanishad.

And verse 79.16 concludes with:

O Aruni, having become one possessed of knowledge by realizing Him, the Supreme, through sannyasa, and with your mind fixed in the heart, do not again fall a prey to death. Because sannyasa is thus the supreme means of realization, therefore wise men declare that to be above all other means of liberation.

Sannyasa is extolled in Brahma Sutras III.iv.18-20. (Link given previously) with Sankara's commentaries:

18. Jaimini (thinks that in the texts referred to in the last Sutra there is) a mere reference (to Sannyâsa), and not injunction, because (other texts) condemn (Sannyâsa).
In the text quoted in the last Sutra (Chh. 2. 23. 1) Jaimini says that as there is no word showing that Sannyâsa is enjoined on man, it is a mere reference and not an injunction. The Brihadâranyaka text quoted in the last Sutra says that some person do like that. Sruti here makes a mere statement of fact. It does not enjoin Sannyâsa. Moreover, the text here praises steadfastness in Brahman. “But only one who is firmly established in Brahman attains immortality.” Sacrifice, study, charity, austertiy, studentship, and lifelong celibacy result in the attainment of the virtuous world. But immortality is gained only by him who is firmly established in Brahman. That is what the text says. Further, there are other texts which condemn Sannyâsa. “Having brought to your teacher the wealth that he likes, do not cut off the line of progeny” (Taitt. 1. 11); “To him who is without a son (this) world does not belong” (Taitt. Br. 7. 18. 12) and so on.
19. Bâdarâyana (thinks that Sannyâsa or monastic life) also must be gone through, for the scriptural text (cited) refers equally; to all the four Âsramas (stages of life).
In the text cited, sacrifice etc. refer to the householder’s life, penance to Vânaprastha, studentship to Brahmacharya and ‘one who is firmly established in Brahman’ to Sannyâsa. So the text equally refers to all the four stages of life. The text relating to the first three stages refers to what is enjoined elsewhere. So also does the text relating to Sannyâsa. Hence Sannyâsa also is enjoined and must be gone through by all.
20. Or rather (there is an) injunction (in this text), as in the case of the carrying (of the sacrificial fuel).
This Sutra now tries to establish that there is an injunction about Sannyâsa in the Chhândogya passage cited. There is a Sruti text referring to Agnihotra performed for the manes, which runs as follows: “Let him approach, carrying the sacrificial fuel below; for above he carries it for the gods.” The last clause Jaimini interprets as an injunction, though there is no word in it to that effect, because such an injunction is nowhere else to be found in the scriptures. On account of its newness (Apurvatâ) it is an injunction. Following this argument this Sutra says that in Chh. 2. 23. 1 there is an injunction with respect to Sannyâsa, and not a mere reference, as it is not enjoined anywhere else. Moreover, there are Sruti texts which directly enjoin Sannyâsa: “Or else he may wander forth from the students’ life, or from the house, or from the forest” (Jâb. 4).
Again Jaimini himself says that even glorification, to be relevant, must be in a complimentary relation to an injunction. In the text cited steadfast devotion to Brahman is being praised, and so it has an injunctive value. Now is it possible for one engaged in sacrificial rites etc. to be wholly devoted to Brahman? Devotion to Brahman means constant meditation on It without any disturbing thought. Such a thing is impossible for a householder engaged in ritualistic work. It is possible only for a Sannyâsin who has renounced all work, and not for others.
Neither is it true that Sannyâsa is prescribed only for those who are lame, blind, etc., and therefore unfit for ritualistic work. The text cited above (Jâb. 4) makes no such difference. Moreover, Sannyâsa is meant as a means to the realization of Brahman, and it is to be acquired in a regular prescribed way. “The wandering mendicant with coloured dress, shaven-headed, accepting no gifts, qualifies himself for the realization of Brahman.” Therefore Sannyâsa is prescribed by the scriptures and Knowledge, because it is enjoined on Sannyâsins, is independent of work.

Sankara's commentary on 18 also references scripture on life-long celibacy, not merely after taking a vow of brahmacharya or sannyas.
Lifelong celibacy is especially extolled. In fact if you look at Brahma Sutras Chapter III, section IV contents, you will see that Adhikarana X, XI, and XII discusses those who lapse.


Q:

D3.js line transition is going out of the graph

I have a line graph where I have line transition. However on the initial graph drawing line path is ok, within the graph. But when I use the transition the line goes out of the container to the margins.
Transition function:
that.graph.select('.data-line')
     .transition().duration(750)
     .attr('fill', 'none')
     .attr('stroke', '#ff0000')
     .attr('stroke-width', 2)
     .attr('d', line);

Line:
const line = d3.line()
     .x(d => xAxis(new Date(d.n)))
     .y(d => yAxis(d.v))
     .defined(d => d.v || d.v === 0);

Axes:
const xAxis = d3.scaleTime()
                .range([0, width])
                .domain(xDomain);

const yAxis = d3.scaleLinear()
                .range([height, 0])
                .domain(yDomain);

Domains:
const yDomain = d3.extent(data, d => d.v);
const xDomain = d3.extent(data, d => new Date(d.n));

Dimensions:
const width = window.innerWidth - this.margins.left - this.margins.right;
const height = window.innerHeight - this.margins.top - this.margins.bottom;

Initial line drawing: (this is ok)
this.graph.append('g').attr('class', 'data-wrapper');

const line = d3.line()
                .x(d => this.xAxis(new Date(d.n)))
                .y(d => this.yAxis(d.v))
                .defined(d => d.v || d.v === 0);

this.graph
     .select('.data-wrapper')
     .append('path')
     .datum(data)
     .attr('class', 'data-line')
     .attr('fill', 'none')
     .attr('stroke', '#ff0000')
     .attr('stroke-width', 2)
     .attr('d', line);

Here is the screenshot:

Any help is appreciated.

A:

As @rioV8 suggested adding clip path solved issue.
If anyone in the feature has this problem here is the solution:
On your topmost SVG add this:
  this.graph.append('defs')
                .append('clipPath')
                .attr('id', 'clip')
                .append('rect')
                .attr('width', this.width)
                .attr('height', this.height);

And on the function where you draw data add
.attr('clip-path', 'url(#clip)')


Q:

Mocking throwing mongoDb exceptions in Clojure

I want to overwrite my function to throw com.mongodb.MongoException$DuplicateKey. But that class needs some object called com.mongodb.CommandResult in its constructor.
Problem is with that com.mongodb.CommandResult. No matter what I am trying to do, I end up with:

No matching ctor found for class com.mongodb.CommandResult

getConstructors says it has no constructor. But if I try to do it without parameters it's the same... Could someone point what am I doing wrong?
I really doubt it, but maybe this will be somehow helpful to understand my problem:
user=> (com.mongodb.CommandResult.)

CompilerException java.lang.IllegalArgumentException: No matching ctor found for class
com.mongodb.CommandResult, compiling:(/tmp/form-init5865306652286645706.clj:1:1)

A:

If getConstructors returns nothing, it means there are no public constructors and you cannot create an instance via regular means. You can use getDeclaredConstructors to access non-public constructors.
Before you do that though, I would suggest an alternative approach: Wrap the MongoDB client in a thin custom wrapper which a) only exposes what you need from the client, b) uses your domain-specific operation names, c) doesn't use any MongoDB-specific types on its surface (catches exceptions, propagates different results than the CommandResult etc.) It's usually much much easier to mock in your tests, can be used to hide hard-to-test APIs, and if it's thin enough, it's reasonably safe not to unit-test the wrapper itself. Integration tests or other higher-level automated tests usually simulate and cover these kinds of errors states quite well.


Q:

Why is a field with a value of 0 not the same as 0 in this formula?

We've got a report calculating margin which is pretty simple. I understand that there is no short circuiting of an IIF in SSRS. This question is focused on why there is a behavior difference between using field values in a formula, and direct values.
=IIF(SUM(Fields!Sales.Value) = 0, "N/A", 1 - SUM(Fields!Cost.Value) / SUM(Fields!Sales.Value))

This formula results in #error when Sales.Value = 0. However, if I change the formula to the following:
=IIF(SUM(Fields!Sales.Value) = 0, "N/A", 1 - 1 / 0)

This results in "N/A" like it's supposed to. So 1 - / 0 = -infinity, but dividing by a field whose value is 0 results in an error.
Why is the behavior different here?
EDIT: I'll clarify this a bit. Ignoring the IIF aspect of this, if I do:
= 1 - 1 / 0

I get -infinity. If I do (where Sales.Value = 0):
= 1 -1 / Fields!Sales.Value

I get #error.

A:

Based on VB documentation, the Double data type is the only data type that does not throw the DivideByZeroException.  But since you've clearly used two Int's, something else is going on here.
After some searching I found this answer to a related but different divide-by-zero question, which has a great explanation:

VB.NET does things a little bit differently; integer division automatically results in a floating point value using the / operator. This is to allow developers to write, e.g., the expression 1 / 2, and have it evaluate to 0.5, which some would consider intuitive

TL;DR Fields!Sales.Value is likely interpreted as a Decimal resulting in the divide-by-zero #error, while the 1 / 0 example results in a data type of Double and displays infinity.


Q:

Play framework only Error: object httpclient is not a member of package org.apache.commons

I have two import in scala on play framework. However play keep telling "me object httpclient is not a member of package org.apache.commons". I did add commons-httplclient.jar as external jar in .classpath(in eclipse). I created a console application in eclipse to verify and there is no error at all when importing these two objects and calling their methods. What is special of play that it cannot find httpclient object?
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.methods.StringRequestEntity

A:

You need to declare the dependency to the library in the build.sbt file. Ex :
libraryDependencies += "org.apache.httpcomponents" % "httpclient:jar" % "4.3.3"

See the play documentation for more details : http://www.playframework.com/documentation/2.2.x/SBTDependencies


Q:

How to create charts in iOS app like this?

chart
How create create charts in iOS app like this?

A:

You can use this pod:
https://cocoapods.org/pods/Charts
its simple, and efficient


Q:

Calling a variable into main function - Jython

I'm an newbie playing around with JES and I'm testing how to call a variable in from another function to the main function. I'm using return which from what I understand should return variable num but it's still erroring :( Any guidance would be most appreciated.
def update():
  a = sqrt(10)
  b = 239
  getTotal(a,b)
  print num

def getTotal(a,b):
  num = a*b
  return num

A:

Need somewhere for that value to return to.
Try this:
def update():
  a = sqrt(10)
  b = 239
  c = getTotal(a,b)
  print c

def getTotal(a,b):
  num = a*b
  return num


Q:

Dismissing Modal View Swift

EDIT: Thanks to the person behind the answer below, who fixed the unknown class. However, can anyone tell me if the code to dismiss is correct? I am on vacation and can't program until I get back.
I am developing an app in Swift. Currently, I am working on an info screen (legal notices, credits, documentation, etc)  that will be presented modally atop the main screen.
The expected behavior is that, when a button press triggers Dismiss in InfoViewController, the modal view controller is dismissed.
Here’s the code I’m trying to use:
//This is InfoViewController, the swift file used to conorol the info screen.

import UIKit

class InfoViewController: UIViewController {

    @IBAction func Dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: {});//This is intended to dismiss the Info sceen.
        println("pressed")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

Here’s the layout of the storyboards:

When I press the button, the app crashes and doesn’t dismiss the modal view controller.
It compiles, suggesting it is not a syntactual error.
Here’s the LLVM debugger output:

2014-08-30 20:02:20.571 CryptoCalc[799:244086] 17545849:_UIScreenEdgePanRecognizerEdgeSettings.edgeRegionSize=13.000000
  //Unrelated stuff deleted.
  2014-08-30 20:03:03.756 CryptoCalc[799:244086] Unknown class InfoViewController in Interface Builder file.
  2014-08-30 20:03:20.485 CryptoCalc[799:244086] -[UIViewController Dismiss:]: unrecognized selector sent to instance 0x14d57990
  2014-08-30 20:03:20.489 CryptoCalc[799:244086] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController Dismiss:]: unrecognized selector sent to instance 0x14d57990'
  * First throw call stack:
  (0x2238be2f 0x2f46bc8b 0x22391179 0x2238f097 0x222c11f8 0x259b9fef 0x259b9f91 0x259a4d13 0x259b99fd 0x259b96d7 0x259b2fa1 0x25989a09 0x25bfbae3 0x259884a1 0x2235257f 0x2235198f 0x2234fff5 0x2229e611 0x2229e423 0x297f80a9 0x259e8485 0x73720 0x7375c 0x2f9f1aaf)
  libc++abi.dylib: terminating with uncaught exception of type NSException

If you need any more info, let me know. Thanks so much.

A:

The main issue here is Unknown class InfoViewController in Interface Builder file.
You need to make sure that (in 'Custom Class' section)
1) The class in the storyboard is set to InfoViewController
2) The module is set to 'Current - your project name'
screen shot include to show which part of Interface builder I am referring to


Q:

ms-access: using getrows method

i am new to access and i am debugging someone's database

how do i know if i am using ADO?
i have stuff in a listbox, how do i use the .GetRows method to put the recordset into a two-dimensional array?

A:

Do you have a reference to the ADO libraries (In a code window, under Tools->References: Microsoft ADO Ext x.x For DLL and Security, Microsoft ActiveX Data Objects x.x Library) Have you set the recordset to an ADO recordset?
You will find details of GetRows here: http://www.w3schools.com/ado/met_rs_getrows.asp
You can use it like GetString, as illustrated in a reply to your previous post.
EDIT
You do not have to have a reference to the ADO libraries to use ADO, but it can be easier. To use ADO without the libraries (late binding), try something like:
Dim cn As Object
Dim rs As Object

Set cn=CreateObject("ADODB.Connection")
Set rs=CreateObject("ADODB.Recordset")

cn.Open strConnect ''Any suitable connection string
rs.Open strSQL, cn ''Any suitable SQL string


Q:

Unable to connect to powermeter through Ethernet-GPIB adapter

When i am trying to run my code i get the following error :
ValueError: Please install linux-gpib to use this resource type.
No module named 'gpib'
After trying to install linux-gpib, using pip and the command line, i get this one :
Could not find a version that satisfies the requirement linux-gpib (from versions: )
No matching distribution found for linux-gpib
I have managed to connect a signal generator through ethernet but i got no luck using the same principles with gpib.
Tried to reinstall python and the pyvisa package with no luck, tried importing a wrapper for this specific ethernet adapter :
pip install git+git://github.com/nelsond/prologix-gpib-ethernet.git
again no luck.
I also tried using the ip provided by the adapter driver to connect through TCPIP, still no luck.
import visa

rm = visa.ResourceManager()
rm.list_resources()
inst = rm.open_resource('GPIB0::16::INSTR') #using GPIB
inst = rm.open_resource('TCPIP::192.168.1.77::INSTR') #using TCPIP
print(inst.query("*IDN?"))

The executed code should provide the IDN of the device, eg :
Rohde & Schwarz,SMB100A,1406.6000k02...etc

A:

Try changing to another USB to GPIB adapter.


Q:

Sampling from a given probability distribution using R

Given the probability distribution as follows:

x-coordinate represents hours, y-coordinate means the probability for each hour.
The problem is how to generate a set of 1000 random data that follows the probability distribution?

A:

The important function is sample. You can specify an extra argument prob to sample which specifies the probabilities for each element. For example,
sample(1:22,1000,replace=TRUE,prob=c(
  0,1,0,3,7,14,30,24,5,3,3,2,4,3,1,2,3,2,2,2,1,0
)

(replace that string of numbers with the heights of your bars). The prob argument doesn't have to sum to one, R will renormalise it for you.
R may generate a warning that it is using "Walker's Alias method" and the results are not comparable to old versions of R. This is normal, and nothing to worry about.


Q:

How to ignore parseErrorOccurred when using NSXMLParser to parse xml

I'm now using NSXMLParser to parse html, but when meet "br" tag in html, it will throw an error for mismatch and stop to parse, because typically "/br" tag will not appear in html. So I want to ignore this mismatch error to continue parse, how to deal with it?

A:

Not the best solution, but you might consider to do some regex correction before parsing, such as:
$input =~ s/<br>/<br \/>/ig;


Q:

Linguistic gloss for dialogue with expex and marking the speakers

I am looking to create something that will look like this:
(1) A: word word word?
gloss gloss gloss?
translation translation translation?
B: word word word!
gloss gloss gloss!
translation translation translation!
For ordinary examples I am using expex like this:
\pex
\begingl
\gla ...
\glb ...
\glft ...
\endgl...
\xe

One thing I tried was this:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{expex}
\begin{document}
\pex<withparts>
\a<first>
\begingl
\gla Meri - mal'čik.//
\glb Mary - boy.//
\glft `Mary is a boy.'//
\endgl
\a<second>
\begingl
\gla Net, Mèri - devočka.//
\glb No, Mary - girl//
\glft `Mary is a boy.'//
\endgl
\xe\end
{document}

but it does not really work because I may need to do the gloss of a dialogue where it is speaker A - speaker B - speaker A again, but with this method I will be getting a-b-c-d...
Next I also tried this:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{expex}
\begin{document}
\pex<withparts>
\a<first>
\begingl
\gla A: Meri - mal'čik.//
\glb A: Mary - boy.//
\glc ...//
\glft ...//
\endgl
\xe\end
{document}

I thought I would be able to replicate the example in (1) by adding \glc, \gld, \gle, but evidently a b in \gla \glb do not stand for a,b,c ...

A:

If all you need to do is supply speaker labels, you can simply use the label= key for the example, and add your speaker labels there.  All that is needed is to adjust the width of the label accordingly.  To do this, I've created a command that takes your longest envisioned speaker name and adjusts the label width based on its length.
Here's a complete example:
\documentclass{article}
\usepackage{expex}
\usepackage{calc}
\newlength{\largestspkr}
\newcommand*\largestlabel[1]{\settowidth{\largestspkr}{#1~}}
\largestlabel{Speaker A}
\begin{document}
\pex[labelwidth=\largestspkr]
\a[label=Speaker A]
\begingl
\gla Meri - mal'čik.//
\glb Mary - boy.//
\glft `Mary is a boy.'//
\endgl
\a[label=Speaker B]
\begingl
\gla Net, Mèri - devočka.//
\glb No, Mary - girl//
\glft `Mary is a girl.'//
\endgl
\xe\end
{document}


Q:

how to disabled and uncheck the checkbox values from database fields..VB.NET !

Possible Duplicate:
How to disable and uncheck the checkbox values from database fields..VB.NET

how to disabled and uncheck the checkbox values from database fields..
if i have entry in my database records as :
Name          Seats           Date

Sumit         1,3             11-Dec-2010
Sanjeev       2,4             12-Dec-2010
Manish        1,3,4           11-Dec-2010

I want on page load event the default date for todays is 11-Dec-2010 then checkbox1, checkbox2, checkbox3, checkbox4 will be disabled and unchecked state for 11-Dec-2010
as you see on the above database structure the seats for 11-Dec-2010 is 1,2,3,4 so the chekbox1, checkbox2, checkbox3, checkbox4 will be disabled...
I wanna this code snippet in VB.NET !! Can anybody help me in that ???

A:

You should normalize your database - the Seats field is not normalized and should only hold one item.
Having comma delimited values in a field is bad practice. If you had a single value in it like the following:
Name          Seats           Date

Sumit         1               11-Dec-2010
Sumit         3               11-Dec-2010
Sanjeev       2               12-Dec-2010
Sanjeev       4               12-Dec-2010
Manish        1               11-Dec-2010
Manish        3               11-Dec-2010
Manish        4               11-Dec-2010

Removing a record would correlate to unchecking and adding one would correlate to checking a checkbox.


Q:

Does /proc/net/udp count all drops that occur between ethernet plug and my app?

/proc/net/udp on Linux has a "drops" column:
cat /proc/net/udp
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode ref pointer drops
16151: 00000000:CB53 00000000:0000 07 00000000:00000000 00:00000000 00000000  1000        0 39947169 2 ffff88084c108080 0

If the drops counter is 0 for a certain socket, can I be sure that any drops that occur between the sender of a legitimate UDP packet and the application happened outside of my box, say in some switch or router etc.?
Or could it be that i.e. my NIC driver silently dropped a packet for whatever reason, without affecting the counter?
I know for a fact that on Windows packets may get dropped even though there is still lots of space in the receive buffer, not sure if something similar exists on Linux.

A:

No.
Packets can be lost before they are de-multiplexed into user sockets.
This happens when the kernel is not able to read packets fast enough from the network card for some reason.
Network cards do not count packets lost on a per-port basis... at least not necessarily, and I don't believe anything like that is integrated into per-socket counts in /proc/net/udp.
There's a 2015 document that goes into detail about packet drops, I don't know if you'd find it interesting.  https://access.redhat.com/sites/default/files/attachments/20150325_network_performance_tuning.pdf


Q:

I am getting ****finished with non-zero exit value 2. how to resolve it?

I have read many questions related to this problem but all of them pointing to same solution jar duplicate in dependencies. I have check my dependencies their is no duplicate jar please tell how should i resolve this issue
**
"Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2"

**
here's my dependencies files
compile fileTree(dir: 'libs', include: ['*.jar'])
        compile files('libs/nextomeframework_beta1_mod.jar')
        compile 'gov.nist.math:jama:1.0.3'
        compile 'org.apache.commons:commons-math3:3.3'
        compile 'com.google.code.gson:gson:2.2.4'
        compile 'joda-time:joda-time:2.3'
        compile 'com.fasterxml.jackson.core:jackson-core:2.5.1'
        compile 'com.fasterxml.jackson.core:jackson-databind:2.5.1'
        compile 'com.fasterxml.jackson.core:jackson-annotations:2.5.1'
        compile 'com.googlecode.efficient-java-matrix-library:core:0.26'
        compile 'org.osmdroid:osmdroid-android:4.3'
        compile 'org.slf4j:slf4j-simple:1.6.1'
        compile 'commons-io:commons-io:2.4'
        compile 'org.codehaus.jackson:jackson-mapper-asl:1.8.5'
        compile 'org.codehaus.jackson:jackson-core-asl:1.8.5'
        compile 'com.android.support:appcompat-v7:23.1.0'
        compile 'com.android.support:design:23.1.0'
        compile files('libs/concurrent.jar')
        compile files('libs/Jama-1.0.3.jar')
        compile files('libs/zip4j_1.3.2.jar')

A:

I think there is a duplication in jama library as you have mentioned
compile 'gov.nist.math:jama:1.0.3'
and
compile files('libs/Jama-1.0.3.jar')
Try removing one of them.


Q:

Separate all multipage PDF files inside a directory into single page PDFs via Python

I need to take hundreds of randomly named multipage PDF files and split them into single-page PDF files.  I have been experimenting with Python with some success.  The following code does exactly what I need, but it is written to split a 'specific' PDF file (w9.pdf).  I need to split all PDF files in a directory (*.pdf).
Can somebody point me in the right direction, please?
# pdf_splitter.py

import os
from PyPDF2 import PdfFileReader, PdfFileWriter

def pdf_splitter(path):
fname = os.path.splitext(os.path.basename(path))[0]

pdf = PdfFileReader(path)
for page in range(pdf.getNumPages()):
    pdf_writer = PdfFileWriter()
    pdf_writer.addPage(pdf.getPage(page))

    output_filename = '{}_page_{}.pdf'.format(
        fname, page+1)

    with open(output_filename, 'wb') as out:
        pdf_writer.write(out)

    print('Created: {}'.format(output_filename))

if __name__ == '__main__':
    path = 'w9.pdf'
    pdf_splitter(path)

A:

I suggest you the following solution:
import glob

if __name__ == '__main__':
    paths = glob.glob('*.pdf')
    for path in paths:
        pdf_splitter(path)


Q:

Wordpress 3.2 - removed ability to select a page template in the page attributes when adding a new page?

Maybe it's just the site I'm running but has the 3.2 update removed the ability to select a page template in the page attributes when adding a new page?
It's kinda essential unless anyone knows a way around it?

A:

It seems as though it was a personal problem. A knew install solved the problem so it must've been clashing with some legacy data.


Q:

IOS: random paging scrollview

I have this code for a scrollView (with paging enabled)
- (IBAction) random{
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * (arc4random() % (numberOfPage - 1));
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];}

It make a random paging scroll and it's ok, but it is very slow. Can I have a fast scrolling as a slot machine?

A:

I'm not sure you could get it to look like slot machine (you'd probably need some motion blur to get that kind of effect), but you could try putting your scrollRectToVisible: in an animation block to change the duration of the animation:
- (IBAction) random
{
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * (arc4random() % (numberOfPage - 1));
    frame.origin.y = 0;

    [UIView animateWithDuration: <your duration>
                     animations:^(void) {
                         [scrollView scrollRectToVisible:frame animated: NO];
                     }];
}

Don't forget the animated:NO, otherwise it'll override your duration


Q:

When will the generalist badge start being awarded?

The Generalist badge description reads:

Provided non-wiki answers of 15 total score in 20 of the top 40 tags.

There’s a hidden rule about when the badge gets turned on:

One thing the badge doesn't say, is that there must be at least 200 questions in all 40 of the top tags before this badge is awarded to anyone. That's why you won't see it on meta for a bit longer, or any new sites for about a year.

So far, nobody on the main site has been awarded the badge.
But it seems to me that we’ve met the conditions for the badge to be awarded, and have done for a while now:

Looking at the tags page, the 40th top tag is [suggested-order], with 202 questions. The most recent question in this tag was July 8th, nearly a fortnight ago, so it’s been >200Qs for a while.
At least three of our users (no surprises – DVK, Thaddeus and Richard) all meet the tag badge criterion. It seems like they should have been awarded this badge.

Why hasn’t the badge been awarded yet?

A:

Update: As of September 13th, 2015 the badges are now being awarded
https://scifi.stackexchange.com/help/badges/14/generalist
You've failed to take into account that the tag page is 9 lines long, not 10.
Of the top 40 tags, only 37 38 have over 200 questions and only 36 37 have enough qualifying questions (e.g. non-wiki questions).

As to when I get my shiny new badge, based on current projections it'll probably be within the next 3 months unless we have some major push on the tags that are bubbling under.
You can keep an eye on the progress using this data search
UPDATE: We now have 38 tags with 200 questions. Two more are required for Generalist to be offered:

A:

When will the generalist badge start being awarded?

Yesterday:  https://scifi.stackexchange.com/help/badges/14/generalist


Q:

How to set PEC flag to SM bus in device tree?

I have a I2C/SMBus device that requires PEC and I'm writing a kernelspace driver for it.
On Linux 2.6.37 I use i2c_board_info to instantiate the client and set the flag there, but now the driver is being ported to 3.14 and I could not find the device tree binding for the PEC flag.
Actually I don't think there is such a binding because the I2C core is not getting any property from device tree other than reg and wakeup-source.
So shall I just do i2c_client->flags |= I2C_CLIENT_PEC in my device driver?

A:

In current mainline kernel(4.5) code, at least three i2c client drivers enable I2C_CLIENT_PEC flag in the driver (ipmi_ssif, lm90 and pmbus_core), and one of them (lm90) exposes it to sysfs.
I believe it's safe to do i2c_client->flags |= I2C_CLIENT_PEC in the client driver.


Q:

El Capitan incompatible with Mad Catz Editor

I upgraded my Macbook Pro to OSX 10.11 El Capitan but sadly the mapping software for my Mad Catz Mouse (M.M.O.7) does not start anymore.
Crash Report
Process:               editor [33209]
Path:                  /Applications/Mad Catz Editor.app/Contents/MacOS/editor
Identifier:            com.madcatz.MadCatz.editor
Version:               1.0 (1.1.69)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           editor [33209]
User ID:               501

Date/Time:             2015-10-07 13:41:42.846 +0200
OS Version:            Mac OS X 10.11 (15A284)
Report Version:        11
Anonymous UUID:        8B5B6605-7448-4DDA-627C-11145BEF80FE

Sleep/Wake UUID:       4D337680-5145-4CF7-B785-93E78B39BE4D

Time Awake Since Boot: 100000 seconds
Time Since Wake:       17000 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MCProfile profile]: unrecognized selector sent to instance 0x10042c350'
abort() called
terminating with uncaught exception of type NSException

Application Specific Backtrace 1:
0   CoreFoundation                      0x00007fff8b3a7bd2 __exceptionPreprocess + 178
1   libobjc.A.dylib                     0x00007fff866ac4fa objc_exception_throw + 48
2   CoreFoundation                      0x00007fff8b4110ed -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3   CoreFoundation                      0x00007fff8b3183d1 ___forwarding___ + 1009
4   CoreFoundation                      0x00007fff8b317f58 _CF_forwarding_prep_0 + 120
5   MCDeviceLib.dylib                   0x0000000100041587 -[MCProfile checkName] + 119

The result is that I have a lot of hovering problem (hover event does not fire anymore) and shortcuts macros do not work at all.
Does anyone have a workaround ?
I contacted the Mad Catz team via Facebook and Twitter 2 days ago and I still have no answer.

A:

I'm having the same issue, in a chat with Madcatz support they stated to come up with a new driver by end of this year - still a bit to suffer unfortunately.
Installing USB overdrive and controller mate are too much for me to achieve a little bump in functionality.


Q:

how to make NSTextField editable

I am creating a custom class which is inherited from NSPanel and this panel is my landing screen of the application.
I am adding a NSTextField on it, which is visible on the screen. Problem is that the textfield is not editable.
However, if i create a new cocoa project and run the same addSubview code for textfield, all is good, i am able to edit the textfield.
It seems to me like problem is with my custom panel, but i am not able to hunt it down.
Here is my code:
NSTextField *infoTextField = [[NSTextField alloc] initWithFrame:rect];
[[window contentView] addSubview:infoTextField];
[infoTextField setDelegate:self];
[[infoTextField window] becomeFirstResponder];
[infoTextField setTextColor:[NSColor blackColor]];
[infoTextField setDrawsBackground:YES];
[infoTextField setBordered:YES];
[infoTextField setSelectable:YES];
[infoTextField setEditable:YES];
[infoTextField setEnabled:YES];
[infoTextField setAlignment:NSLeftTextAlignment];
[infoTextField setStringValue:@"What are you doing?"];
[infoTextField release];

I need your help...

A:

Override the method in NSPanel subclass,
- (BOOL)canBecomeKeyWindow {
    return YES;
}


Q:

Debug logs for a failing apex trigger

We have had a contractor develop a trigger for us that doesn't seem to be working in the way it should. Unfortunately, the contractor no longer works with us and we've been told by BMC support we need to provide them with the following info. Is anybody able to advise me on how I should go about this, please
"1. Debug logs when the status of an incident is closed"
"2. Ask a customer to add logs in the trigger which they have implemented and collect the logs when the trigger gets executed."
Is anybody able to guide me on how I could do this, please?
trigger COL_JIS_Set_Status_Closed on BMCServiceDesk__Incident__c (before update) {
BMCServiceDesk__Status__c closedstatus = [Select Id from BMCServiceDesk__Status__c where Name = 'Closed'
                                          and BMCServiceDesk__inactive__c = False limit 1];
    For (BMCServiceDesk__Incident__c inc : Trigger.New){
        if (inc.COL_JIS_Stop_SLA__c == True && Trigger.oldMap.get(inc.id).COL_JIS_Stop_SLA__c == False){
            inc.BMCServiceDesk__FKStatus__c = closedstatus.Id;
        }
    }
}

A:

You can set up a debug log for the user at Setup > Monitoring > Logs > Debug Logs.
Then perform an update on the one of your objects to make the trigger fire, and the log will appear in the list below.
By "add logs" to the trigger, I assume they mean to add system.debug() statements, which will print values out into the debug log.


Q:

Finding the age from a user input jQuery

I'm trying to have the user enter a year like 2030, it will take that and tell you that Bob is 34 since he was born in 1996. So I want the output to be "Bob is YEAR Inputted -  1996 in YEAR INPUTTED" (Bob is 34 in 2030.)

Enter a Year: <input id="yearborn" type="number"/>

                <button type="button" id="year_button">Enter</button>

A:

Please take a look at the code snippet.

.form-wrap{
  display: flex;
}

.get-age{
  padding: 10px;
  background: #ddd;
  cursor: pointer;
  margin-left: 10px;
}

Enter a Year: <input id="yearborn" type="number" >
      <button type="button" id="submityear">Enter</button>

Hope it helps.
Edit : Please try the new code and let me know if you still having any issue.


Q:

Batch rename list of files to totally different names using R

I have 330 files that i would like to rename using R. I saved the original names and the new names in a .csv file. I used a script which does not give an error but it does not change the names.
Here is a sample of the new names:(df1)
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010101.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010117.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS_EVI_20010201.tif

And a sample of the original names:(df2)
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001001.yL1600.EVI.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001033.yL1600.EVI.tif
D:\Modis_EVI\Original\EVI_Smoothed\ MODIS.2001049.yL1600.EVI.tif

Then here is the script i'm using:
csv_dir   <-  "D:\\"
df1        <- read.csv(paste(csv_dir,"New_names.csv",sep=""), header=TRUE, sep=",")        # read csv
hdfs       <- df1$x
hdfs       <- as.vector(hdfs)
df2        <- read.csv(paste(csv_dir,"smoothed.csv",sep=""), header=TRUE, sep=",")        # read csv
tifs       <- df2$x
tifs       <- as.vector(tifs)
for (i in 1:length(hdfs)){
  setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")
  file.rename(from =tifs[i], to = hdfs[i])
}

Any advice please?

A:

I think you mix up the old and the new files, and you are trying to use rename the new file (names), which do not exist, to the old file names. This might work
file.rename(from =hdfs[i], to = tifs[i])

A general approach would go like this:
setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")

fin <- list.files(pattern='tif$')
fout <- gsub("_EVI_", ".", fin)
fout <- gsub(".tif", "yL1600.EVI.tif", fout)

for (i in 1:length(fin)){
   file.rename(from=fin[i], to= fout[i])
}

To fix your script (do you really need .csv files?)
setwd("D:\\Modis_EVI\\Original\\EVI_Smoothed\\")

froms  <- read.csv("d:/New_names.csv", stringsAsFactors=FALSE)
froms <- as.vector(froms$x)

First check if they exist:
all(file.exists(froms))

Perhaps you need to trim the names (remove whitespace) -- that is what the examples you give suggest
library(raster)
froms <- trim(froms)
all(file.exists(froms))

If they exist
tos  <- read.csv("d:/smoothed.csv", stringsAsFactors=FALSE)
tos <- as.vector(tos$x)
# tos <- trim(tos)

for (i in 1:length(froms)) {
  file.rename(froms[i], tos[i])
}


Q:

Redirect to controller throws "Unfortunately, something went wrong."

I have installed this plugin https://github.com/shopware/swag-docs-storefront-controller in development-template but when i run this and tried to clear cart it redirect to url and shows error "Unfortunately, something went wrong."
In logs i have found below error

request.CRITICAL: Uncaught PHP Exception
  Shopware\Core\Framework\Routing\Exception\InvalidRouteScopeException:
  "Invalid route scope for route frontend.checkout.clearCart." at
  /var/www/html/shopware6/vendor/shopware/platform/src/Core/Framework/Routing/RouteScopeListener.php
  line 93 {"exception":"[object]
  (Shopware\Core\Framework\Routing\Exception\InvalidRouteScopeException(code:
  0): Invalid route scope for route frontend.checkout.clearCart. at
  /var/www/html/shopware6/vendor/shopware/platform/src/Core/Framework/Routing/RouteScopeListener.php:93)"}
  []

However this works fine in installer setup.

A:

You need to add a route scope to your controller. This is mandatory since a few weeks ago, but it seems as the example was not changed according to this.
https://docs.shopware.com/en/shopware-platform-dev-en/getting-started/recent-updates#routescope-details
It should be enough to add the routescope-annotation to the controller:
https://github.com/shopware/swag-docs-storefront-controller/blob/master/src/Storefront/Controller/ClearCartController.php#L23
Just add this to the annotation:
 * @RouteScope(scopes={"storefront"})

And add the route scope:
use Shopware\Core\Framework\Routing\Annotation\RouteScope;

I will prepare a pull-request which should fix it.


Q:

Wait until Excel RefreshAll (Ctrl+Alt+F5) finishes - VBA

I am running into a race condition issue where I have two QueryTables, each is hooked with its own AfterRefresh event. Each AfterRefresh event does some copy'n'pasting as well as doing some calculations.
Now, when the user click Refresh All (Ctrl+Alt+F5) in Excel, I would love to have each AfterRefresh handler to execute, but ONLY after all QueryTable refreshes are entirely completed.
I did a search on StackOverFlow, and someone suggested
Activeworkbook.RefreshAll
DoEvents

However, that's assuming that we are programmatically triggering the RereshAll. In my case, Refresh All is done by the built-in Refresh All (Ctrl+Alt+F5) button within Excel. Thus, I don't see where I can insert DoEvents in my case (unless I create my own Refresh All button, but I would like to avoid doing so).
I tried to search for "Excel VBA mutex", but I did not find anything in particular. So how do I make sure that all the refreshes are done, before each AfterRefresh handler takes place?
Thanks for reading!
Update: To help out with debugging.. here are my VBA codes.
I have a module named AutoOpen
Dim S As New DataCopy
Dim U As New DataCopy

Sub Auto_Open()
    Set S.qt = ThisWorkbook.Sheets(1).QueryTables(2)
    S.myWorkbookName = ThisWorkbook.Name
    S.sWorksheetProcessName = "ProcessS"
    S.sWorksheetDataColumnStart = 1
    S.sWorksheetDataColumnEnd = 5
    Set U.qt = ThisWorkbook.Sheets(1).QueryTables(1)
    U.myWorkbookName = ThisWorkbook.Name
    U.sWorksheetProcessName = "ProcessU"
    U.sWorksheetDataColumnStart = 6
    U.sWorksheetDataColumnEnd = 10
End Sub

I also have a Class module named DataCopy
Public WithEvents qt As QueryTable
Public myWorkbookName As String
Public sWorksheetProcessName As String
Public sWorksheetDataColumnStart As Integer
Public sWorksheetDataColumnEnd As Integer

Private Sub qt_AfterRefresh(ByVal Success As Boolean)
    DataCopier
End Sub

Private Sub DataCopier()
    'Debug.Print sWorksheetProcessName & "," & Application.CalculationState
    Dim LastNRows As Integer
    Dim sWorksheetDataName As String

    ' How many rows to copy
    LastNRows = 297
    sWorksheetDataName = "Data"

    Application.ScreenUpdating = False

    ' Clear content in process tab
    With Workbooks(myWorkbookName).Worksheets(sWorksheetProcessName)
        .Range(.Cells(4, 1), .Cells(.Cells(Rows.Count, 1).End(xlUp).Row, 6)).ClearContents
    End With

    ' Copy to process Tab
    With Workbooks(myWorkbookName).Worksheets(sWorksheetDataName)
        LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        FirstRow = LastRow - LastNRows
        If FirstRow < 2 Then
            FirstRow = 2
        End If
        .Range(.Cells(FirstRow, sWorksheetDataColumnStart), .Cells(LastRow, sWorksheetDataColumnEnd)).Copy _
             Destination:=Workbooks(myWorkbookName).Worksheets(sWorksheetProcessName).Range("A4")
    End With

    Debug.Print (sWorksheetProcessName & "," & sWorksheetDataColumnStart & "," & sWorksheetDataColumnEnd)

    Application.ScreenUpdating = True
End Sub

Because of the race condition, only one AfterRefresh handler succeeds in copy'n'pasting.. the other one doesn't work until I click Refresh All button (Ctrl+Alt+F5) again.

A:

If a DoEvents works after the explicit VBA trigger Activeworkbook.RefreshAll then a DoEvents before the code that you want to run in the event handlers should cover the case when the refresh is triggered by Ctrl+Alt+F5. Thus, begin each event handler with the line DoEvents.


Q:

How to create data driven effects/abilities for collectable card game

I'm trying to create cards for a ccg/tcg that are completely "data-driven" from an xml/json/external file. I've read multiple articles on this issue already, even here on stack exchange, but i can't figure out how to actually code this. I have a simple example:
My two cards have the following abilities
1) "Increase the value of all adjacent red cards by 1"
2) "Increase the value of this card by the amount of all adjacent red cards"
In my code i have the following functions (pseudo) that i need to accomplish these effects:
Increase(targetCards, byValue) // increases a card's value by another value
FindCards(filter=adjacent) // returns all adjacent cards
FilterCardsBy(filter=isRed) // returns only red cards
Count(targetCards) // counts the number of cards

To create effect 1 i would use the functions like this:
Increase(FilterCards(FindCards(adjacent), isRed), 1);

and to create effect 2 i would use:
Increase(this, Count(FilterCards(FindCards(adjacent), isRed)));

So here's the problem:
I have no clue how i can describe these functions in my external file and also i have no clue how i actually tell my functions to work in this combination to achieve the desired effects.
Maybe i'm misunderstanding the concept here but as far as i understood and described here i can create some pseudo script/code in my external file that then my code can interpret and execute on. But i feel i somehow missing the middle part where i write code to interpret these commands i'm defining in the external file.
Anyone with experience here that can give me some super simple starter ideas on how to takle this. Especially the part where i can combine several functions into one.

A:

When you have complex logic in the mechanics of individual cards, then it might be best to express that logic with a scripting language. But if you really want to go for a completely domain-driven approach, you might go for something in between: Markup which describes logic.
Both of the effects mentioned in the question could be called an "adjacency effect". It's an effect which triggers if an adjacent card fulfills a certain condition. The difference is that one is a bonus on the adjacent card, the other one on the card itself (which stacks for each card which fulfills the condition). In JSON, these two effects could be expressed as a triplet of adjacencyCondition, self-effect and adjacent-effect.
{
    "adjacencyCondition: { color: "red" },
    "self": { "value": 1 },
    // "adjacent": undefined
}

{
    "adjacencyCondition": { "color": "red" },
    // self: undefined
    "adjacent": { "value": 1 },
},

If you don't like JSON, feel free to use XML, YAML, INI or whatever markup language you prefer instead. But I would not recommend you to invent your own. When you use an existing markup language, you will likely find a well-tested library for parsing it. When you develop your own, you will have to spend countless hours writing your own parser. This will be far harder than it sounds at first. And subtle bugs in your parser can and will cause you frustration to no end.
Your program code to apply these would look like this (pseudocode):
if (card has 'adjacencyCondition') {
    foreach (adjacent card) {
        if (adjacent card has all attributes specified by 'adjacencyCondition') {
              increase adjacent card attributes by everything specified in 'adjacent'
              increase current card attributes by everything specified in 'self'
        }
    }
}

This system can easily be enhanced to have more conditions than just adjacencyCondition (where "adjacent" doesn't necessarily makes sense, but other fields might). Your should allow cards to have an array of effects to allow cards which have more than one effect. In that case you might also have an unconditional condition which allows you to define inherent attributes of cards. But I have no idea how your game mechanics look like or what the theme of your game is, so I could only guess what could be useful for you.
Anyway, here is an example of a red card with a value of 3 which counts as both a kitten and a zombie, which turns all adjacent space stations green and gets +1 for every blue card controlled by the opponent:
{   "name": "Bob the Zombie Kitten",
    "effects": [
         {
             "unconditional": true,
             "self": {
                 "color": "red",
                 "traits": [ "zombie", "kitten" ],
                 "value": 3,
             }
          },
          {
            "adjacentCondition": { "traits": "space_station" },
            "adjacent" : { "color": "green" }
          },

          {
            "allCondition": { "owner": "opponent", "color": "blue" },
            "self" : { "value": 1 }
          },
    ]
}


Q:

Position of axis titles in ggplot, relative placement?

Does anyone have any insight into the placement of the axis titles in ggplot?
ggplot(mtcars, aes(x=mpg, y=hp)) + geom_point() + ylab("HP") + ylim(50,350) + xlim(10,35)

You can see the P in HP is below the top of the 200. And likewise the m on mpg is almost in line (or partly overlapping) with the 0 on 20 leaving the g in the middle of 20 and 25. I would have thought the middle of the gap between the H and P would have been in the middle (vertically) of the 2 in 200. If that makes sense.
Adding a few spaces to the label ("   HP") helps to fix it. Obviously the title is being centered relative to some co-ordinates, my guess is a 'box' that goes all the way to the bottom of the x labels (for the y title) and to the left of the y labels (for the x title). When having them relative to the actual plotting area would be more desirable.
Is this achievable?

A:

Per @Hadley's comment, as of version 0.9.0 this bug-let has been fixed:
ggplot(mtcars, aes(x=mpg, y=hp)) +
    geom_point() +
    ylab("HP") +
    ylim(50,350) +
    xlim(10,35)

produces:


Q:

How do I find orphaned forks for a deleted gist or GitHub repo

Because the Twitter algorithm is Weird™, this super old tweet come through my feed very recently and I decided I'd like to try out the gist it links to.
Unfortunately, sometime in the 5 years since that tweet was sent, the gist has either been deleted or made private1. Fortunately, I found the gist on the Wayback Machine. Problem solved! Right?
I could just copy-paste the file into a gist of my own for posterity, but  I notice that there were 25 forks as of the Wayback snapshot. According to this documentation it seems like...

...one of the existing public forks [should have been] chosen to be the new parent repository.

...assuming Gists have the same behaviour as vanilla repositories. Sadly, Wayback has not cached a list of who those forks belong(ed) to. If I want to follow along with that gist and its forks, how do I find them?

1: fwiw - it looks like the original author deleted their GitHub account very recently

A:

I was able to find the forks by going to gist.github.com and copying a string from your wayback link in the search box (seeyouspacecowboy.sh).
This search provided me with 2 search results, one of which showed "25 forks". Clicking that gist allowed me to see all 25 forks of the Gist.


Q:

'isConnected' deprecated in iOS 7

I know this is a stupid question but here goes.
I have an older app that uses isConnected.  Now I get a warning that it is deprecated.  Can I just delete this line of code without any ramification or how do I handle this.  Sorry for being so dense.
here is some code it is from the CBPeripheral framework.
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    // Deal with errors (if any)
    if (error) {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        [self cleanup];
        return;
    }
}
- (void)cleanup
{
    // Don't do anything if we're not connected
    if (!self.discoveredPeripheral.isConnected) // here is where the warning comes {
        return;
    }

I think I found the answer  should be
- (void)cleanup
    {
        // Don't do anything if we're not connected
        if (CBPeripheralStateDisconnected)  {
            return;
        }

I also added @property(readonly) CBPeripheralState state;  in my .h
I don't get an error  Can anyone verify this for me?

A:

As Apple Documentation says:

isConnected
A Boolean value indicating whether the peripheral is currently connected to the central manager. (read-only) (Deprecated in iOS 7.0. Use the state property instead.)

Just replace your code by:
if (self.discoveredPeripheral.state != CBPeripheralStateConnected)
    return;

On the other hand, if that's all you have in this method, basically you are doing nothing.
So you could just remove that dead code. Which makes me thinks something missing... No cleanup?


Q:

Split to Dubrovnik on Schengen visa for Indian

I am Indian and next month I am traveling from Split to Dubrovnik via bus. I have a Schengen visa. The bus in between goes to Bosnia and Herzegovina which is not part of EU / Schengen. Will I be able to board that bus?`

A:

Yes, if your Schengen visa is valid for multiple entries.  People with multiple-entry visa for a Schengen country (or an EU country or the US) may enter Bosnia and Herzegovina on the basis of that visa for a stay of up to 30 days (yours will be more like 30 minutes).
Reference from the embassy to India:

(1) Citizens of the countries with whom Bosnia and Herzegovina has a visa regime, may enter Bosnia and Herzegovina with passport, without the obligation to obtain a visa for entry, exit, transit and stay on the territory of Bosnia and Herzegovina upto 30 days only if they have a valid multiple entry visa or residence permit issued by the signatory countries of the Schengen Agreement, the EU member states or the United States of America.


Q:

Why do motherboard voltages meet 5v standard when so much seems to work at 5.5?

I am working with supercaps (>1F) for resin embedded purposes. I have an induction charger that says 5v, but it really is outputting 4.85 volt. Caps seem to be commonly in 2.7 and 5.5 volts... although there are some caps at other voltages, 5.5v seems to have way more supercaps than just 5v. Why is this?
I can't really fully charge big 2.7v caps in series (5.4v) but it seems so perfect for a 5.5 volt system. And I have to use a buck converter to get to 5.5 volt... or I have to just resistor drop everything to 2.7/3 and then they don't last anywhere near as long. SO what is the reason for this and how do I deal with this problem?
I could really use some insight. I'm sorry if this has been explained elsewhere... I'm struggling to dig through huge search results with just voltages and basic words for filtering. Thanks for any help.

A:

Well, 5.5V (or 6V or 6.3V) are a common specifications for parts designed to work at 5V with a bit of tolerance. 5.5V for ICs is about as close as you want to call it (10% more than nominal). For example, the 74ACH00.
Often the 5V is biased a bit higher to account for conductor losses at full load, so you might find a regulated 5V wall wart that outputs 5.1V or even a bit higher with a light load.
You don't want the parts failing if things are just slightly off nominal. For example, the ubiquitous LM7805 regulator will output between 4.8 and 5.2V.


Q:

Special characters cannot be identified by Reg Ex

I have this Reg Ex
\b\d{7}PM\w{2}\d*\b

so based on the reg ex it should only accept
 7 Numbers + PM + 2 alphanumeric + Any Length of Number. so this will accepts such as this respectively as it has \b in the beginning and in the end
1032213PM39849723

My question is that why does the regex above accepts
1032213PM39849723<\test>

or
1032213PM39849723.

or
>1032213PM39849723

and not
A1032213PM39849723

or
1032213PM39849723K

it really bugs me why is this happening, if there are any changes to be made in the regex so that any other characters would not be accepted at the end or the beginning please tell me so.

A:

It depends on the flavour of regex function you use, but typically that regex does not mean that the entire string has to consist of this and only this, it merely means that some part of the string has to match this. If you want to match the whole string, add start and end anchors:
^\d{7}PM\w{2}\d*$


Q:

NULL defaults to empty string in mysql?

I have a strange situation with a field that doesn't allow NULL values. If I insert a row, the field defaults to the empty string, even when mysql claims that the default is NULL.
mysql> describe user;
+---------------------------+------------------+------+-----+---------+----------------+
| Field                     | Type             | Null | Key | Default | Extra          |
+---------------------------+------------------+------+-----+---------+----------------+
| id                        | int(30)          | NO   | PRI | NULL    | auto_increment |
| username                  | varchar(45)      | NO   | UNI | NULL    |                |
| city                      | varchar(45)      | NO   |     | NULL    |                |
+---------------------------+------------------+------+-----+---------+----------------+

mysql> show triggers;
Empty set (0.00 sec)

mysql> insert into user (username) values ('just_testing');
Query OK, 1 row affected, 17 warnings (0.01 sec)

This is the point where I go WHAT?! - city should default to NULL which isn't allowed, but look here:
mysql> select username, city from user where username = 'just_testing' and city is null;
Empty set (0.00 sec)

mysql> select username, city from user where username = 'just_testing' and city='';
+--------------+------+
| username     | city |
+--------------+------+
| just_testing |      |
+--------------+------+
1 row in set (0.00 sec)

Mysql has decided to use the empty string as default even though it isn't so and there isn't any triggers.
And further:
mysql> insert into user (username, city) values ('just_testing3', NULL);
ERROR 1048 (23000): Column 'city' cannot be null

What am I overlooking? How does the city column default to ''?

A:

From the docs:

If you are not running in strict SQL mode, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values. Default value assignment is described in Section 11.6, “Data Type Default Values”. See also Section 1.8.3.3, “Constraints on Invalid Data”.

and further:

For string types other than ENUM, the default value is the empty string. For ENUM, the default is the first enumeration value.


Q:

How to distinguish between “user must change password at next logon” and “wrong password” use cases?

I use UnboundID for the authentication against Active Directory.
I have same error code when I authenticate with the wrong password and when the user is configured with “user must change password at next logon”.
“wrong password” exception:
LDAPException(resultCode=49 (invalid credentials), errorMessage='80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece

“user must change password at next logon” exception:
LDAPException(resultCode=49 (invalid credentials), errorMessage='80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece

The only difference is the value of word data in the exception message.
I do not want to rely on the message.
How to distinguish between “user must change password at next logon” and “wrong password” use cases?

A:

A quick look at this page:
http://ldapwiki.willeke.com/wiki/Common%20Active%20Directory%20Bind%20Errors
Shows that:
data 52e = Returns when username is valid but password/credential is invalid.
data 773 = Entry's password must be changed before logging on LDAP pwdLastSet: value of 0 indicates admin-required password change - MUST_CHANGE_PASSWD
-jim


Q:

Can I delete a dynamically allocated class using a function within that class?

I'm writing a state manager for a game. I've got most of the logic down for how I want to do this.
I want states, which will be classes, to be handled in a stack in the StateManager class. Each state will have pause functions, and the stack will be an STL stack.
When a state is done with what it needs to do (example: from the pause screen, the user clicks "return to game") it needs to be removed from the stack and deleted. My current logic (which I have been unable to test, unfortunately) would be this:
State finishes its job.
In its update function, when it finds that its done, it will call a function to clean up the state.
This function will take care of any immediate loose ends that need to be tied (if there are any), call the pop function from the state manager stack, and delete itself.
What I'm asking is: can I delete a class from within itself?

A:

See C++-FAQ-lite: Is it legal (and moral) for a member function to say delete this?

As long as you're careful, it's OK for an object to commit suicide (delete this).


Q:

First publication claim patent

I published four months before them
They filed for patent eight months after I published
Can I claim their patent?
Also I submitted an very similar patent two months before I published.
I am just one man and don't have resources to really submit a thorough patent. The idea I published was more scientific so my patent publication into more of a applicable hardware device, because I don't understand what is "patentable".
The other patent was filed by a University 8 months after my publication.
Is there any argument explaining that obviously if I had resources such as a University. I would have filed my patent before them.
Do I have a case?

A:

The answer is no, you have no claim on anyone else's patent applications. What you have is prior art. Once you published your technology, you lost your ability to patent it in many countries. In the US, you do have a 12 month grace period, but it is dangerous to publish before filing for a patent as someone else could file  before you. Your publication should prevent anyone else being able to patent your invention. That said, it is possible the patent examiners may not find your publication while examining their applications. You may want to make the patent examiners aware of your publication to make sure it is considered during the examination of the applications you believe copy it.


Q:

How to change Content-Type for XQuery response?

Adding images instead of code because it doesn't show up.

I have an xquery which forms webpage. It runs on exist-db.
This xquery calls another xquery with xforms submission:

returnTable.xq returns an HTML table when run from browser directly

In this case Content-Type in response is:

You can see from submission that this HTML table should replace data in 'table' instance.
It does replace the data, but instead of HTML table I get a plain text.
I use
<xf:output value="instance('table')" mediatype="xhtml"/>
to show the table on webpage. I tried mediatype xml, text/xml and others.

So, when it is replaced I got a plain text instead of HTML table on webpage.

Should be like this (which I get in a completely different way, but do not want to use it due to poor performance):

I think it happens because response's Content-Type is Content-Type = text/javascript instaed of Content-Type = text/xml:

Do you know how can I change this?

A:

You're looking for XQuery serialization options, which are supported by eXist DB, but differ between XQuery 1.0 and XQuery 3.0.
XQuery 1.0 option to set the content type to application/xhtml+xml:
declare option exist:serialize "method=xml media-type=application/xhtml+xml";

For XQuery 3.0, you can use standard XQuery serialization options:
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "xml";
declare option output:media-type "application/xhtml+xml";


Q:

Calculate distance with JTS

I'm trying to get the distance between two points with JTS.
The problem is that this function with JTS
new Coordinate(Lon1,Lat1).distance(new Coordinate(Lon2,Lat2))

Is giving a different result from this function used in postgis(wich provides the good distance)
ST_Distance_Sphere(point1,point2)

A:

The short answer is you can't do that unless your points are very close together and you want the answer in degrees. JTS knows nothing about units or the curvature of the earth. So you need to pull in some GeoTools jars that do know about such things. Then you can create a method like:
private void calculateDistance(CoordinateReferenceSystem crs, Point[] points) {
    if (crs == null) {
        crs = default_crs;
    }

    double distance = 0.0;
    try {
        distance = JTS.orthodromicDistance(
            points[0].getCoordinate(),
            points[1].getCoordinate(),
            crs
        );
    } catch (TransformException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Measure<Double, Length> dist = Measure.valueOf(distance, SI.METER);
    System.out.println(dist.doubleValue(SI.KILOMETER) + " Km");
    System.out.println(dist.doubleValue(NonSI.MILE) + " miles");
}

Which will take care of all the hard maths for you. The full example program can be seen here.

A:

You could use the Java implementation of GeographicLib to solve the inverse geodesic problem on WGS84.
import net.sf.geographiclib.*;

...

    private double calculateDistance(
            double lon1, double lat1, double lon2, double lat2) {
        GeodesicData g = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2);
        return g.s12;  // distance in metres
    }

The length of the geodesic, which represents the shortest distance in metres between the two points, is in g.s12.


Q:

conditionally make the 2nd axios call happen based on a first

I'm trying to make it so that I can look at the returned object from the first axios call, and if empty, continue to the 2nd (if it's not empty I will craft an error message)
Basically, the 2nd axios call should only happen if the userStatus object is empty. Both axios calls work independently but how Can I properly make this work so that I can hit the 2nd call if the object is empty?
Currently I get a 200 on the first axios call and an empty userStatus object in my console but the 2nd call doesn't happen
changeStatus: function(event) {

  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
  .then((response) => {
      this.userStatus = response.data
  })

  if(this.userStatus.length < 1){

    let data = {
        id: event.id,
        status: 'A'
    };

    axios.post('/status/change',data)
    .then((response) => {
        if (response.data.success == false) {
            this.errors = [];
            const errorLog = Object.entries(response.data.errors);
            for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
            }
        }
    })

  }else{
    console.dir('No');
  }
},

A:

The issue is that your code is being executed synchronously (essentially line-by-line), while axios calls are asynchronous. So while your first axios call is still executing in the background, the statement if(this.userStatus.length < 1) gets evaluated – before your first call has returned.
If your second call is conditioned upon the result of your first call, you would need to make your second call inside the .then() handler of your first call:
changeStatus: function(event) {
  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
    .then((response) => {
      this.userStatus = response.data;

      if(this.userStatus.length < 1) {
        let data = {
          id: event.id,
          status: 'A'
        };

        axios.post('/status/change',data)
          .then((response) => {
            if (response.data.success == false) {
              this.errors = [];
              const errorLog = Object.entries(response.data.errors);

              for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
              }
            }
          });
       } else {
         console.dir('No');
       }
    });
},


Q:

Add extra URL in front of PHP function for redirect - PHP

I use a PHP function which gets the current URL for a WordPress plugin:
$current_url = home_url(add_query_arg(array(),$wp->request));
If I then add $current_url to a href link, it will redirect to the current page. However, I want to add another link in front of the redirect (in front of the PHP code).
So if you are on
test.com/page123
I want it to redirect to :
test.com/redirect/https://test.com/page123
So I basically want to add test.com/redirect/ in front of it.
How can I add this to the PHP code?

A:

I just found out that there is a simpler way of doing this is to add something to the href. The href is: href='$current_url' you can change it to href='$current_url redirect'.
Then it would redirect to currentdomain.com/currentpage/redirect. currentdomain.com/currentpage is then your current page.


Q:

ggplot2 3D Bar Plot

I Know this sounds basic, but have a been searching for literally more than an hour now without success. I'm simply trying to plot a 3D bar plot in 'R' using the 'ggplot2' package. My dataframe looks something like this:
 x   y     z
t1   5   high
t1   2   low
t1   4   med
t2   8   high
t2   1   low
t2   3   med
t3  50   high
t3  12   med
t3  35   low

and I want to plot something like this on it:

Any help is more than appreciated!!

A:

As mentioned in comments, 3D plots usually aren't a good choice (when other options are available) since they tend to give a distorted/obscured view of data.
That said, here's how you can plot your data as desired with latticeExtra:
d <- read.table(text=' x   y     z
t1   5   high
t1   2   low
t1   4   med
t2   8   high
t2   1   low
t2   3   med
t3  50   high
t3  12   med
t3  35   low', header=TRUE)

library(latticeExtra)

cloud(y~x+z, d, panel.3d.cloud=panel.3dbars, col.facet='grey',
      xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1),
      par.settings = list(axis.line = list(col = "transparent")))


Q:

Exporting types from private headers via the public header

From what I understand, protection of implementation is a good principle to follow, so when writing a new library I decided to give it a shot. My goal is to protect internally used data types and only export the ones that are absolutely needed for people implementing my library.
Let say I have four files:
library_component.c:
#include "library_component.h"

struct my_data {
    int stuff;
};

library_component.h:
// Private header
struct my_data;

library.c
#include "library_component.h"
#include "library.h"

library.h:
// Public header
// Include guards, etc...

typedef struct my_data my_data_type;

In this example library_component.c and library.c would get compiled into a shared library file library.so and installed along with library.h inside the host machine.
What's unclear to me, is how am I supposed to handle the struct my_data situation. I want to export it is as my_data_type. Is it possible to hide the typedef statement from the public header?

A:

If library is the only module exposed to the caller - it is the actual API - then this design is fine. A nosy caller, who for some reason goes to dig up internal header files only used by library, can't do much with it anyway - struct my_data in the header is an incomplete type.
However, a less confusing alternative might be to write library_component.h as:
typedef struct my_data_t my_data_t;

And then use that very same definition in library.h - the type is declared in library_component.h and library.h gets access through it with #include. Then everything will be clear. In library_component.c you would have struct my_data_t { ....
And finally, all functions in library.h should be designed to use my_data_t*, which is a must since the type is incomplete and the caller won't be able to create instances of it.
This design method is known as opaque type/opaque pointers.


Q:

How to show/hide DOM element with jQuery?

There are button (id= "hide_message_button") and message(id="message"). The click on the button should hide/show the message. The source code:
$('#hide_message_button').click(function(){
   var bool = $('#message').css('visibility','hidden').is(':hidden');
   if(bool){
      $('#message').show();
      $(this).val('Hide');
   }
   else {
      $('#message').hide();
      $(this).val('Show');
   }
});

I have a bug: the message is hidden with first click on the button and didn't shown again (but button's value is changed to 'Show'). What's wrong? Thanks.

A:

Try:
$('#hide_message_button').click(function(){
    $('#message').toggle();
});


Q:

Dimension of span of a finitely generated subgroup

If $QA\subset V$ is the span of $A\subset V$, V- a vector space over the field $Q$, $A$ - a finitely generated abelian subgroup (and hence has a finite rank), then is $dim(QA) = rank(A)?$ I think since $A$ spans $QA$, any basis of $A$ has a corresponding basis in $QA$ and hence the statement is true? Intuitively, it feels right but not sure about concrete reason. A hint is appreciated.

A:

Let $\{e_1,\dots,e_k\}$ be a basis in $A$. Then it is also a basis in $QA$. Indeed, every element of $QA$ is a rational linear combination  of elements of $A$ and hence a rational linear combination of $e_1,\dots,e_k$. Let us prove that $e_1,\dots, e_k$ are linearly independent in $QA$. Assume that they are, $\lambda_1 e_1+\dots+\lambda_ke_k=0$. Let $q$ be a common denominator of all nonzero $\lambda_j$, and let $m_j=q\lambda_j$. Then all $m_j$ are integers and $m_1e_1+\dots+m_ke_k=0$, and hence all $m_j=0$ by the linear independence of $e_1,\dots,e_k$ in $A$.


Q:

Recommendations to tether a Nikon DSLR to a Windows PC?

When I shoot portraits indoors, I'd like the option to tether my Nikon D90 to a Windows computer with the USB cable, both to view the results and help adjust the lighting, but also to be making an instant backup of each shot.
Does anybody have a favorite solution to this?

A:

If you're looking for a free program to let you shoot tethered with your Nikon, this post discusses a few of the options.

A:

You can do this with the tethering features in Adobe Photoshop Lightroom 3.
Another option is Nikon's Camera Control Pro.


Q:

Add a panel to a fxml pane

I am new to JavaFX and I am trying to do an app that will show several panels from the same class: The class PacienteGUI creates a panel, and I want to show 5 of this PacienteGUI panels in my main FXML, which has a panel itself.    I´ve tried to add it through the controller by
@FXML Pane principal;

@Override
public void initialize(URL url, ResourceBundle rb)
{
    PacienteGUI paciente = new PacienteGUI(1);
    principal.getChildren().add(paciente);
}

Part of the PacienteGUI:
public class PacienteGUI extends javax.swing.JPanel {

public PacienteGUI(int num) {
    chairNum = num;
    initComponents();
}

private void initComponents() {
..
..
..Creates JPanel with all its components
..
}

The problem is that it says that PacientesGUI cannot be converted to node. How can I solve this??
Thanks

A:

Your Paciente class is a Swing JPanel, which cannot be placed in a JavaFX Pane directly.
You either need to make Paciente a subclass of a JavaFX Pane, or you need to wrap the Paciente instance in a SwingNode. The latter (SwingNode) is tricky, because you will need to use two different threads to create the different components: swing components need to be created and accessed on the AWT event dispatching thread, and JavaFX components need to be created on the FX Application Thread. I strongly recommend not mixing JavaFX and Swing if you can do so.


Q:

Matrix of Linear Map

Here's the problem I've been working on:
Let $V$ be a vector space, and let $B = (v_1,...,v_n)$ be a basis of $V$. Define $T \in L(V)$ as $Tv_k  = \sum_{I=1}^{k}v_i = v_1 + ... + v_k$. Find the matrix $[T]_B$.
I'm not really sure how to proceed with this problem. I think that the matrix should be triangular, as you are summing the previous elements of the basis, but I'm not sure how to proceed in constructing the matrix.

A:

When $n=4$, you have
\begin{align}
Tv_1&=v_1 \\
Tv_2&=v_1+v_2 \\
Tv_3&=v_1+v_2+v_3 \\
Tv_4&=v_1+v_2+v_3+v_4
\end{align}
so, by definition of associated matrix, you get
$$
\begin{bmatrix}
1 & 1 & 1 & 1 \\
0 & 1 & 1 & 1 \\
0 & 0 & 1 & 1 \\
0 & 0 & 0 & 1
\end{bmatrix}
$$
The $k$-th column has the coefficients needed for expressing $Tv_k$ as a linear combination of the basis vectors.


Q:

can't install ElasticSearch image, with java 8

I used the official docker image for els (elasticsearch:6.6.1), and I get the following error, when I run the image:
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.

from searching online, there is problem with the JAVA, its using, and JAVA 8 is recommended.
I tried to make dockerfile that takes els:6.6.1 image, and install java8 on it:
FROM elasticsearch:6.6.1
RUN yum install -y  java-1.8.0-openjdk-devel
RUN export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64
RUN export PATH=$PATH:/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64/bin/

When I run it, I don't see JAVA_HOME env changing to the path I gave, and I still get the above error.
Do you know why?

A:

Set environment variables by using ENV instead of RUN export.
FROM elasticsearch:6.6.1
RUN yum install -y java-1.8.0-openjdk-devel
ENV JAVA_HOME /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64

You can see more explanation by VonC docker ENV vs RUN export.


Q:

viewPager.setCurrentItem() is not working

setCurrentItem() function isnt working for following android(java) code how to make it work ?
    Intent i = getIntent();
    int position = i.getIntExtra("img", 0);
    viewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    ImageAdapter adapter = new ImageAdapter(this);
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(position);

A:

Frank is right. To provide the the scroll device independent, you should use onGlobalLayoutListener. Thereby, you can guarantee that the view is rendered when you call viewPager.setCurrentItem(position). Otherwise setCurrentItem won't have any effect since the view is not rendered yet.
viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                viewPager.setCurrentItem(position, false);
            }
        });

I know the question is already old but maybe someone else will find this usefull!

A:

private ViewPager viewPager;

@Override
public void onResume() {
 Intent i = getIntent();
int position = i.getIntExtra("img", 0);
viewPager.postDelayed(new Runnable() {

    @Override
    public void run() {
        viewPager.setCurrentItem(position);
    }
 }, 100);
}

A:

None of these answers worked for me - it took hours for me to find out that I'd forgotten to update getCount().
My getCount() method in my implementation of the FragmentPagerAdapter was displaying the incorrect count, so it could not change page since it was not part of its count.


Q:

Wrap a method into a func

I want to create a generic wrapper around Polly framework so that can have single implementation. In order to achieve it I have written below code
    private Policy GetPolicy(EType eType)
    {
        var policy = default(Polly.Policy);

        switch (eType)
        {

            case EType.T:
                policy = Policy.Handle<SomeException>().Retry(n, x => new TimeSpan(0, 0, x));
                break;
        }
        return policy;
    }

And I am using the above method in one of my wrapper methods
   public TOutput Execute<TOutput>(Func<TOutput> func, EType eType)
    {
        var policy = GetPolicy(eType);

        return policy.Execute(() => func());
    }

Now in order to consume it I have written a sample method
       var handleError = new HandleError();
        var connection = handleError.Execute(() => factory.CreateConnection(), ExceptionType.Transient);

Till above all works fine, but as soon as I start calling the same in a method which takes parameter, then it throws error as
     var handleError = new HandleError();
        handleError.Execute(() => channel.ExchangeDeclare(queueDetail.ExchangeName, ExchangeType.Fanout), ExceptionType.Transient);

     The type arguments for method 'HandleError.Execute<TOutput>(Func<TOutput>, ExceptionType)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

A:

You need two Execute overloads, one for functions that return value and another for those which do not:
public TOutput Execute<TOutput>(Func<TOutput> func, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    return policy.Execute(func);
}

public void Execute(Action action, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    policy.Execute(action);
}

Then you can pass anything there, including functions with parameters:
// calls first overload
Execute(() => ImReturningValue(parameter1));
// calls second
Execute(() => IDoNot(parameter1));

Policy.Execute method also has the same overloads (one for Func, one for Action) - so you will have no problems to pass either one to it.


Q:

Functions as a Power Series

So, say you had $\dfrac{(-4)^n}{-4}$
Would that be equivalent to $(-1)^{n-1} \times 4^{n-1}$? If so, how come it isn't $1^{n-1}$ (or just $1$) ?

A:

Using the formulas: $(ab)^{n-1} = a^{n-1}b^{n-1}, a = -1, b = 4, \dfrac{x^n}{x} = x^{n-1}$ with $x = -4$ you have: $\dfrac{(-4)^n}{-4} = (-4)^{n-1} = (-1)^{n-1}\times 4^{n-1}$