text:
Q: Multithreaded Geometry loading with GeoTools Hey StackOverflow community,
I am currently trying to write a little tool, that reads a shapefiles geometries (Multipolygons / Polygons) and writes the WKT-representations of those into a text file.
To do so, I am using GeoTools and I managed to get it running fine, due to the fact that I am converting files with about 5000000 Polygons / Multipolygons, it takes pretty long to finish.
So my question is:
Is it possible to fasten up the file loading/writing?
As I am using a SimpleFeatureIterator I did not find out how to implement multithreading.
Is there a way to do so?
Or does anyone know, how to get the shapefiles geometries without using an iterator?
This is my code:
This method is just stating the File Chooser and starting the thread for each selected file.
protected static void printGeometriesToFile() {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "shape-files", "shp");
    chooser.setFileFilter(filter);
    chooser.setDialogTitle("Choose the file to be converted.");
    chooser.setMultiSelectionEnabled(true);
    File[] files = null;

    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        files = chooser.getSelectedFiles();
    }

    for (int i = 0; i < files.length; i++) {
        MultiThreadWriter writer = new MultiThreadWriter(files[i]);
        writer.start();
    }
}

The class for multithreading:
class MultiThreadWriter extends Thread {
    private File threadFile;

    MultiThreadWriter(File file) {
        threadFile = file;
        System.out.println("Starting Thread for " + file.getName());
    }

    public void run() {
        try {
            File outputFolder = new File(threadFile.getAbsolutePath() + ".txt");
            FileOutputStream fos = new FileOutputStream(outputFolder);
            System.out.println("Now writing data to file: " + outputFolder.getName());

            FileDataStore store = FileDataStoreFinder.getDataStore(threadFile);
            SimpleFeatureSource featureSource = store.getFeatureSource();

            SimpleFeatureCollection featureCollection = featureSource.getFeatures();
            SimpleFeatureIterator featureIterator = featureCollection.features();

            int pos = 0;

            while (featureIterator.hasNext()) {
                fos.write((geometryToByteArray((Polygonal) featureIterator.next().getAttribute("the_geom"))));

                pos++;
                System.out.println("The file " + threadFile.getName() + "'s current positon is: " + pos);
            }

            fos.close();

            System.out.println("Finished writing.");

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

This is just a helper function that converts the Multipolygons to polygons and returns its WKT-representation with a "|" as a seperator.
private byte[] geometryToByteArray(Polygonal polygonal) {

    List<Polygon> polygonList;

    String polygonString = "";

    if (polygonal instanceof MultiPolygon) {
        polygonList = GeometrieUtils.convertMultiPolygonToPolygonList((MultiPolygon) polygonal);
     //The method above just converts a MultiPolygon into a list of Polygons
    } else {
        polygonList = new ArrayList<>(1);
        polygonList.add((Polygon) polygonal);
    }

    for (int i = 0; i < polygonList.size(); i++) {
        polygonString = polygonString + polygonList.get(i).toString() + "|";
    }

    return polygonString.getBytes();
}

}
I know my code is not pretty or good. I have just started learning Java and hope it will become better soon.
sincerely
ihavenoclue :)

A: *

*You do not need create a new thread for every file, because creating new thread is an expensive operation. Instead, you can let MultiThreadWriter  implements Runnable and use ThreadPoolExecuter manage all threads.
MultiThreadWriter
public class MultiThreadWriter implements Runnable {
    @Override
    public void run() {
        //
    }
}

Create thread pool matches your runtime processors.
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

for (int i = 0; i < files.length; i++) {
    MultiThreadWriter writer = new MultiThreadWriter(files[i]);
    service.submit(writer);
}

*You can use BufferedWriter instead OutputStream, it is more
efficient when you repeatly write small pieces.
File outputFolder = new File(threadFile.getAbsolutePath() + ".txt");
FileOutputStream fos = new FileOutputStream(outputFolder);
BufferedWriter writer = new BufferedWriter(fos);

A: I would prefere to read files content as a list of objects, then split the list onto sublists, then create a thread to each list, example :
int nbrThreads = 10;

ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(nbrThreads);

int count = myObjectsList != null ? myObjectsList.size() / nbrThreads : 0;

List<List<MyObject>> resultlists = choppeList(myObjectsList, count > 0 ? count : 1);

try
{
    for (List<MyObject> list : resultlists)
    {
        // TODO : create your thread and passe the list of objects
    }

    executor.shutdown();

    executor.awaitTermination(30, TimeUnit.MINUTESS); // chose time of termination
}
catch (Exception e)
{
    LOG.error("Problem launching threads", e);
}

The choppeList method can be like that :
public <T> List<List<T>> choppeList(final List<T> list, final int L)
{
    final List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L)
    {
        parts.add(new ArrayList<T>(list.subList(i, Math.min(N, i + L))));
    }
    return parts;
}


text:
Q: libperf PERF_COUNT_HW_CACHE_REFERENCES I am using libperf on a x86_64 CPU to measure the PERF_COUNT_HW_CACHE_REFERENCES and PERF_COUNT_HW_CACHE_MISSES counters when a given piece of code runs. I do it in two different ways and I expect to get similar numbers but this doesn't happen.
The events are setup like shown below:
struct read_format {
  uint64_t nr;
  struct {
    uint64_t value;
    uint64_t id;
  } values[ 2 ];
};

static void pevnt_init(int cpu_id) {
  struct perf_event_attr pea;
  int                    fd1 = -1;
  int                    fd2 = -1;
  int                    tid = syscall(__NR_gettid);

  memset(&pea, 0, sizeof(struct perf_event_attr));
  pea.type           = PERF_TYPE_HARDWARE;
  pea.size           = sizeof(struct perf_event_attr);
  pea.config         = PERF_COUNT_HW_CACHE_REFERENCES;
  pea.disabled       = 1;
  pea.pinned         = 1;
  pea.exclude_kernel = 1;
  pea.exclude_hv     = 1;
  pea.exclude_idle   = 1;
  pea.read_format    = PERF_FORMAT_GROUP | PERF_FORMAT_ID;

  fd1 = syscall(__NR_perf_event_open, &pea, tid, cpu_id, -1, 0);
  if (fd1 != -1) {
    ioctl(fd1, PERF_EVENT_IOC_ID, &perf_ids[ cpu_id].id_cache_refs);

    memset(&pea, 0, sizeof(struct perf_event_attr));
    pea.type           = PERF_TYPE_HARDWARE;
    pea.size           = sizeof(struct perf_event_attr);
    pea.config         = PERF_COUNT_HW_CACHE_MISSES;
    pea.disabled       = 1;
    pea.exclude_kernel = 1;
    pea.exclude_hv     = 1;
    pea.exclude_idle   = 1;
    pea.read_format    = PERF_FORMAT_GROUP | PERF_FORMAT_ID;

    fd2 = syscall(__NR_perf_event_open, &pea, tid, cpu_id, fd1, 0);
    if (fd2 != -1) {
      ioctl(fd2, PERF_EVENT_IOC_ID, &perf_ids[ cpu_id].id_cache_misses);
    }
  }
  printf("perf_event_open :: %6d :: %2d :: %5d :: %5d\n", tid, cpu_id, fd1, fd2);

  perf_ids[ cpu_id ].pevfd = fd1;
}

Method 1:
execute the code below for 10 seconds {
  ioctl(perf_ids[ cpu_id].pevfd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
  do_work();
  ioctl(perf_ids[ cpu_id].pevfd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP);
  read(perf_ids[ cpu_id].pevfd, &rf, sizeof(rf));
  accumulate the counters that have been read
}

Method 2:
ioctl(perf_ids[ cpu_id].pevfd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
execute do_work for 10 seconds
read(perf_ids[ cpu_id].pevfd, &rf, sizeof(rf));

So the main difference between Method 1 and Method 2 is that Method 2 let's the kernel to accumulates the counters.
The results provided by the methods are sometime very different. I understand that doing enable/disable has some impact on the counters but I don't expect so large differences.
Do you have any ideas on what can be wrong?
Regards,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function vanishes identically on the unit disc Let $f$ be analytic in $\mathbb D$ and continuous in $\overline {\mathbb D}$ . Let $A$ $=$ {$ e^{i \theta}| |\theta - \pi |< \epsilon$} , for $\epsilon > 0$ small enough such that $f|_{A} = 0$ . Show that $f$ is identically equal to $0$ on $\mathbb D$.

A: One method to see it is the reflection principle. You can reflect $f$ across the arc $A$ obtaining a holomorphic extension to a connected open set containing the arc $A$. The identity theorem says that the extension vanishes identically since it vanishes on the arc $A$. Using
$$\tilde{f}(z) = \begin{cases} \overline{f(1/\overline{z})} &, \lvert z\rvert > 1 \\ f(z) &, \lvert z\rvert \leqslant 1,\end{cases}$$
you have the reflection across $A$ explicitly, the analyticity of $\tilde{f}$ is clear in the unit disk and the exterior of the unit disk, for the analyticity on the arc $A$, use Morera's theorem.
Another, lower-level way is to choose an $n$ such that $n\cdot \varepsilon > \pi$, and consider
$$g(z) = \prod_{k=0}^n f(e^{2\pi ik/n}z),$$
which is continuous on the closed unit disk, holomorphic on the open unit disk, and vanishes identically on the unit circle. The maximum modulus theorem implies $g\equiv 0$, and that in turn implies $f \equiv 0$.


text:
Q: What am I missing to vertically align this text? I can set line-height to 85px and it will vertically align it, but I won't always know how tall the element is.  I'm sure I'm missing something simple here... but what can I modify in the .content class to make the text vertically centered?

.tile {
  position: relative;
  width: 100px;
  height: 85px;
  display: inline-block;
  border: 1px solid red;
}
#container1 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#container2 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  margin: auto;
  height: 100%;
  vertical-align: middle;
  text-align: center;
}

Test

A: You can use a psuedo element like this:
.content:after {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

See demo below:

.tile {
  position: relative;
  width: 100px;
  height: 85px;
  display: inline-block;
  border: 1px solid red;
}
#container1 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#container2 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  margin: auto;
  height: 100%;
  vertical-align: middle;
  text-align: center;
}
.content:after {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

Test


text:
Q: Make EVERY Element proportional positioned when resizing window (I use HTML, CSS, Bootstrap 3.3.7 with Gridsystem, I'm new to JS/jQuery)
Hey guys,
I'm building a SPA (single page application) that has multiple  elements, each 100vh, so it should look like 4 different "slides".
My problem:
I don't want the DIVs, images, headings and paragraphs to be responsive in terms of stacking elements under and over depending on the window size.
The elements should move pretty much proportionally however I size the browser window. Like if you make a picture bigger and smaller. Everything should shrink together with a pretty much proportional scaling if I make the window smaller.
I am sure there is the knowledge out there but please help me I'm too stupid I googled half an hour and didn't find anything.
Do you know the attributes and styles I need to apply to my elements to get rid of the ugly over-stacking of elements? To give things a proportional scaling.
A thousand thanks!

A:

.wrapper {
    display: flex;
    flex-direction: row;
    height: 100%;

}
.item {
    display: flex;
    flex-direction: row;
    height: 90vh;
}

1
2
3
4

You can use this snippet as reference. Let me know if I am wrong.

A: You don't need Flex for this requirement.

You can easily constrain blocks from stacking by simply using col-xs-*

.block {
  height: 100vh;
  background: gray;
  border: 5px solid blue;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />


text:
Q: C++. What is a subprogram and method? I have a CPP HW to be done. One question is:
1) Write a subprogram (not a method) void promptForMovie(Movie & myMovie) that .....
2) Write a method void output(ostream & out); that ....
My question is what exactly is a subprogram and a method? Which one of them means a function, and what does the other mean?
Thank you

A: Those aren't C++ terms, so you'll have to ask your professor what he or she means by them.
In other OO languages, "method" typically means what C++ calls a "member function"; that is, a function that is a member of a class, and is invoked on objects of that class.  Constrast with a "free function", which, as the name implies, is a standalone function that is not a member of any class.
I suspect that your professor means "method" to mean "member function", and subprogram to mean just a regular free function.  But who knows;  I wouldn't bet my grades on it.
Ask your professor to rephrase the question using normative terms.

A: A subprogram is a simple, old-fashioned, non-object associated function.
A method is a member function (class or instance); part of a class. It must be called with either class scope or object scope.

A: A method is another word for member function.

A: Both the terms are very overlapping and you need to clarify with your prof about them, but this is a way they can be defined

*

*Subprogram - Its part of your program which achieves a functionality for example a subprogram which stores the performes some computation on data. Now it is up to you how you define such a subprogram. You could implement it as a single monolitic function or a set of functions or maybe using classes.

*Method - another name for a function


text:
Q: Variable in a function cannot be seen out? <?php function curl($mail){

    $go = curl_init();
    $access_token = '1234567890|5fabcd37ef194fee-1752237355|JrG_CsXLkjhcQ_LeYPU.';
    curl_setopt($go, CURLOPT_URL,'https://graph.facebook.com/search?q='.$mail.'&type=user&access_token='.$access_token);
    curl_setopt($go, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
    curl_setopt($go, CURLOPT_POST, 0);
    curl_setopt($go, CURLOPT_HEADER, 0);
    curl_setopt($go, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($go, CURLOPT_SSL_VERIFYPEER, false);
    $json = curl_exec($go);
    curl_close($go);

    $arr = json_decode($json,1);
    if(isset($arr['data']['0']['id'])) {
        return $arr['data']['0']['id'];
    } else {
        return false;
    }
} ?>

I'm placing $name = $arr['data']['0']['name']; right above the return $arr['data']['0']['id']; However I cannot echo the $name variable after I run $a = curl($mail);

A: If you mean this:
function abc() {
    if(isset($arr['data']['0']['id'])) {
        $name = $arr['data']['0']['name'];
        return $arr['data']['0']['id'];
    }
    ...
}
echo $name;

It's not possible, unless you declare $name as global. The variable $name has local-scope and cannot be refered to outside the function unless it has been a global. There are other tricks (like reference-variable as function-parameter) too achieve your goal.
Edit for reference-example:
$refVar = 'foo';
function withRef(&$var) {
    echo $var; // returns 'foo'
    $var = 'bar';
    return 'return some other value';
}
$result = withRef($refVar);
echo $refVar; // now returns 'bar'

A: Of course not. A local variable stays local, it doesn't leak to the outside. Do you have the slightest idea how much havok that could cause if it worked? You could never rely on that some function's local variables don't shadow your own.
Return some data structure (e.g. array('name' => ..., 'id' => ...)) from which the caller can get the info he needs. Or use a reference parameter and set that one.

A: Unless you're updating a global variable (the use of which isn't best practice) the only way to "access" a variable that's present within a function/method is if the function/method returns the value you require or accepts the variable by reference as a parameter and updates the variable.
i.e.:
// curl returns the required value.
$name = curl('email@xxx');

or
// The curl function optionally accepts the '$name' parameter
// which can be overwritten in its original scope.
function curl($email, &name=null) {
    ...
    $name = 'xxx';
    ...
}

if(curl('email@xxx', $name))
...

This is due to the fact that variables in functions/methods/classes, etc. are only visible within the scope they're defined with. (This is a good thing.)
You can read more about this at: http://php.net/manual/en/language.variables.scope.php
Incidentally, I'd be tempted not to name a function "curl", as this is a risky in terms of clashing with an existing function - something like "fetchUserData" might be a better approach.


text:
Q: show max date of customer Demo
I have to show max date of column Visit_Date
if i search on '2013-10-29' then record shows those customers have date '2013-10-29'
but in coloumn i have to show max date of customer

A: this ...
SELECT
P_Master.PID,
Visit_Date,
(SELECT MAX(Visit_Date) FROM P_Visit v WHERE v.PID = p_Master.PID) as MaxVisit
FROM P_Master
LEFT JOIN P_VISIT
ON P_Master.PID=P_VISIT.PID
WHERE CAST(CONVERT(varchar(10), Visit_Date, 101) AS datetime)='2013-10-29'

... adds a column with the moste recent visit date

A: SELECT
P_Master.PID,
Visit_Date FROM P_Master
LEFT JOIN P_VISIT

on Visit_Date=(SELECT MAX(Visit_Date) FROM [dbo].[P_Visit] WHERE  P_Master.PID=P_VISIT.PID )

A: Try this :
SELECT
P_Master.PID,
(SELECT MAX(Visit_Date) FROM P_Master
LEFT JOIN P_VISIT ON P_Master.PID=P_VISIT.PID) AS VISIT_DATE
FROM P_Master
LEFT JOIN P_VISIT
ON P_Master.PID=P_VISIT.PID
WHERE CAST(CONVERT(varchar(10), Visit_Date, 101) AS datetime)='2013-10-29'

A: SELECT
P_Master.PID,
MAX(Visit_Date) FROM P_Master
LEFT JOIN P_VISIT
ON P_Master.PID=P_VISIT.PID

will give you the most recent visit of each Visitor


text:
Q: Re-structure sequence in existing SQL Server table I have a SQL Server 2016 table and it has than 10,000 rows. The Id column is a sequential id incremented by 1. But that Id is not in the correct order as shown in the screenshot below where 330 is missing. Is there any way to correct this sequence in an existing table?

I've tried like below but it's not working.
CREATE SEQUENCE contacts_seq
AS BIGINT
   START WITH 1
   INCREMENT BY 1
   MINVALUE 1
   MAXVALUE 99999
   NO CYCLE
   CACHE 10;

A: There is no point of fixing this - you are going to perform a operation which will block the access to your table and may affect your application performance.
And then, someone can delete the record X and you will be at the same position again.
Generally, the perpouse of id is to uniquely identify a row. If for some visualization reasons you do not want to have gaps you can use RANKING functions to fix this.
For example:
SELECT ROW_NUMBER () OVER (ORDER BY id) AS [ID]


text:
Q: Radon-Nikodym derivative of $\mu$ with respect to $\nu$ Let ($x_{n} : n \in \mathbb{N}$) be a strictly increasing sequence of real numbers (i.e.
$x_{n} < x_{n+1}, n \in \mathbb{N}$) and ($p_{n} : n \in \mathbb{N}$) be a sequence of positive numbers such that $\sum_{n=1}^{\infty}p_{n}< \infty $ Let $\mu$  be the measure defined by $\mu(A) = \sum \{p_{n}: x_{n} \in A \}$.
Let $\nu$ be the counting measure on $\mathbb{R}$. Find the Radon-Nikodym derivative of $\mu$
with respect to $\nu$.

A: You're looking for a measurable function $f$ so that
$$
\mu(A) = \int_Af\,d\nu
$$
for any measurable set $A$. Take the above equation and let $A=\{x\}$, for any $x\in\mathbb R$.
Addendum Continuing the above thought, when $A=\{x\}$, then
$$
\mu(\{x\})=\int_{\{x\}} f\,d\nu=\int f1_{\{x\}}\,d\nu = f(x)\cdot\nu(\{x\})=f(x)
$$
Thus, once we write what $\mu(\{x\})$ is, we have a formula for $f(x)$. By definition, $\mu$ of a single element set is $p_n$ if that element is $x_n$, and 0 otherwise. Thus,
$$
\frac{d\mu}{d\nu}=f(x)=\begin{cases}
p_n & x = x_n\\
0 &\text{otherwise}
\end{cases}
$$


text:
Q: Redirect to url based on server or system time I am searching for a way to redirect to a url based on fixed time when the time (system or server) hits 06:00 o'clock it needs to redirect to given url.. it needs to check the time (system or server) every second i dont know if this is possible..?

A: You could do this by using javascript. I made an example. This checks the current hour and if it is between start and end it does something. you could trigger timeRedirect(); at document load or something.
<script>
        function returnTime() {
            var d = new Date();
            var time = d.getHours();
            console.log(time);
            return time;
        }

        function timeRedirect() {
            var start = 6;
            var end = 22;
            var time = returnTime();

            if (time >= start && time <= end) {
                console.log("redirect");
            }
        }
    </script>

and for the redirect you could use this javascript, place it where the console.log(redirect) is.
window.location.replace("http://stackoverflow.com");


text:
Q: Jquery Smooth Scrolling anchor I am having a problem, so basically, I tried to add a smooth scrolling with jquery, I want to have a smooth scrolling everytime I click in my navbar anchor link, I tried to do it by myself but it's not working, any help would be much appreciated, Thanks.
// Smooth Scroll to div
$(".ser").click(function() {
  $("html, body").animate(
    {
      scrollTop: $("#services").offset().top
    },
    1000
  );
});

Kataki

          Home

          About

        Portfolio

        Testimonials

        Contact

Our Services

A: You appear to be using the slim build of jQuery, which doesn't include most of the library. Instead, you should be using the full version and just need to put your script in document ready event :

I tried this Here and it worked fine. if this doesn't solve your issue then you probably have another java script error in your code.
I hope it helps.


text:
Q: Parameter selection for RBF and polynomial kernel of SVM - Is the best 'c' (Cost parameter) same for both kernels? I have read that Cost parameter is independent of kernel used and depends on training data. After performing parameter selection for RBF, I get the best combination of 'c' and Gamma 'g'. So can I use the same 'c' for Polynomial kernel and identify a good degree 'd' ? Or can I do better if I start a fresh grid search for 'c' and 'd' ?

A: You can do better. Changing the kernel is changing the type of solution and SVM can find and how well it might overfit your data, so you need a new C. Though keeping the old C might be an acceptable guess if you use a high degree polynomial.


text:
Q: change src in iframe which depend on viewport size I'm quite new in website area
I'm trying to change src in my iframe which the src content is a table along with the width and height which make it not responsive
I'm trying to change the src which depend on the size of the viewport
here is my code

            The Free Charts are Powered by FXEmpire.com - Your Leading Financial Portal

I'm trying to change the following width inside the src automatically
src="http://tools.fxempire.com/sidebar-quotes.php?instruments=5,10,1,2,4,3&width=375&height=410&text_color=333&text_hover_color=082F60"

but i don't get any idea to do it
is there a way to do it??what I found in internet is all using either link or button to change the src

A: well because of the Access-Control-Allow-Origin you can not do it with ajax, you could do it with php, but i dont know legal/illegal this would be.
By using iframe it works this way, but only really sluggish cause the iframe needs a lot time to load...:
$(window).bind('load resize',function(){
    var windowH = $(window).height(),
        windowW = $(window).width();

    $('#iframe').attr('src','//tools.fxempire.com/sidebar-quotes.php?instruments=5,10,1,2,4,3&width='+windowW+'&height='+windowH+'&text_color=333&text_hover_color=082F60');
    $('#iframe').css({'height':windowH+'px', 'width':windowW+'px'});
})

http://jsfiddle.net/ebjsd8xx/3/
EDIT:
I changed the code a little bit for better performance but, well - the graph still loads freaking slow, but it's the same on their preview..
var resizeTimer;

$(window).load(function(){
   $(window).trigger('resize');
});

$(window).resize(function(e){
    var windowH = $(window).height(),
        windowW = $(window).width();

    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
       $('#iframe').attr('src','http://tools.fxempire.com/sidebar- quotes.php?instruments=5,10,1,2,4,3&width='+windowW+'&height='+windowH+'&text_color=333&text_hover_color=082F60');

       $('#iframe').css({'height':windowH+'px', 'width':windowW+'px'});

     }, 250);

})

http://jsfiddle.net/ebjsd8xx/7/

A: Maybe like this?
jQuery(document).ready(function(){
    var iframe=jQuery('iframe'),/** target iFrame */
        src=iframe.attr('src'); /** src of iFrame */

    /** check viewport size */
    if (window.innerWidth<945){

        /** remove width value from src */
        src=src.replace(/(&width=[0-9]+)/,'');

        /** add new width */
        src+='&width=275';

        /** PROFIT */
        iframe.attr('src',src);
    }
});

On jsfiddle

A: For me the simplest way to select a src given the viewport size was with a small script, where your iframe has the id="vid"

That will pick the source when you load the page the first time, but wouldn't change it if you resize the viewport later, foor that you need to listen to resize event (this might help).


text:
Q: Dynamically determining dependency based on user parameters Problem
I currently have a factory that depends on a few parameters to properly decide which object to return. This factory is not yet bound to DI. As I understand it NInject uses providers as a factory.
Here is what I currently have. I'll warn you it's not pretty.
public interface IRole
{
    string Name { get; }
}

public class FooRole : IRole
{
    public string Name { get { return "Foo Role"; } }
}

public class BarRole : IRole
{
    public string Name { get { return "Bar Role"; } }
}

public class FooBarRoleModule : NinjectModule
{
    public override void Load()
    {
        Bind<IRole>().ToProvider<RoleProvider>();
    }
}

public class RoleProvider : Provider<IRole>
{
    protected override IRole CreateInstance(IContext context)
    {
        var isNewParameter = context.Parameters
            .Where(x => x.Name == "isNew")
            .Select(x => x.GetValue(context))
            .Cast<bool>()
            .FirstOrDefault();

        if (isNewParameter) return new FooRole();
        return new BarRole();
    }
}

var role = kernel.Get<IRole>(new ConstructorArgument("isNew", true));
Console.WriteLine(role.Name);

I'm almost certain this is not the proper way of dynamically injecting dependencies, however it does work. And frankly, looking at what I've hacked together doesn't seem to make much sense.
The reason I need to dynamically resolve the dependency is that during the life cycle of the application the end-user can assume several roles. The sample posted above is pretty simply but the parameters (currently only isNew) would determine would object to inject.
Question
What is the proper way to use a provider with parameters not known at run time? These parameters would be passed in whenever the user triggers the code that could give them a different role.
Thank you.
Edit
public class RoleFactory : IRoleFactory
{
    public IRole Create(bool isNew)
    {
        if (isNew) return new BarRole();
        return new FooRole();
    }
}

Bind it with Bind<IRoleFactory>().To<RoleFactory>(); and use it like so.
var role = kernel.Get<IRoleFactory>();
Console.WriteLine(role.Create(true).Name);

This revised version does look better and makes more sense, however I believe I missed some key details in your post. Wanted to add that the isNew parameter would be true if the factory was called from for example a "Create New Event" button.

A: Ninject provides several machanism to handle such problems. Which one that suits best for you depends on the exact problem. Here are the most likely ones:
Use named bindings:
kernel.Bind<IRole>().To<FooRole>().Named("old");
kernel.Bind<IRole>().To<BarRole>().Named("new");
kernel.Get<IRole>("new");

Use conditional Bindings
kernel.Bind<IRole>().To<AdminRole>().When(ctx => UserHasAdminPermission())
kernel.Bind<IRole>().To<UserRole>();
kernel.Get<IRole>();


text:
Q: Python file edit I'm trying to write some text directly into a python file that I intend to store data in a dictionary. The script runs and works perfectly and writes the data I need into a key-value pair within the dictionary of the file. However when the script finishes and I check the file, at the very top of the file I get a string of diamond shapes with a question mark in them.
This is the code:
def add_new_value(key, var):
        total = ",'"+key+"'"+":"+var+" #$%$#"
        print(total)

        with open("TheseusDictionary.py","r+", encoding = "utf-8") as  intent:
             read=intent.read()
             with open("TheseusDictionary.py", "w+", encoding = "utf-8") as far:
                 print("second phase complete")
             print(read)
             read = read.replace("#$%$#",total)

             intent.write(read)

add_new_value("False", "1")

#$%$# is a comment within my dictionary file that I use to tell at what point in the file to insert the key-value pair.
What's causing these characters at the top of the file?


text:
Q: Flutter showDialog() when Firebase Cloud Messaging Notification is received I've configured Firebase Cloud Messaging (FCM) as described in the docs and it is working as expected. iOS and Android devices receive a notification, and if the notification is tapped, the application opens.
I would like to show an alert dialog when the notification is tapped and the app opens, since the notification menu on iOS does not show the entire notification body content if it exceeds a certain amount of characters.
I've tried adding to the code provided in the linked docs as follows, but showDialog requires a context. As these methods are defined in the main.dart file, no context is available?
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    if (message.notification != null) {
      showDialog(
          context: context, // suggests importing dart.js
                            // this.context => "invalid reference to 'this' expression"
          builder: (_) => AlertDialog(
                title: Text(message.notification!.title!),
                content: Text(message.notification!.body!),
              ));
    }
  });
  runApp(const MyApp());
}

A: You can use GlobalKey:
final navigatorKey = GlobalKey<NavigatorState>();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    if (message.notification != null && navigatorKey.currentContext != null) {
      showDialog(
          context: navigatorKey.currentContext,
          builder: (_) => AlertDialog(
                title: Text(message.notification!.title!),
                content: Text(message.notification!.body!),
              ));
    }
  });
  runApp(
    MaterialApp(
      home: HomePage(),
      // Setting a global key for navigator
      navigatorKey: navigatorKey,
    ),
  );
}


text:
Q: Storyboard elements invisible I don't know what button I pressed wrong in Xcode, but all elements become invisible in storyboard, preview and simulator. here is the screenshot:

It is certainly some wrong button press/click that caused this problem.
Please help!

A: From your view hierarchy, it looks like you may have placed the background image chalkboard above the rest of your UI elements. If you move chalkboard to be the first item under View, you should then see the content of all other views, rather than just their outline.


text:
Q: getting value in angularjs and quotemark I have some project written by someone else using AngularJS and i have to do small changes in it.
There are forms, where user can insert their own text, and it is then displayed on page.
But as far, as i can see, it's not save.
For example, here is fragment of TPL displaying images:

iconUrl}" alt="{$category->name}" title="{$category->name}">

Everything works fine, until user will input quote  mark in category name.
is there any way to add something like php "addslashes"? in easy way?
So far we've spend with 3 coworkers 6 hours each on so simple task and we all already hate AngularJS :) But work must be done.

A: It lookes like the category name is inserted in PHP rather than by AngularJS.
If it is Smarty, then the correct syntax would be:
iconUrl}" alt="{$category->name}"
     title="{$category->name|escape}">


text:
Q: Getting the current layer folder from a recipe
*

*I have defined a layer for my company applications and all of them uses the same license that is not standard.

*I want to put my license file on a central location (say the layer root directory).
My question is:
How can I get from inside my recipe the layer path? so I can write something like:
LIC_FILES_CHKSUM = "file://${LAYER_ROOT_PATH}/license;md5=ddab9d0ed499556ec3ce30314a81b47a

A: There is a better way to do this:
Put your license file, let's call it customlicense, in a directory in your layer (e.g. licenses), then add that path to the path where licenses are searched, in your layer.conf file:
LICENSE_PATH += "${LAYERDIR}/licenses"

Now you can reference the license inside the licenses directory without specifying a path like this:
LIC_FILES_CHKSUM = "file://customlicense;md5=ddab9d0ed499556ec3ce30314a81b47a"

A: You can refer to your layer root using the ${COREBASE} BB variable which points to the poky layer, but this may be not the best way to deal with the license file issue you mentioned.


text:
Q: Problem with accessing variable from function in another file I need to get a variable declared in a function in another file.
Requirement is that I can't call the variable from setvar() function.
set.py:
def setvar():

    global x
    x = 100

def getvar():

    return x

if __name__ == '__main__':
    setvar()
    getvar()

get.py:
import set

y = set.getvar()

print(y)

Error:
NameError: name 'x' is not defined

Why is x not defined? When I print it in getvar, x is defined.
How can I change it to get it work?

A:
Why is x not defined?

The reason is because of your line:
if __name__ == '__main__':

As you know, that line means to only run the code within the if statement if the program is being run directly, rather than being imported into another program. As you are only importing the set.py program into the get.py program, the setvar() function never got called, hence the x variable never got defined.

Requirement is that I can't call the variable from setvar function.

That's not a problem! All you'll need to do is call the setvar() function outside of the if __name__ == '__main__': block once, and the problem would be fixed:
set.py:
def setvar():

    global x
    x = 100

def getvar():

    return x

setvar()
if __name__ == '__main__':
    getvar()

get.py:
import set

y = set.getvar()

print(y)

Output:
100


text:
Q: Is this user auth secure enough? I am trying to move away from using md5() for storing and comparing passwords. So I want to start using password_hash().
Now, how I used to do it, was I would store the username and an md5 of their password in their session or cookies (if they chose "remember me"), and then check the database to see if any user existed with that username and md5'd password. I realize this is not very secure, which is why I want to stop this.
I can no longer do this because password_hash() always changes, so I cannot store a hash in their session and then check for it in the database, because I need to use password_verify on the unhashed password.
So my question is, if I store a hashed "session id" and "token" in the user table when a user successfully logs in, and then store that in the persons session/cookies along with the user id in order to check the database with, is this secure enough? When I say hashed "session id" and "token" I mean sha256'd or even md5'd hash of random large numbers...
Example:
User logs in -> hashed "session id" and "token" is store in the users cookies/session, and their row in the database is updated with the hashed "session id" and "token".
User visits site -> code checks to see if their "session id" and "token" exists in the database based on their browser session/cookie vars. If it does, it assumes that the row found represents the current user.
Any insight would be greatly appreciated.

A: What I'd do is when the user logs in, generate a unique id for his login using uinqid() (http://php.net/uniqid) and then store this in a new table. Id then check this table to see if the cookie matches the uniqid stored in the table.
You'd have to make sure the table row is deleted when the user logs in again, but this would cause a problem if the user sets a remember me on multiple devices, so I'd set an expire date in the table for each id, and the login script would:

*

*SELECT * FROM 'UNIQIDS' WHERE $current_date_and_time > 'EXPIRE' and delete all results

*Check for the existence of a cookie. If there is one and it matches the uniqid, create a session on the computer, else show login page

Upon user login:

*

*Check if there is already a uniqid stored in the table

*If there is one stored, if the current date and time is past its expire date, delete the row

*If the one has expired generate a new one with a new expiry date matching the expiry date of the cookie you are generating. If the one hasn't expired, calculate the time between now and the time it expires and create a cookie containing its value and expiring in the time you calculated.

This is highly secure as it would be hard to fake this cookie, and it doesn't ever pass the users password information to the client machine.
For even more security, you can md5 the uniqid you generate but theres no real need, as it contains no important information.
This is rather complicated but if you take it one step at a time, it shouldnt be impossible.
Good luck!

A: For best password hashes and usage and yet simple to code is below example...
$salts= ['cost' => 12];
password_hash("Password", PASSWORD_BCRYPT, $options);
$salts is an array which combines miltiple times when password_hash() is used.
PASSWORD_BCRYPT is an algo which hashes the string with "$2y$" identifier and with blowfish encryption algo. This outputs 60 char of jumbled set.


text:
Q: Draw region boundaries with Google Maps Api v3 as in Google Maps web page If I search 'province of huelva, ES' in Google Maps web page, I get a marker and the province boundaries with a color layer, that even is filled when zoom out.
It is possible to use Google Maps API for getting that polygon (or layer, json object, ...) and even change its color just providing a query string like in the Google Maps web page?
For now I must use regions LatLng values for drawing a polygon, but would be great if I can get the polygon only providing a search string.
Thank you guys!


text:
Q: Does anyone know of an antivirus that can scan multiple hard drives simultaneously? I have 5 hard drives and am so very sick of waiting for 3 hours for the virus scanner to scan each drive one at a time.  I see absolutely no reason that a virus scanner can't be threaded to scan each drive separately and at the same time.  This would cut the scan process down immensely as half of a single core is being used the way it is doing it now, when I have 4 cores that can handle 8 threads.  There has to be some virus scanner that can do this.  From all research I've done, I really can't find a single one that is capable of this.
What I want is to be able to hit the "scan all drives" button and have it kick up 5 threads scanning all 5 drives at once in parallel.  Currently it starts with C then goes to D, E etc.  With a million files involved, this serial method takes a rediculous amount of time.  I know others have said that virus scanner companies just plain don't bother to do this because most people don't have multiple drives, so they see no point in taking the time to add the functionality.  Is there not at least one scanner out there that is designed for computers with multiple drives?
Furthermore, I do not care that it would take up a lot of computer resources.  I don't see why there can't at least be an option to use multiple threads (that can be turned off if you want to run something intensive in the foreground).

A: Eset NOD 32 can do this. I just did a quick test and started up two scans:

I'm on my work laptop so it really started to slow down when started the second one.


text:
Q: Attendance tracker: Only count days Absent, Present, Late etc.. from previous days till present I have a google sheet that I use an attendance tracker for our business. This sheet reads month tabs and tally's the total Days present, Absent, Late etc..
The issue I am running into is that when someone plans a future time off or prearrange lateness I don't want it to tally that until it becomes the present day.
Essentially it should only tally up the present day and the past.
Thanks for the help.

In the "Report 2022" tab it shows Employee 15 having 6 Present days and 2 AR days. That totals to 8 "Working days count" , thats not accurate because the 2 AR days didnt happen yet; they are future dates.
If you look in the November tab it is counting the AR for future dates, I only want it to count past and present.
I haven't really came up with an idea, I tried the today function but I don't know exactly the best way to go about it.
Here is the sheet with Dummy employee data: https://docs.google.com/spreadsheets/d/103srHeFcJXvVKNn3w4ljuxAbnpMMy3YNHS4EJthx1pw/edit?usp=sharing


text:
Q: Bootstrap 3 Grid how to make nested columns all the same height as the largest I am trying to get bootstrap 3 to ensure all the columns are the same height across the page.
I can get this to work when I have 3 columns much like the example here:
How can I make Bootstrap columns all the same height?
The issue I am having is that I want to have nested columns and these nested columns will need to be x% each equalling up to 100% of the height of the largest parent column. I can't seem to find a solution to nested columns.
So I need the nested columns to fill their parent column depending on the height percent provided to the nested columns css.
The css height percentage will be provided via jquery .css()
.row {
    display: table;
}

.row [class*="col-"] {
    float: none;
    display: table-cell;
    vertical-align: top;
}

30%

20%

50%

25%

75%

    100%

A: Please try "display: flex;" property to the parent.

A: @Satheesh Kumar thanks for pointing me in the right direction. Flex was definitely what I wanted. Here is a link to what I was trying to achieve.
https://codepen.io/anon/pen/XeXXpQ

A

B

C

    .equal-height-container {
          max-width: 900px;
          margin: 0 auto;
          display: flex;
        }
    .first {
      background-color: #FFF;
      padding: 20px;
      flex: 1;
    }

    .second {
      background-color: yellow;
      flex: 2;
      display: flex;
      flex-direction: column;
    }

    .third {
      background-color: yellow;
      padding: 20px;
      flex: 2;
    }
    .second-a {
      background-color: #c0dbe2;
      flex: 2.5;
    }

    .second-b {
      background-color: #cdf1c3;
      flex: 1;
    }

    .second-c {
      background-color: red;
      flex: 1;
    }


text:
Q: Are Google OpenID Connect error responses conformant? I'm integrating to Google OpenID Connect as a relying party, using the authorization code flow. If I send in an invalid parameter in the AuthenticationRequest, e.g. an invalid value for scope, Google presents the error in a web page saying e.g. "Some requested scopes were invalid...".
The OpenID Connect spec (and the OAuth spec) clearly states that: "Unless the Redirection URI is invalid, the Authorization Server returns the Client to the Redirection URI specified in the Authorization Request with the appropriate error and state parameters."
Am I doing something wrong in my request, or am I misinterpreting the specification, or are Google just not conformant when it comes to sending error responses?

A: Sounds to me like Google is a little non-conformant here:

*

*Step 10 of my blog post shows the standards based behaviour

As a developer of an OIDC client you need to accept that some invalid input will be displayed in the browser:

*

*Invalid client_id / redirect_uri

I tend to use an invalid scope to test error responses - it is handy for that - and I guess you're doing the same.
Solutions from the big cloud vendors often have this type of annoyance - when all that we want as consumers is a standards based solution.


text:
Q: Xcode Won't Compile To Simulator I've just updated Xcode 4.5 via the App Store, from my previous version which I got from my Apple Developer Account. Since the update I can't compile any apps into the Simulator. I can compile onto a device, e.g. my iPhone.
The error I recieve is
    fatal error: file
    '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/
Developer/SDKs/iPhoneSimulator6.0.sdk/usr/include/Availability.h'
         has been modified since the precompiled header was built

1 error generated.

A: There's easiest way: Just "clean" project (Product > Clean)

A: go in ~/Library/Developer/Xcode/DerivedData/{project name + gobly-gook} and delete folder with your project name.
EDIT After suggestion
NOTE:
By default Library Folder is hidden so we can't see it.
So we have three way to use this hidden ~/Library folder
1.Unhide Library folder by following command to unhide ~/Library folder
chflags nohidden ~/Library

Now you can see Library folder as /Users//Library

2. Open GO menu of finder and press Alt key and Library will be visible as new menu item.
   Select that to open Library folder

3. You can access ~/Library folder by Terminal.

A: You can just open the Organizer (top-right corner of XCode), go to the Projects tab, select your project on the left and then delete the Derived Data.

A: This happened when I updated Xcode from 6.0.1 to 6.1
I cleaned the project and could compile successfully!!


text:
Q: PHP function include -> site not loading when I try to call a function that is included a few rows above the whole site  isnt able to reload.
$object = 'termin';
$cache_available = check_cache($object);

That´s how i call the function and the defintion look like this:
function check_cache($object){
    $file = '../../cache/' . $object . '.json';
    if(file_exists($file)){
        $time_cache = date ("H:i:s", filemtime($file));
        $time_now = date ("h:i:sa");
        $diff = strtotime($time_now) - strtotime($time_cache);

        if($diff <= 60) {return true; } //Neu genug
        else            {return false;} //Zu alt
    }
    return false;
}

Can someone tell me what causes the error.
Explanation of not loading:
---When i navigate to the folder in my browser (localhost, xampp) and click on the file to open it loads for a short time but then displays the directory again.

A: That check_cache does not look right. It has wrong path checking to begin with and a to long return statement. With if and else. I rewrote it, try it and see if it works.
function check_cache($object) {
    $file = __DIR__ . '/../../cache/' . $object . '.json';

    if(file_exists($file)){
        $time_cache = date ("H:i:s", filemtime($file));
        $time_now = date("H:i:s");
        $diff = strtotime($time_now) - strtotime($time_cache);

        return $diff <= 60;
    }

    return false;
}

A: First your filemtime() function needs to be debugged to see if possible error could be found.
Secondly, your file path could be the problem
Thirdly, Your time format do not correlate. I recommend you use the same format i.e
$time_cache = date ("H:i:s", filemtime($file));
    $time_now = date ("H:i:s");//the a has been removed
    $diff = strtotime($time_now) - strtotime($time_cache);

A: So the unit for $diff is seconds. Could it be that your display of the file is dependant upon this function evaluating to true and that is only the case for one minute after writing the file to the cache? I really don't have enough information to go on here but that code should work as intended. I tested your function and it works as expected on my machine. Can we see the code for the page that where it is going back to the directory after a period of time? I still did not really understand what you were saying with that.
Can be cleaned up a bit here are my suggestions & sorry to be that guy.
function check_cache($object)
{
    $file = '../../cache/' . $object . '.json';
    if(file_exists($file)){
        $time_cache = date ("H:i:s", filemtime($file));
        return strtotime("now") - strtotime($time_cache) <= 60;
    }
    return false;
}

or
function check_cache($object)
{
    $file = '../../cache/' . $object . '.json';
    return file_exists($file) ? strtotime("now") - filemtime($file) <= 60 : false;
}


text:
Q: JQuery tooltip open event not working as expected I am trying to make my tooltips change position depending on the orientation of the .menu container. For some reason they only change position when the second open event is fired.
$(".menu button").tooltip({
  position: {
    my: "left center",
    at: "right+10  center"
  },
  open: function () {
    if ($(".menu").hasClass("vertical")) {
      $(this).tooltip("option", "position", {
        my: "left center",
        at: "right+10  center"
      });
    } else {
      $(this).tooltip("option", "position", {
        my: "center bottom",
        at: "center top-10"
      });
    }
  }
});

Is there anyway to make the tooltips change position when the first open event is fired?

A: It is because when the open event is fired the display position is already calculated... so any changes you do after that will be reflected only in the next display.
The following solution is a hack, the right solution will be is to change the tooltip solution when the orientation is actually changed.
$(".menu button").tooltip({
    position: {
        my: "left center",
        at: "right+10  center"
    },
    open: function () {
        var $this = $(this),
            pos = $this.data('position');
        if ($(".menu").hasClass("vertical") && pos != 'vertical') {
            setTimeout(function () {
                $this.tooltip("option", "position", {
                    my: "left center",
                    at: "right+10  center"
                }).data('position', 'vertical').tooltip('close').tooltip('open');
            })
        } else if (!$(".menu").hasClass("vertical") && pos != 'horizontal') {
            setTimeout(function () {
                $this.tooltip("option", "position", {
                    my: "center bottom",
                    at: "center top-10"
                }).data('position', 'horizontal').tooltip('close').tooltip('open');
            })
        }
    }
});

Demo: Fiddle


text:
Q: Is $f =g$ when $g=\limsup f_n$? f and g are two functions . Is $f =g$ $\mu$ a.e when $g=\limsup f_n$ when n -> infinity ?
we have $f_n$ --> f $\mu$ a.e , $f_n$ is measurable for all n in N.
I think they will equal because when f_n - > f , g = limsup f  = f at each x that makes f_n --> f.

A: Yes these are the same. The pointwise limit is the same as the pointwise limsup everywhere where the limit exists.


text:
Q: @AuditJoinTable not working while auditing the many to many relations using Hibernate envers I am using Spring Boot 1.3.2 and Spring Data JPA 1.9.4 with MS Sql server2014 database for process for process of mapping a many-to-many relationship.
I have two tables with entities Book & Publisher. where they have many to many relations ship with BookPublisher table and BookPublisher entity.
I used hibernate envers 4.3.3 final to audit the each entity. Book_AUD and Publisher_AUD and BookPublisher_AUD tables created automatially  by placing the @Audited annotation on each entity.
Book_AUD and Publisher_AUD are working properly to audit the inserting, updating and deleting.
Record is getting saved to join table when save the record in Book table with set of publisher records. But auditing happen only in inserting BookPublisher_AUD table, not in updating the deleting.
I used @AuditJoinTable annotation to audit the relation mapping table as below.
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "BookPublisher", joinColumns = @JoinColumn(name = "BookId", referencedColumnName = "BookId"), inverseJoinColumns = @JoinColumn(name = "PublisherId ", referencedColumnName = "PublisherId"))
    @WhereJoinTable(clause = "isActive = 1 ")
    @AuditJoinTable
    private Set<Publisher> publishers;

Is there any way to audit the relational mapping table  in hibernate envers or any wrong in using @AuditJoinTable annotation?


text:
Q: "We have detected a strange activity from this IP address" message At 15:04 UTC, during the Read-only test - August 1, 2015, trying to open my Stack Overflow profile page I received a message saying something like

"We have detected a strange activity from this IP address"

Only text: no style, no topbar, zilch. It has happened only once.
I work and use Stack Overflow in different libraries scattered in four cities, so my public IP address may be shared by other Stack Overflow and Stack Exchange users.
What I ask is:

*

*Do the various background processes that control  the compliance with
rules, take into account the public or private address of my PC? Was
the above message talking about my public or private IP address?

*Was the above message somehow caused by the Read-only test? Or some misbehavior of some users has caused it?

*Should I worry about some retaliation from some user? Although I have some limitations in the language, I can assert that I have never offended anyone.
I love this network, my graduation thesis was a project almost identical to the idea of Stack Overflow, and I don't want either to give or cause any problems of any kind.
Note: As you can see on my Stack Overflow reputation tab, on that day I had not received either upvotes or downvotes.

A: Yes, it was caused by that read-only test. The new Denver IP range didn't get added and it briefly rate limited all traffic to the network. The error was fixed after about 5 minutes, but not before about 80 people emailed us about the problem. ;)
So you have nothing to worry about. It was completely an error on our end.


text:
Q: Passing array in struct by reference to coder.ceval I have a struct with very large arrays in it. I use MATLAB coder to generate C code.
In my generated code I wish to call some C function and pass by reference one of the arrays.
For example:
coder.ceval('Foo',coder.ref(MyStruct.VeryLargeArray));

This is not allowed by MATLAB coder and I get the error:

coder.ref may only be applied to an expression of the type V or V(E) ...

Since MyStruct.VeryLargeArray is very large, as the name suggests, I wish to avoid the abvious solution of copying it to a temporary varliable:
UnnecessaryTempVar = MyStruct.VeryLargeArray;
coder.ceval('Foo',coder.ref(UnnecessaryTempVar));

Any ideas for a workaround?

A: You could write a C wrapper for Foo that accepts a pointer to a struct and forwards the underlying data pointer, MyStruct->VeryLargeArray, to Foo.
MATLAB Code passStruct.m:
function y = passStruct(x)
%#codegen
coder.cinclude('Foo.h');
s.f = x;
coder.cstructname(s, 'wrapperStruct_T');
y = 10;
y = coder.ceval('WrapFoo', coder.ref(s));

Header file Foo.h:
/* Include generated header to get struct definition */
#include "passStruct.h"
double WrapFoo(wrapperStruct_T *s);
double Foo(double *x);

Source file Foo.c:
#include "Foo.h"
double WrapFoo(wrapperStruct_T *s)
{
    return Foo(s->f);
}

double Foo(double *x)
{
    return 2.0*x[0];
}

Codegen command:
codegen passStruct -args zeros(1000) Foo.c -report

A: Although the solution proposed by lilbill39 will work, I came across a different approach:
function y = passStruct(x)
%#codegen
s.f = x;
ps = coder.opaque('double *','&s.f[0]');
y = 0;
y = coder.ceval('Foo', ps);

However, it assumes that the name of the struct is not changed in the code generation process.


text:
Q: jQuery is not defined Error and No method i m using this autocomplete function. I run it in new project and it really worked great. I moved it to my main project but it didnt work.
I looked to javascript console and i get
Uncaught ReferenceError: jQuery is not defined jquery.autocomplete.js:2
(anonymous function)

Uncaught TypeError: Object [object Object] has no method 'autocomplete'
(anonymous function)
jQuery.fn.extend.ready jquery.js:2299
jQuery.extend.ready.jQuery.readyList jquery.js:2319
jQuery.extend.each jquery.js:745
jQuery.extend.ready jquery.js:2318

I checked all paths.
 <script src="jscripts/jquery.js" type="text/javascript"></script>
 <link rel="stylesheet" href="skins/skin_1/jquery.autocomplete.css" type="text/css" />
 <script type="text/javascript" src="jscripts/jquery.autocomplete.js"></script>

<script type="text/javascript">
     $(document).ready(function () {
         $("#Size").autocomplete("AutocompleteData.ashx");
     });
     $(document).ready(function () {
         $("#Color").autocomplete("AutoCompleteData2.ashx");
     });
     $(document).ready(function () {
         $("#Brand").autocomplete("AutoCompleteData3.ashx");
     });
  </script>

<input type="text" ID="Size" runat="server"/>
<input type="text" ID="Color" runat="server"/>
<input type="text" ID="Brand" runat="server"/>

It works in normal aspx,html pages. But i have to put it in .config page.
It starts like this. I dont know how can i explain it.
<PackageTransform>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asp="urn:asp" exclude-result-prefixes="asp">

Normally i have another jQuery and it works. Like this;
function moveScroller() {
            var a = function () {
            var b = $(window).scrollTop();
            var d = $("#scroller-anchor").offset().top;
            var c = $("#scroller");
            if (b > d) {
            c.css({ position: "fixed", top: "0px" })
            } else {
            if (d >= b) {
            c.css({ position: "relative", top: "" })
            }
            }
            };
            $(window).scroll(a); a()
            }

How can i run it, or do you have any other autocomplete system which using database, keyboard arrows and mouse. Thank you, sorry for my english.

A: Check for the jscripts/jquery.js file .You said you have moved your project so may be that file is not completely uploaded and also check for jscripts/jquery.autocomplete.js
compare their size and check are they completele uploaded ?


text:
Q: Can't figure out how to solve matrix equation Ax=0 I tried googling how to solve this matrix through RREF and parametric variables but failed to find something that works similarly to try and solve myself.
A is a 2x3 matrix with the values going [ 2 -1 -1 : 1 -2  2 ]
(imagine the set after the colon to be under the first set)
x is [x_1, x_2, x_3] but obviously a column instead of a row and for lack of subscript key I just used "_#" to denote the same thing.
0 is a 2 row x 1 column matrix with two 0's.
To start, I wrote out the matrix's into 2 equations.
2x_1 - x_2 - x_3 = 0
x_1 - 2x_2 + 2x_3 = 0
Then I turned it into a simplified coefficient matrix.
[ 2 -1 -1 0: 1 -2  2 0] (with the second set of numbers past the colon under the first set)
Afterward, I reduced it into RREF form to get:
[ 1 0 (-4/3) 0 : 0 1 (-5/3) 0 ] (with the second set of numbers past the colon under the first set)
Once I got this, I turned the matrix back to these equations:
X_1 - (4/3)X_3 = 0
X_2 - (5/3)X_3 = 0
So then I set X_1 = (4/3)X_3 and X_2 = (5/3)X_3. I then tried setting X_3 to t to try and see if I could finagle an answer by solving for 't'. So far, my answers have been wrong every time in comparison to the answer my book gives. Can someone tell me if I messed up somewhere? I deduced it would have to be from my matrix reduction but I did it over a few times in different ways to make sure but I still can't seem to get the answer...

A: The general method for solving a linear equation
$$Ax=b$$
is to utilize the Moore-Penrose inverse $A^+$ and the associated nullspace projector $$P=(I-A^+A)$$
With these two matrices, the general solution can be written as
$$x=A^+b + Py$$
where the vector $y$ is completely arbitrary.
Applied to the current problem this technique yields
$$\eqalign{
&A=\begin{bmatrix}2&-1&-1\\1&-2&2\end{bmatrix},\quad
&A^+=\frac{1}{50}\begin{bmatrix}\;\;16&\;\;\;2\\\;-5&-10\\-13&\;\;14\end{bmatrix},\quad
P=\frac{1}{50}\begin{bmatrix}16&20&12\\20&25&15\\12&15&9\end{bmatrix} \\
&
b=\begin{bmatrix}0\\0\\0\end{bmatrix}
,\quad
p=\begin{bmatrix}4\\5\\3\end{bmatrix}
&\implies P=\frac{\;\;pp^T}{50},\quad
x=0+\frac{p(p^Ty)}{50}
 = \lambda p
 = \lambda\begin{bmatrix}4\\5\\3\end{bmatrix}
\\
}$$

A: You are right, indeed by the augmented matrix for the system and by row operation we obtain
$$\left[\begin{array}{ccc|c}
      2&   -1&   -1&  0\\
      1&   -2&  2&  0
    \end{array}\right]\to \left[\begin{array}{ccc|c}
      2&   -1&   -1&  0\\
      0&   -3&  5&  0
    \end{array}\right]\to \left[\begin{array}{ccc|c}
      6&   0&   -8&  0\\
      0&   -3&  5&  0
    \end{array}\right]$$
from which we obtain

*

*$x_1=\frac43 x_3$

*$x_2=\frac 53 x_3$
that means we have a free parameter and by $x_3=t$ the genral solution is
$$(x_1,x_2,x_3)=t\left(\frac43,\frac53,1\right)$$
which is equivalent to
$$(x_1,x_2,x_3)=t\left(4,5,3\right)$$


text:
Q: NavHostFragment and ViewPager2 doesn't work at the same time I have an app, that has a few fragments in it. I'm using ViewPager 2 to swipe between them.
Lately I've added Navigation component to make a way to get into one specific fragment that is not avilable for user just by swipe.
I've found out, that whever I place FragmentContainerView over the ViewPager2 in my MainActivity layout, I can go to this unvailable fragment, but I can't swipe. Same thing whener I switch FragmentContainerView with ViewPager2. Is there any way to make them both work at the same time?
Here's my layout
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

A: They can work together but not like this, at least not for what you want.
Navigation component is made to handle traveling between destinations. ViewPager2 is a widget to be used in a destination, not for traveling between them.
For what you are describing you will need to have FragmentA that will contain ViewPager2 where all of the swiping will take place and handling of fragments (let's say Fragment1, Fragment2, Fragment3) in the ViewPager2.
Those fragments will have nothing to do with the Navigation component.
Navigation component will come to play when you will want to go from FragmentA to FragmentB.


text:
Q: Display a message on Alcatel CLI before login I would like to know if there is a way to show a message on the CLI when connecting to an Alcatel switch before it asks to enter login and password.
I'm doing that because I would like to set a custom ID for each switch and knowing the ID without having to log in.
(Another solution would be to replace the word login by the message I want to show)

A: The answer is given right here :
https://www.manualslib.com/manual/207427/Alcatel-Lucent-Omniswitch-6850-48.html?page=83#manual

Modifying the Text Display Before Login

By default, the switch does not display any text before the login prompt for any CLI session.
At initial bootup, the switch creates a pre_banner.txt file in the /flash/switch directory. The file is empty
and may be edited to include text that you want to display before the login prompt.

With the following result :
Please supply your user name and password at the prompts.

login : user123
password :

Old Answer
I have found some information for you inside a manual of one switch:
https://www.manualslib.com/manual/207427/Alcatel-Lucent-Omniswitch-6850-48.html?page=82

The Login Banner feature allows you to change the banner that displays whenever someone logs into the switch. This feature can be used to display messages about user authorization and security

Two steps are required to change the login banner. These steps are listed here:

*

*Create a text file that contains the banner you want to display in the switch's /flash/switch directory.

*Enable the text file by entering the session banner CLI command followed by the filename

[omissis]

If you want the login banner in the text file to apply to FTP switch sessions, execute the following CLI command where the text filename is firstbanner.txt.-> session banner ftp /flash/switch/firstbanner.txt

If you want the login banner in the text file to apply to CLI switch sessions, execute the following CLI command where the text filename is secondbanner.txt.-> session banner cli /flash/switch/secondbanner.txt

A: you have to create the pre_banner.txt file in the switch directory. This should solve your question


text:
Q: Notation to Replace the Input to a Function On pg. 54 of a Quantum Computing textbook (Nielsen and Chuang), it's said that:

it is not surprising that similar techniques can be used to compress the source so that only $H(p, 1 − p)$ qubits are required to store the compressed source, where $H(·)$ is again the Shannon entropy
function.

I'm confused with the use of the symbol "·" and I wonder what's the name of it as how it's used.


text:
Q: unable to refer System.Threading.Volatile I've just installed final version of .NET Framework 4.5 and rebooted. I'm using VS 2010.
I've tried to use new System.Threading.Volatile class but I receive "Cannot resolve symbol" error when using System.Threading.Volatile.
In project properties target framework version is ".NET Framework 4" which I suppose includes 4.5
Why I can't refer System.Threading.Volatile and how to resolve my problem? Have I to use VS 2012 for that?

A: You can't use .NET 4.5 from Visual Studio 2010.  You need to install VS 2012 to target .NET 4.5 and use new types defined only in 4.5.

In project properties target framework version is ".NET Framework 4" which I suppose includes 4.5

No, it does not.  It only includes classes and types in .NET 4.  You need to target ".NET Framework 4.5", which requires VS 2012.


text:
Q: How do I set logging level in Glassfish? We are running glassfish 2.1; I want to reduce the chattiness of the logging to server.log but cannot find what config file allows me to do this.  (I'm assuming this will use log4J syntax.)  thanks!

A: I think the ans need an update in 2018 (after 6 long yrs). The log level option can be viewed by traversing following tabs in left hand side of Glassfish (4.x) Admin Console:
Configuration -> Server Config -> Logger Settings.
Then select: 'Logger Levels'.

Note:
Different Log Levels in order are:
SEVERE, WARNING, INFO, CONFIG, FINE, FINER, and FINEST.
where SEVERE is least detailed and FINEST is most detailed.

A: Glassfish uses JDK (java.util) logging, which is configured in the admin UI, typically running http://server:4848
Depending on whether you installed it as developer profile (the default) or clustering, the logging settings will be two different places.
Developer profile: Application Server/Logging/Log Levels
Cluster profile: Configurations/cluster-config/logger settings/levels


text:
Q: Parameter error when running selenium webdriver test case in Java I'm trying to run this method in Selenium webdriver but I continue to get this error:
org.testng.TestNGException:
Method PopulateBorrower requires 2 parameters but 0 were supplied in the @Test annotation.
    at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:198)
    at org.testng.internal.Parameters.createParameters(Parameters.java:134)
    at org.testng.internal.Parameters.createParameters(Parameters.java:370)
    at org.testng.internal.Parameters.handleParameters(Parameters.java:447)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1384)
    at org.testng.internal.Invoker.createParameters(Invoker.java:1075)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1180)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:128)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1203)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
    at org.testng.TestNG.run(TestNG.java:1036)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

--------->what am I doing wrong? The code is below. I have its's setup in a SetUpBase separate class.
@Test
public static void PopulateBorrower(String PrimaryBorrowerBaseName1,String PrimaryBorrowerBaseName)
{
    String fName= PrimaryBorrowerInputDictionary.get(BorrowerFirstNameElement);
    String lName=PrimaryBorrowerInputDictionary.get(BorrowerLastNameElement);
    String suffix=PrimaryBorrowerInputDictionary.get(BorrowerSuffixElement);
    String social=PrimaryBorrowerInputDictionary.get(BorrowerSocialSecurityNumberElement);
    String homePhone=PrimaryBorrowerInputDictionary.get(BorrowerHomePhoneNumberElement);
    String schoolYears=PrimaryBorrowerInputDictionary.get(BorrowerYearsInSchoolElement);

    driver.findElement(By.id(PrimaryBorrowerBaseName1 + BorrowerFirstNameElement)).sendKeys(fName);
    driver.findElement(By.id(PrimaryBorrowerBaseName1 + BorrowerLastNameElement)).sendKeys(lName);
    driver.findElement(By.id(PrimaryBorrowerBaseName1 + BorrowerSuffixElement)).sendKeys(suffix);
    driver.findElement(By.name(PrimaryBorrowerBaseName + BorrowerHomePhoneNumberElement)).sendKeys(social);

    driver.findElement(By.name(PrimaryBorrowerBaseName + BorrowerHomePhoneNumberElement)).sendKeys(homePhone);
    driver.findElement(By.name(PrimaryBorrowerBaseName + BorrowerYearsInSchoolElement)).sendKeys(schoolYears);
    driver.findElement(By.name(PrimaryBorrowerBaseName +BorrowerMarriageStatusElement )).click();

    assertEquals(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerFirstNameElement))
                .getText(), fName);

    assertEquals(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerLastNameElement))
            .getText(), lName);

    assertEquals(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerSuffixElement))
            .getText(), suffix);

    assertEquals(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerHomePhoneNumberElement))
            .getText(), homePhone);

    assertEquals(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerYearsInSchoolElement))
            .getText(), schoolYears);

    assertTrue(driver.findElement(By.id(PrimaryBorrowerBaseName + BorrowerMarriageStatusElement))
            .isSelected());
 }

A: The TestNGException is coming because your @Test method requires 2 parameters (i.e. PrimaryBorrowerBaseName1 and PrimaryBorrowerBaseName) but you are not passing them.
To solve this you need to supply these parameters when TestNG invokes your @Test method (i.e. PopulateBorrower). TestNG provides 2 ways to do the same.
Supplying parameters in TestNG

*

*Parameters from testng.xml

*Parameters with DataProviders

You can try any one of below approach to solve your issue.

Solution 1: Parameters from testng.xml
The testng.xml file:
<suite name="My Suite">
    <parameter name="primary-borrower-base-name1" value="value1" />
    <parameter name="primary-borrower-base-name"  value="value"/>
    <test name="My Test">
        <classes>
            <class
                name="yourpackage.PopulateBorrowerTestClass2" />
        </classes>
    </test>
</suite>

Your test class:
package yourpackage;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class PopulateBorrowerTestClass2 {

    @Parameters({ "primary-borrower-base-name1", "primary-borrower-base-name" })
    @Test
    public static void PopulateBorrower(String PrimaryBorrowerBaseName1, String PrimaryBorrowerBaseName)
    {
        System.out.println(PrimaryBorrowerBaseName1 + " " + PrimaryBorrowerBaseName);
       //your all code goes here
     }
}

Solution 2: Parameters with DataProviders
The testng.xml file:
<suite name="My Suite">
    <test name="My Test">
        <classes>
            <class name="yourpackage.PopulateBorrowerTestClass1" />
        </classes>
    </test>
</suite>

Your test class:
package yourpackage;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class PopulateBorrowerTestClass1 {

    //This method will provide data to any test method that declares that its Data Provider
    //is named "test1"
    @DataProvider(name = "test1")
    public Object[][] createData1() {
     return new Object[][] {
       { "PrimaryBorrowerBaseName1Value", "PrimaryBorrowerBaseNameValue" }
     };
    }

    //This test method declares that its data should be supplied by the Data Provider
    //named "test1"
    @Test(dataProvider = "test1")
    public static void PopulateBorrower(String PrimaryBorrowerBaseName1, String PrimaryBorrowerBaseName)
    {
        System.out.println(PrimaryBorrowerBaseName1 + " " + PrimaryBorrowerBaseName);
       //your all code goes here
     }
}

A: Why do you use static function as a test? It should not be static!

A: Does your unit test use the @DataProvider annotation (@Parameterized in JUnit 4.11)?  If so, and you have defined a data provider method, then your @Test annotation needs to recognize it as such like so:
@Test
@Parameters(value="number", value2="digit")
public void parameterIntTest(int number, int digit) {
    System.out.println("Parameterized Number is : " + number + " and " + digit);
}


text:
Q: How to create single jar with dependencies in maven I am trying to create single fat jar using maven assembly plugin but somehow after running maven clean install it give 2 jars, one is client-1.0-SNAPSHOT.jar and other one is client-1.0-SNAPSHOT-jar-with-dependencies.jar.
I am only interested to create a jar with dependencies so dont know why the other jar is also creating by this assemble plugin.
Can someone tell me how to eliminate this jar Or should i use some other maven command rather than clean install ?
<build>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <resources>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <excludes>
                    <exclude>*.properties</exclude>
                </excludes>
            </resource>
        </resources>

        <plugins>

            <!-- download source code in Eclipse, best practice -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                </configuration>
            </plugin>

            <!-- Set a compiler level -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>

            <!-- Maven Assembly Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <!-- get all project dependencies -->
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    -->
                    <!-- MainClass in mainfest make a executable jar -->
                    <archive>
                        <manifest>
                            <mainClass>com.app.MainApp</mainClass>
                        </manifest>
                    </archive>

                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <!-- bind to the packaging phase -->
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.5</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <!-- overwrite! -->
                            <overwrite>true</overwrite>
                            <outputDirectory>${project.basedir}/target</outputDirectory>
                            <resources>

                                <resource>
                                    <directory>${project.basedir}/</directory>
                                    <includes>
                                        <include>*.properties</include>
                                    </includes>
                                </resource>

                            </resources>
                        </configuration>
                    </execution>

                </executions>
            </plugin>
        </plugins>
    </build>


text:
Q: How to deal with mixing models between services? I am working on an API that has a User resource to represent the current user and a User service that handles business logic for representations of this user.
I need to introduce an Organization resource that has Members, which are effectively Users within an organization.
I need to build a resource that is represented as /:organizationId/members that pulls a collection of Users that belong to an organization.
In my database, a user belongs to an organization if their id is in a row with the matching organization id in a join table.  I can very easily query this and get all of the information I need.
However, I do not want my organization service to be querying any tables that have to deal with user data as I anticipate I will inevitably need to add a new column to the user data.  I'd like all management of user data to occur within the User service.
One solution I had was to return a set of ids for users belonging to that organization, and then send that to the User service to get the user data, but then I lose the ability to effectively sort by name and limit the length of the query since that is handled by the SQL.
Is there a best practice for handling this type of problem?

A: In this case probably the best approach is to create a "membership" service.  Organization, Users, and Membership.
Membership would have a GET to return all the members for an organization.  This would return an array of member DTOs.  Other operations may include Add/Remove membership (POST/DELETE).  Also, if the joiner table had some properties perhaps an update (PATCH) membership.   Other potential GETs would be show all organizations for a user in addition to get members for organization mentioned earlier.
By returning a different dto, you don't have to return all the user or organization data, just a small proxy object.  If you need the full org or user, just call those service gets to return those object(s) if needed.


text:
Q: Select data from multiple tables in RDS using DataPipeline Is there a way (using existing templates) to select data from multiple tables by joining them using AWS datapipeline. My usecase requires me to combine data from multiple RDS tables to export to Redshift.
For eg. RDS has Tables School, Student, District. I want to export data like:-
select sch.Name, stu.Name, dis.Name from School sch inner join Student stu on stu.schoolid = sch.id inner join District dis on dis.id = sch.districtid;

Is there a way in AWS Datapipeline for me to select data from multiple tables ?

A: There is a field name "select Query" in Data node. You can write your transformation SQL which can pull out data from different tables.
Please refer below image.
Select Query in Data Node

A: You can create a single pipeline that will have different activities for each table that you want to replicate.
This way, you won't have to write join query to replicate multiple tables.
Answering to an old question, so that it can help others still searching for something like this.


text:
Q: Vue - unable to access component functions/data within handler method I have a function in Vue called doSomething() and a event handler within it called onmessage() that is also it's own function. However within onmessage I cannot access anything within the component. I cannot access the components variables or methods.
How can I gain access to the components data from within that function?
export default {
  name: "component",
  data() {
    return {
      name: "Jeb",
      connection: null
      }
  },
  methods: {
    doSomething: function() {

      this.connection = new WebSocket("ws://localhost:2000");
      this.connection.onmessage = function(event) {

         console.log(this.name); //UNDEFINED
         this.doAnotherThing(); //ERROR
      };
      ...
      ...
    },
    doAnotherThing: function() {
      ...
    }
  }
};

I apologize in advance if this question has been asked before. I have tried searching for it for some time but couldn't find a similar post.

A: Change way how you organize the code of methods:
doSomething() {
  this.connection = new WebSocket("ws://localhost:2000");
  ...


text:
Q: How to hide a property of custom collection while using DataGridView DataSource? I have a custom collection let's say
MyClass
{
    prop Name;
    prop Address;
    prop isRequired;
}

MyCustomCollection : List<MyClass>
{

}

When I do
MyCustomCollection collection = new  MyCustomCollection ();
datagridView.DataSource = collection;

The datagridview is populated with three columns Name, address , isRequired..
I want to hide isRequired property from the datagrid view how can i do that...
and also I want to use it as a property to check in another classes...

A: I used [Browsable(false)]
MyClass
{
     prop Name;
   prop Address;
   [Browsable(false)]
    prop isRequired;
}
to hide the column

A: the Browsable attribute is a good option indeed. You could also set AutoGenerateColumns to false and create the columns manually...

A: Or you can set the visible property of the column to false.
For each set of business data I want to display, I keep track of the # of leftmost-columns I want hidden because they hold PK values.
Here's a sample:
        dgvDisplaySet.DataSource = _setSource
    gridColsToHide = _displaySet.hidePKFields
    For gridCol = 0 To dgvDisplaySet.Columns.Count - 1
        dgvDisplaySet.Columns(gridCol).Visible = (gridCol >= gridColsToHide)
    Next


text:
Q: find point given a line and two arbitrary points on one side of the line I have geometrical question which I'm trying to solve for a while now and it goes like this :
given a Line AB and 2 arbitrary points on one side of that line (C and D).
suggest a method to find a point M along AB so that ∠CMA = ∠DMB

can I please get direction to the solution ?
Thanks!

A: Hint: Having $\angle AMC = DMB$ is equivalent to having the perpendicular to $AB$ through $M$ to bisect $\angle CMD$. Recall that a light ray reflecting off a mirror has exactly that property, which means that $M$ is where $C$ needs to look at to see $D$ in the mirror $AB$. Thus you can construct $M$ by constructing $D'$ to be the reflection of $D$ in $AB$ and then $M = AB \cap CD'$.

A: Here is one way. From $C$ and $D$, draw perpendicular lines to the line $AB$. So you get $CC_1$ and $DD_1$.
Now, if you find a point $M$ on $AB$ that satisfies the following equation, then you have the required point.
$\frac{C_1M}{D_2M}=\frac{C_1C}{D_1D}$
It is easy to see that triangles $CC_1M$ and $DD_1M$ are similar.
Now it remains to find a way to find edges that their length add up to the length of $C_1D_1$ and have the required fraction. An easy way is to draw an edge with length $|CC_1|+|DD_1|$ from $C_1$ (with an arbitrary angle, such that the angle between the edge and $AB$ is less than $90$ degrees). The end point is called $X$. make edges $CC_1$ and $DD_1$ on $C_1X$ and call the point that they meet $Y$. Then connect $X$ to $D_1$. Draw a line parallel to $D_1X$ from $Y$ to intersect the line $AB$. the intersection is $M$.


text:
Q: Cannot set property 'textContent' of null error I am getting this error in SAP UI5 app.
updateFinished: function (count) {
    itemCount = count.getParameters().total;
    var labelId = thats2.getView().byId("page").getCustomHeader().getContentMiddle()[0].sId;
    document.getElementById(labelId).textContent = "Requests (" + itemCount + ")";
}

what is wrong with the code. Do I need to do null check before assignment?
Thanks

A: document.getElementById() tries to retrieve an element by using it's HTML id attribute, which may or may not exist.
var labelId = thats2.getView().byId("page").getCustomHeader().getContentMiddle()[0].sId;

Here you are getting the UI5 element id, mapped to HTML attribute data-sap-ui.
In order to get the UI5 element no matter if it has HTML id attribute or not you can do:
sap.ui.getCore().byId(labelId).textContent = "Requests (" + itemCount + ")";

Anyway, it'd be still a good practice to check if sap.ui.getCore().byId(labelId) exists.


text:
Q: What is the current status of Pluto? Pluto has been designated a planet in our solar system for years (ever since it was discovered in the last century), but in 2006 it was demoted.
What caused this decision? And is there a chance that it could be reversed?
Edit: well, http://www.dailygalaxy.com/my_weblog/2017/03/nasas-new-horizon-astronomers-declare-pluto-is-a-planet-so-is-jupiters-ocean-moon-europa.html is interesting; this is science, so anything could (potentially) change.

A: Pluto is still considered a dwarf planet. This was because it did not meet the full criteria for being classified as a planet. Most notably it did not clear its orbit of other debris.
This is still considered controversial as many scientist do not agree with the definition of what a planet is and still consider Pluto to meet planet criteria. So it is possible that this may change especially if the criteria for what is a planet changes due to new discoveries. This is very possible with the work the Kepler telescope is producing. As we discover new planets in large numbers you can be sure they will be finding ever different planets that will force a redefinition of what a planet is.

A: Pluto is now classified as a dwarf planet.  The main difference between a planet and a dwarf planet has to do with the requirement that a planet clear out the material in and near its orbit.  Planets do this, dwarf planets do not.
The reclassification was triggered by the discovery of many additional object (the Edgeworth-Kuiper Belt) out beyond the orbit of Neptune.  Some of the objects are nearly as big as (and is a few cases, possibly bigger than) Pluto and in very similar orbits.  Thus it was realized that Pluto was just the largest of a large number of objects in the outer solar system.
This is simply science at work.  At the local university, we have an Astronomy textbook from the 1800's that lists the 12 planets:  Mercury, Venus, Earth, Mars, Ceres, Pallas, Juno, Vesta, Jupiter, Saturn, Uranus, and Neptune.  However, as more objects were detected between Mars and Jupiter, it was realized this was a new class of object and the middle four were downgraded from planet status to asteroids.  It is the same process at work today out in the outer solar system.

A: As many already said, Pluto is now considered a "dwarf planet"
For your second question, there is no chance that Pluto will be reclassified as a planet again.

A: Pluto has been reclassified as a dwarf planet.
It was reclassified as such because a growing number of objects were found similar to Pluto, which exhibited at least one notable difference from the other planets.  The choice would have been to accept these other objects as planets or to develop a new class of object.
The primary features of a planet are that it has an orbital path 'clear' of other debris, orbits around the sun, and is massive enough to maintain hydrostatic equilibrium.  Pluto (as well as other dwarf planets) fail to meet the first criterion.

A: If you are interested, there is an audio recording of the IAU General Assembly session on the definition of a planet http://www.jodcast.net/archive/200608IAU/

A: I don't really care what the IAU voted. Pluto will always be a planet in my book. Astronomy is full of historic inaccuracies that we perpetuate for tradition sake. Some examples that come to mind are early/late-type galaxies, Population I/II/III stars, and brown dwarfs.

A: Mercury, Venus, Earth, Mars, Vesta, Juno, Ceres, Pallas, Jupiter, Saturn and Uranus are the primary planets in the Solar System.


text:
Q: Use CodeMirror editor for both CSS and HTML on the same page I am trying to load the CodeMirror editor to be used in a plugin backend. Some textareas are for HTML and some are for CSS. I am quite new to WP development, so pardon my ignorance, but doing this:
    add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');
    function joermo_enqueue_scripts($hook) {
        $joermo_html_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html'));
        $joermo_css_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css'));
        wp_localize_script('jquery', 'joermo_html_code', $joermo_html_code);
        wp_localize_script('jquery', 'joermo_css_code', $joermo_css_code);

        wp_enqueue_script('wp-theme-plugin-editor');
        wp_enqueue_style('wp-codemirror');
    }

I only get the one that is last declared, here CSS. How can I get both?
This is my js:
jQuery( function() {
    wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_html_code);
} );

And HTML:
<textarea class="joermo-html-code-editor" name="shipping_label_text">' . $shipping_label_text . '</textarea>

And also, is it not possible to .initzialie() several textareas with a shared class in one go? Do I have to call each one by id?

A: I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.
I've tweaked your code slightly so it should now work.
The PHP:
add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');
function joermo_enqueue_scripts($hook) {
    $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html'));
    $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css'));
    wp_localize_script('jquery', 'joermo_code', $joermo_code);

    wp_enqueue_script('wp-theme-plugin-editor');
    wp_enqueue_style('wp-codemirror');
}

The jQuery:
jQuery(function() {
    wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);
    wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);
});

Before I got the above working, I tried exactly the same as you did with running wp_localize_script twice. But $joermo_html_code['ce_html'] & $joermo_css_code['ce_css'] can be switched to an array and then you only need to run localize once. So in my example it became $joermo_code['ce_html'] & $joermo_code['ce_css'].
Hope this helps!

A: This approach might be easier to read. wp.codeEditor.initialize must be used for both, just passed the desired setting.
PHP
wp_register_script('cm_js', plugins_url('js/admin_codemirror.js', __FILE__), array('jquery'), '0.1.0', true);
$cm_settings = array(
    'ce_css' => wp_enqueue_code_editor(array('type' => 'text/css')),
    'ce_html' => wp_enqueue_code_editor(array('type' => 'text/html'))
);

wp_localize_script( 'cm_js', 'cm_settings', $cm_settings );
wp_enqueue_script( 'cm_js' );
wp_enqueue_script( 'wp-theme-plugin-editor' );
wp_enqueue_style( 'wp-codemirror' );

JS
wp.codeEditor.initialize($('#id_for_css'), cm_settings.ce_css);
wp.codeEditor.initialize($('#id_for_html'), cm_settings.ce_html);

A: None of the above worked for me. But i found a solution.
PHP:
    $cm_settings = wp_enqueue_code_editor( array( 'type' => 'text/css' ) );
    $cm_settings2 = wp_enqueue_code_editor( array( 'type' => 'application/javascript' ) );

    wp_localize_script('jquery', 'cm_settings', $cm_settings);
    wp_localize_script('jquery', 'cm_settings2', $cm_settings2);

    wp_enqueue_script('wp-theme-plugin-editor');
    wp_enqueue_style('wp-codemirror');

JS:
  wp.codeEditor.initialize($('#batheme_custom_css_textarea'), cm_settings);
  wp.codeEditor.initialize($('#batheme_custom_js_textarea'), cm_settings2);

Now both work like a charm. :)

A: Another way to do this without an additional JS file:
add_action( 'admin_enqueue_scripts', 'my_admin_page_editor' );

function my_admin_page_editor() {

    global $pagenow;

    if ( ( 'admin.php' === $pagenow ) && ( 'my-options-page' === $_GET['page'] ) ) {

        $custom_css = wp_enqueue_code_editor( array( 'type' => 'text/css' ) );
        $header_js  = wp_enqueue_code_editor( array( 'type' => 'application/javascript' ) );
        $footer_js  = wp_enqueue_code_editor( array( 'type' => 'application/javascript' ) );

        wp_add_inline_script(
            'code-editor',
            sprintf(
                'jQuery( function() {
                    wp.codeEditor.initialize( jQuery( ".my-custom-css textarea" ), %1$s );
                    wp.codeEditor.initialize( jQuery( ".my-header-scripts textarea" ), %2$s );
                    wp.codeEditor.initialize( jQuery( ".my-footer-scripts textarea" ), %3$s );
                });',
                wp_json_encode( $custom_css ),
                wp_json_encode( $header_js ),
                wp_json_encode( $footer_js )
            )
        );
    }
}


text:
Q: Why does my d3.js image appear in the wrong place? I have been designing a gantt chart. The javascript files are located within the html body:

Areas of Expertise

However, when I look at the source, the svg file is located outside of the section tags:

...

  <svg class="chart" width="777" height="827">...</svg>

I want my chart to take on the properties of the container it's in. It doesn't seem to be doing that. Here is a working example of my chart in action: http://jsbin.com/pigudeyovi/2/edit?html,output
Why is the .svg outside of the section tags?

A: The location of the code is not significant in deciding where its output appears -- D3 requires you to specify explicitly where to add any new elements to the DOM.
In this case, the output will always appear immediately below the body element. This is hard-coded in the Gantt chart library source code and not configurable by the user. To change that you either need to change the source code of the library or move the DOM element yourself.

A: The gnatt-chart plugin is appending the SVG to the body.
https://github.com/dk8996/Gantt-Chart/blob/master/gantt-chart-d3.js#L75


text:
Q: Battery remaining time I have a non-rechargeable 3.6V, 19Ah lithium polymer battery, and I want to calculate the remaining time for the battery from its measured voltage assuming that the average consumption current is constant.
I've read about the state of charge but don't have a curve for it in the datasheet.
The voltage battery will be measured by a voltage divider.
Any help how to estimate the approximate reaming time?