text:
Q: Real life example of relations with various combination of properties Attempted a set of questions as below:
Give examples of relations that are
1. asymmetric
2. reflexive, symmetric, but not transitive
3. antisymmetric, transitive, but not reflexive
4. reflexive, transitive, but not antisymmetric (equivalence)

I solved the first three questions but I couldn't solve the last one.
My answers for the first two:
1). x is a father of y
2). x lives within one mile of y
3). x is an ancestor of y

A:

*

*Asymmetric --  x is a father of y

This is a perfectly fine example of an asymmetric relation. After all, if John is Paul's father, Paul is assuredly not John's father in turn.

*reflexive, symmetric, but not transitive -- x lives within one mile of y

Perfectly valid as well:

*

*Any person lives within a mile of themselves (namely zero distance), so it is reflexive.

*If one person lives within a mile of another, that person consequently lives within a mile of the first, so it's symmetric.

*It is not ensured that if Paul lives within a mile of John, who lives within a mile of Martha, that Paul is within a mile of Martha. For instance, if Paul and Martha are two miles apart, and John is exactly between the two, we see a lack of transitivity.

*antisymmetric, transitive, but not reflexive -- x is an ancestor of y

This one works as well, but I wouldn't say it's a stellar example considering how antisymmetry works here.

*

*If X is Y's ancestor, in the typical usage, Y is never X's ancestor. Thus we have antisymmetry: since we never have both, we have no worries about the conclusion. (Recall: antisymmetry for a relation $R$ is that $xRy$ and $yRx$, if both true, always imply $x=y$. Here, we would never have one of the two premises, so $x=y$ doesn't matter. So it works but it doesn't necessarily scream a good example. But that's a matter of opinion.)

*Of course, if X is Y's ancestor, who is in turn Z's ancestor, Z is an ancestor of X, so we have transitivity.

*No one is their own ancestor, so this relation is not reflexive.

*reflexive, transitive, but not antisymmetric (equivalence)

First, I want to state despite some nudges in the comments in this way -- an equivalence relation is explicitly reflexive, transitive, and symmetric. "Not antisymmetric" is not the same as "symmetric." You can have relations which are both symmetric and antisymmetric, and relations which are neither.
For instance, on the set $\{1,\cdots,10\}$, let us define a few relations:

*

*$R_1 = \{(1,1)\}$

*$R_2 = \{(1,10),(10,1),(10,2)\}$

*$R_3 = \{(2,5),(5,2),(3,3)\}$

*$R_4 = \{(4,8)\}$
We analyze symmetry and antisymmetry as so:

*

*$R_1$ is symmetric and antisymmetric outright. $1R_11$ is true, and in turn $1R_11$ is true as well, so you have symmetry. But this same logic alongside the fact $1=1$ gives antisymmetry too. (In fact, any relation which consists solely of a set of pairs of the form $(x,x)$ is both antisymmetric and symmetric.)

*$R_2$ is neither symmetric nor antisymmetric. $1R_210$ and $10R_21$, but $10 \ne 1$, so we don't have antisymmetric. $2R_210$ is true, but we don't have the reverse, so no symmetry.

*$R_3$ is symmetric, but not antisymmetric. $2R_35$ and $5R_32$ but $2 \ne 5$, so no antisymmetry. However, whenever $(x,y) \in R_3$ we have that $(y,x) \in R_3$ too, so we have symmetry.

*$R_4$ is antisymmetric, but not symmetric. We never have both premises of $xR_4y$ and $yR_4x$, so we already see antisymmetry. However, $4R_48$ is true where $8R_44$ isn't, so no symmetry.
For these reasons, it is not right to interpret antisymmetry as the opposite of symmetry, but rather antisymmetry is as far as one could get from symmetry - whenever symmetry would hold it just means the two related objects are the same thing.
Some of these notions are easier to see and understand in the sense of representing relations as matrices. You can see this briefly discussed in my answer here where specifically symmetry and antisymmetry are concerned, since that seems to be the crux of this issue.
So, back to the comments and their suggestions -- would an equivalence relation work as an example? Sure, since symmetry doesn't negate antisymmetry. A trivial example of this is, say, a relation where everything is related to everything. Then:

*

*Reflexivity: Everything is related to itself

*Symmetry: If $xRy$ then $yRx$ (since each is related to everything)

*Transitivity: If $xRy$ and $yRz$ is true (always is), then $xRz$ is true (because $x,y,z$ are related to everything)

*Not Antisymmetric: Assume distinct $x,y$. Then $xRy$ and $yRx$ is always true since, again, everything is related, but $x \ne y$ on assumption.

The first three give equivalence, and the first two and the last are the properties you desire. But again, equivalence relations are a bit too strong here, insofar as having properties not strictly necessary, so perhaps an example of a relation where you have reflexivity and transitivity, but not symmetry or antisymmetry, would help.
Let us consider a relation on the set of people in the world, and define a relation $\sim$ by
$$x \sim y \iff \text{age}(x) \ge \text{age}(y)$$
In words, a person $X$ is related to a person $Y$ under $\sim$ if $X$ is at least as old as $Y$. (For simplicity, age is measured only in years, rounded down as necessary.) Let's verify:

*

*Reflexive: $\text{age}(x) = \text{age}(x)$, and thus $\text{age}(x) \ge \text{age}(x)$, so $x \sim x$ obviously.

*Transitive: Let $\text{age}(x) \ge \text{age}(y)$ and $\text{age}(y) \ge \text{age}(z)$. That is, let $x \sim y$ and $y \sim z$. Since $\ge$ itself is a transitive relation, we'll have $\text{age}(x) \ge \text{age}(z)$, giving $x \sim z$ and transitivity.

*Not Symmetric: If we have a strict inequality somewhere, there is no symmetry. For instance, if $X$ is $10$ years old and $Y$ is $15$ years old, then $Y \sim X$ but $X \not \sim Y$ (because $15 \ge 10$ but $10 < 15$).

*Not Antisymmetric: Suppose $x\sim y$ and $y \sim x$. The corresponding ages must be equal for this to hold, but this doesn't mean the people are the same person. For instance, both Paul and John can be ten years old, but they're obviously not the same person.


text:
Q: Is there an option in OGR2OGR to repair geometry when importing data to PostGIS? this is related to one of my questions here Invalid Geometry in PostGIS but Valid in FGDB
If I could, I want to repair geometry while I am importing my data to PostGIS.
So I wrote this code below on OSgeo4W Shell
ogr2ogr -overwrite -progress -f "PostgreSQL" PG:"host=localhost port=5432 dbname=test user=test password=test" D:\FGDB_Edit\OCEAN.gdb -lco GEOMETRY_NAME=shape -t_srs EPSG:3857 -nln ocean_repair -dialect sqlite -sql "select ST_MakeValid(Shape) as geometry, * from ocean_boundary"

and it gives me this error

have you experienced this before? and have any solutions?

A: so basically your whole code will be like this

ogr2ogr -overwrite -progress -f "PostgreSQL" PG:"host=localhost
  port=5432 dbname=yourdb user=yourid password=pw" inputGDBpath -lco
  GEOMETRY_NAME=shape -t_srs EPSG:3857 -nln whatever_the_layer_name
  -dialect sqlite -sql "select ST_MakeValid(shape) as geometry, OBJECTID_1, objectid, sc1class_c, sc2class_c, sc3class_c, sc4class_c,
  Shape_Leng, polygon_id, feature_type, display_id, language_code, name,
  display_class, coverage_indicator, iso_country_code, ver_cnt, region,
  nccode, bk_nccode, id, scalerank, featurecla, Shape_Length, Shape_Area
  from ocean_boundary"

OBJECTID_1, objectid, sc1class_c, sc2class_c, sc3class_c, sc4class_c, Shape_Leng, polygon_id, feature_type, display_id, language_code, name, display_class, coverage_indicator, iso_country_code, ver_cnt, region, nccode, bk_nccode, id, scalerank, featurecla, Shape_Length, Shape_Area
these are the field in my feature class except "shape" field

redpajama_set_name: RedPajamaStackExchange


text:
Q: OCR error correction algorithms I'm working on digitizing a large collection of scanned documents, working with Tesseract 3 as my OCR engine.  The quality of its output is mediocre, as it often produces both garbage characters before and after the actual text, and misspellings within the text.
For the former problem, it seems like there must be strategies for determining which text is actually text and which text isn't (much of this text is things like people's names, so I'm looking for solutions other than looking up words in a dictionary).
For the typo problem, most of the errors stem from a few misclassifications of letters (substituting l, 1, and I for one another, for instance), and it seems like there should be methods for guessing which words are misspelled (since not too many words in English have a "1" in the middle of them), and guessing what the appropriate correction is.
What are the best practices in this space?  Are there free/open-source implementations of algorithms that do this sort of thing?  Google has yielded lots of papers, but not much concrete.  If there aren't implementations available, which of the many papers would be a good starting place?

A: For "determining which text is actually text and which text isn't" you might want to look at rmgarbage from same department that developed Tesseract (the ISRI).  I've written a Perl implementation and there's also a Ruby implementation.  For the 1 vs. l problem I'm experimenting with ocrspell (again from the same department), for which their original source is available.
I can only post two links, so the missing ones are:

*

*ocrspell: enter "10.1007/PL00013558" at dx.doi.org]

*rmgarbage: search for "Automatic Removal of Garbage Strings in OCR Text: An Implementation"

*ruby implementation: search for "docsplit textcleaner"

A: Something that could be useful for you is to try this free online OCR and compare its results with yours to see if by playing with the image (e.g. scaling up/down) you could improve the results.
I was using it as an "upper bound" of the results I should get when using tesseract myself (after using OpenCV to modify the images).


text:
Q: Jquery- How to remove comma after a specific record in an array I am using the datatables mRender function to generate a list of items in a column separated by commas. I wanted to remove a specific record from the list and the record lies at the end of list of records in an array. Something like this:
LESS,SAAS,REST,API

I want to remove the last record (API, which i did), however, when i remove it the comma still sticks to it at the end, resulting into something like:
LESS,SAAS,REST,
LESS,SAAS,

assuming that all time the record after the comma is the ALL. How can i remove the record and also the comma that sticks after it??
EDIT: This is how i have the code and im removing the API, by passing empty string. Please suggest of this could be done better.
mRender: function (obj) {
    _.each(obj, function(item, index){
        var prodVal = "";

        else if (item === 'API'){
            prodVal = '';
        }

        returnVal.push("" + prodVal + "");
    });

    return returnVal.join(', ');
}

Any ideas???
Thanks!

A: There are many ways to do this, but I think that splitting the string into an array, filtering out the array, and then joining back into a string will be the most robust & flexible.
Something like this:
var items = 'LESS,SAAS,REST,API'.split( ',' );
items = items.filter(function( item ) { /* return false for anything you want to remove */ });
console.log( items.join( ',' ) );

A few relevant links:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

A: use this
 var str = "LESS,SAAS,REST,API";
 var res = str.split(",");
 res.pop();
 console.log(res.join(","));

A: var list = 'LESS,SAAS,REST,';
list = list.substring(0, list.length);

A: *

*explode into array i.e. var arr = 'LESS,SAAS,REST,API'.split(',')

*remove element i.e. av.splice(av.length-1,1); //<- removes last element

*Join again to generate string av.join(',')

A: Removing the last element
Depending on whether you're working with an array, object, or string, there are a few different ways to handle it.  With your example, it looks like your setting the value to empty, rather than removing the entry, which is why you're getting an extra comma after using returnVal.join(', ').
Remove last element from array
var mRecord = ["LESS","SAAS","REST","API"];
mRecord.pop();

console.log(mRecord); // Array( [0] => "LESS", [1] => "SAAS", [2] => "REST" )
console.log(mRecord.join()); // String "LESS,SAAS,REST"

Remove last element from string
// with simple built-in functions - will perform better in your example
mRecord = mRecord.substring(0, str.lastIndexOf(",") - 1);

// with regex - may perform better with larger strings
mRecord  = mRecord.replace(/,[^,]+$/, "");

Remove the last member of an object
While I am uncertain as to the structure of the object you are working with, you should likely be using some variation of delete mRecord[member].
Currently, prodVal = '' leaves the entry in the array, causing returnVal.join(', ') to include an extra ', ' between the last value, and the empty one.
Your code includes an else if but not the initial if declaration. I suspect that if you move the push and returns within the main conditional, it may work as you intend
mRender: function (obj) {
    _.each(obj, function(item, index){
        var prodVal = "";

        if (item === 'API'){
            prodVal = '';
            // edit: your best bet is to generate a new array or object to act on
            //       rather than trying to unset the item here.
        } else {
            returnVal.push("" + prodVal + "");
        }

    });
    return returnVal.join(', ');
}

A: this will remove the 7 from this example array showing how the splice works
var anArray = [ "1", "2", "3", "4", "5", "6", "7" ];
anArray.splice(-1);

will give 123456 (without the 7 the last element in the array)
here is a jsfiddle showing it in action

A: This is a very simple function exactly for what you need. Try it out and let me know what you think:
   $(document).ready(function() {

        var string = "LESS,SAAS,REST,API";
        var array = string.split(",");

        function delete_last(elem) {
            var index = array.indexOf(elem);
            array.splice(index, 1);
            return array.join(",");
        }

        var results = delete_last("API");

        console.log(results);

    });


text:
Q: Where are database of contents inside the widget - wordpress stored? I transferred the contents of the site and the database but the contents of the widget were not moved.
I have a full backup from the previous site.
I want the exact location inside the backup ( wordpress ) or name it in datebase??


text:
Q: Constantly failing to create the Java virtual machine on Windows 7 I just installed : "FishStatJ, a Java-based desktop application,"
Download is fine, installing is fine but when I try to use the program I get this message:

Failed to create the Java Virtual Machine.

I have done everything that I can think of

*

*Updated java

*got the developers kit part from their home page to see if it would help

*cleaned up the computer and etc

And my computer is almost new, it's a IBM think station with up to date Windows 7, so the hardware should not be a problem.
Any help would be greatly appreciated!
sorry for the bad spelling, English is my 2nd language.

A: Provided page seems to says it only supports 32-bit. If you are using a 64-bit system, it will not work.


text:
Q: Is the a way to plot that the distance between 2 moving averages has reached a specific percentage or tick value? Pinescript I am attempting to calculate that the distance between the Ema50 and Ema100, and Ema100 and Ema150 are 12 points apart from each other respectively. Just trying to trigger a simple alert that a trend is starting. For both upward and downward trends.
Here is my attempt...
Trendcatcher = ema50 - ema100 >= 12 * syminfo.mintick and ema100 - ema150 >= 12 * syminfo.mintick or ema150 - ema100 >= 12 * syminfo.mintick and ema100 - ema50 >= 12 * syminfo.mintick
It works... but it only works when candles are crossing though the moving averages?
However the candles are not the reason for the alert... It's the distance between the Ema's that I need to trigger the alert.
How can I achieve this alert based on the distance of the moving averages on their own and not because a candle is moving though the averages?
Is this even possible in Pinescript?
Any help would be greatly apricated!
Big thanks in advance!
Paul

A: This is definitely possible!
Here is a version based on percentage:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lysergik

//@version=5
indicator("stack trendcatcher question", format=format.percent)

// set percentage difference between
threshold_percentage = input.float(0.1, "threshold_percentage", minval=0.1)

// calculate emas
ema50 = ta.ema(close, 50)
ema100 = ta.ema(close, 100)
ema150 = ta.ema(close, 150)

// calculate percentage difference between ma's at each candle close
diff1 = (ema50-ema100)/close*100
diff2 = (ema100-ema150)/close*100

// logic

bool up = diff1 >= threshold_percentage and diff2 >= threshold_percentage
bool down = diff1 <= threshold_percentage*-1 and diff2 <= threshold_percentage*-1

bool newUp = up[1] == false and up == true
bool newDown = down[1] == false and down == true

// front-end

hline(0)
plot(diff1, color=color.aqua)
plot(diff2, color=color.white)

plotshape(up ? 0 : na, style=shape.circle, size=size.tiny, color=color.lime, location=location.absolute)
plotshape(down ? 0 : na, style=shape.circle, size=size.tiny, color=color.red, location=location.absolute)

plotshape(newUp ? 0 : na, style=shape.diamond, size=size.small, color=color.lime, location=location.absolute)
plotshape(newDown ? 0 : na, style=shape.diamond, size=size.small, color=color.red, location=location.absolute)

I've plotted everything from the script into the indicator's front-end to exemplify its inner workings and help make it clear what it's doing.
The white and aqua lines are the percentage differences between ema100, ema 150 and ema 50, ema 100 respectively.
The tiny circles are plotted at every candle close are where the differences are both above or below the set threshold.
The small diamonds are plotted at the beginning of a new period of time where both differences are above or below the threshold. These boolean values can be used as the triggers for your alert!
I think you already know what to do to modify this script for use with number of ticks instead of percentage, but comment on this answer if you need any help doing so and I will be glad to help!


text:
Q: Format xargs output to grep I have a script that I'm trying to optimize with xargs. The current version uses find with -exec to call the command:
find -type f -iname "*.mp4" -print0 -printf '\n' -exec getfattr -d --absolute-names {} \;
after which I can pipe to grep with something like:
grep -z -P user\.md5\=\"$input_search_hash\"
to filter the results while keeping the whole output with -z.
I need the whole output returned from getfattr to be "preserved", per file, because I need the filename for which there is a matching extended attribute, which then is then passed to sed to extract it. There are also cases where I have multiple grep commands in sequence if I need to search for files with multiple matches in the extended attributes. The problem is that the output of:
find -type f -iname "*.mp4" -print0 | xargs -0 getfattr -d --absolute-names
is not formatted in such a way that grep will filter in this way. This does work with the -exec method. Can I pass an addional option to xargs or pipe in some additional command that will format the output to make grep properly replicate the behaviour of -exec? I'm guessing I need some sort of line-break before feeding to grep like what -printf '\n' does in the -exec method. I would just use getfattr to "search" the extended attributes instead of needing to grep the output at all, but it has no way to do this by suppling a xattr name and value.
Example
The input comes from the find command, which is a list of video files in an arbitrary directory structure. The output of each getfattr command, for each file is such:
# file: /path/to/file/test.mp4
user.md5="0e29a7f555af518872771689e28d998d"
user.quality="10"
user.sha256="d49ba58e3b30f4ef8c81d19ce960edcf6552977bb8adb79b5b9a677ba9a54b2b"
user.size="1645645"

If I attempt to grep the output of find using the + method, say for a value of "10" on the quality, I will get results like this:
# file: /path/to/file/test.mp4
user.md5="8cf97b888e6fdbed27b02233cd6779f5"
user.quality="12"
user.sha256="613d16b2a0270e2e5f81cfd58b1eacf710a65b82ce2dab49a1e415275440f429"
user.size="1645645"

# file: /path/to/file/test1.mp4
user.md5="3c5a39f1ceefce1e124bcd6786a99155"
user.quality="10"
user.sha256="0d7128a7642d24ea879bbfb3de812b7939b618d8af639f07d5104c954c8049c3"
user.size="5674567"

# file: /path/to/file/test2.mp4
user.md5="0e29a7f555af518872771689e28d998d"
user.quality="6"
user.sha256="d49ba58e3b30f4ef8c81d19ce960edcf6552977bb8adb79b5b9a677ba9a54b2b"
user.size="15645"

All files that find locates are returned and the string to be searched from grep, in this example user.quality="10", is highlighted, but the other files test.mp4 and test2.mp4 still have the output printed post-grep. In other words, find may locate 1000 mp4 files of which maybe 20 have a user.quality="10" entry, but even applying grep to search for that string still returns 1000 filenames (after sed).
This does not happen when using \;. The only thing I would get out from grep would be:
# file: /path/to/file/test.mp4
user.md5="3c5a39f1ceefce1e124bcd6786a99155"
user.quality="10"
user.sha256="0d7128a7642d24ea879bbfb3de812b7939b618d8af639f07d5104c954c8049c3"
user.size="5674567"

This is the expected behaviour.

A: xargs vs find -exec
To me it seems like you want to use xargs instead of find -exec {} \; to speed things up.
Yes, xargs is faster than find -exec {} \;, not because it does the same work more efficiently, but because it does different work!

*

*find -exec {} \; calls once for each file (getfattr file1, then getfattr file2, and so on).

*xargs crams as many files into one call as possible (getfattr file1 file2 file3 ...).
The same behavior (and even more speedup) can be achieved with find -exec {} + -- no need to use xargs for that.

With xargs and find -exec {} + you loose control over the output format. There is only one call of getfattr so that program decides what to print between file1, file2 and so on. getfattr has no option to customize its output format.
No problem! You can ...
Parse getfattr's output
... pretty easily.
For starters, we assume that all path names are pretty normal. Spaces, *, and ? are ok though. For really unusual path names containing backslashes and linebreaks see the last section.
If you output only the relevant attribute using -n user.md5 instead of -d, then you know that the output (if any) for each file is always of the form
# file: path in a single line
user.md5=encoded value of the attribute

Files without the attribute user.md5 are not printed at all. They cause a warning on stderr which can be suppressed by 2> /dev/null.
Now, grep for matching attributes. Use grep -B1 to print the line above each match (i.e. the path) too. Then use sed -n or grep -o to extract the filenames.
find -type f -iname '*.mp4' -exec getfattr -n user.md5 --absolute-names {} + 2> /dev/null |
grep -B1 -Fx "user.md5=\"$input_search_hash\"" |
sed -n 's/^# file: //p'

Above command prints the paths of all mp4 files having the attribute user.md5 with value $input_search_hash.
Handling Unusual Filenames
At least my version (getfattr 2.4.48 by Andreas Gruenbacher) on Debian 10 always prints the file name in a single line. Linebreaks are encoded using \012 and backslashes are encoded using \134. Therefore, safe processing of those files is possible.
Above command works, but prints only the encoded file names. To get the actual filenames you have to extend the sed command or add another command to interpret octal escape sequences. For me, getfattr only escapes \n, \r and \\, thus sed 's:\\012:\n:g;s:\\015:\r:g;s:\\134:\\:g' should be sufficient for printing. For further processing, you may want to use tr \\n \\0 | sed -z ... instead, such that filenames are separated by null bytes.
To test which characters are escaped for you, create a filename containing all allowed bytes and let getfattr print its name:
f=$(printf $(printf '\\%o' $(seq 1 255)) | tr -d /)
touch "$f"
setfattr -n user.md5 -v 123 "$f"
getfattr -n user.md5  "$f"
rm "$f"


text:
Q: Why ErrorCollector doesn't work with PowerMockRunner? I've tried to use ErrorCollector in project. At start it works. All errors are collected, but at the end when the list of errors should be printed, something throws MultipleFailureException at PowerMockRunner.
org.junit.internal.runners.model.MultipleFailureException
    at org.junit.internal.runners.model.MultipleFailureException.assertEmpty(MultipleFailureException.java:23)
    at org.junit.rules.ErrorCollector.verify(ErrorCollector.java:40)
    at org.junit.rules.Verifier$1.evaluate(Verifier.java:35)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:83)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Maybe that feature (multiple error listing) simply wasn't implemented into the PowerMock yet? (It works well with MockitoJUnitRunner or without mocking) And it works with one error stored in ErrorCollector with PowerMockRunner also, but it doesn't make sense using ErrorCollector only with one error. Or is there any other problem with using of PowerMockRunner with ErrorCollector?
JUnit version: 4.8.2
PowerMockRunner version: 1.4.2


text:
Q: Unable to find "Upgrade to Requests 2.0" in facebook application settings As mentioned in this blog post http://developers.facebook.com/blog/post/464/
....enable "Upgrade to Requests 2.0" in your Developer App settings on the "Advanced" tab. This switch controls the bookmark counts seen by your users and synchronizes the count with sent requests.
I have thoroughly checked the "Advanced" tab in my application settings, but I couldn't find any such "upgrade to requests 2.0" option.

A: You clearly created application after September 2011. Since then this option is no longer available to newly created applications.
According to Completed changes list:

January 1, 2012
  All apps will be opted into "Upgrade to Requests 2.0" and "Requests 2.0 Efficient" Migrations
  Existing apps will be opted into "Requests 2.0 Efficient" and "Upgrade to Requests 2.0" migrations and all developers must ensure that they are using the correct request_id format and deleting requests appropriately. Details here.

Also Improvements to Requests 2.0 blog post (from September 30, 2011) states:

Starting today new apps will automatically be opted into "Upgrade to Requests 2.0" and "Requests 2.0 Efficient" and these migrations will no longer be available in the app settings for new apps. This requires developers to use the new request_id format as detailed above. In addition when a user is directed to your app, by clicking a Request from the app, the games dashboard, or from a Request notification, you must delete the request after it has been accepted. These are not automatically deleted once they have been clicked, thus it is the developer's responsibility to clear them once they have been consumed. See sample above for how you can delete these requests.

A: Maybe you are using a new application?
This option is only available to users that have create the application with the old options.
All new applications support Requests 2 so you don't need to activate a support method to work with.


text:
Q: when checkbox is checked, change background color of div What I'm trying to do is when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?

    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
       Mark as reviewed and acknowledged

using parent selector and .removeclass I do not know how to select my div and turn the color off and on using jquery.

A: You don't need jQuery for this
You can do this  only with css.
    .checkbox-container:has(input:checked) {
    background-color: red;
}

:has pseudo class is supported in chromium, safari.
For firefox, need to enable flag.
know more at mdn ::has pseudo class

A: Add a change event listener to the input that sets its closest parent div's background color based on whether it is checked:

$('input[type="checkbox"]').change(function(){
  $(this).closest('div').css('background-color', this.checked ? 'green' : 'white')
})

    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
       Mark as reviewed and acknowledged

A: Try this I hope this will help you

<!DOCTYPE html>

    <input type="checkbox" class ="checkbox-border" id="personal-info-checkbox">
       Mark as reviewed and acknowledged

A: Here's an example of how you can do this

$(function() {
  $("input[type=checkbox]").click( () => {
    $("div").toggleClass("background");
  })
});
.background {
  background: blue;
}

Change colors<input type="checkbox" />

A: There are a number of ways to do this:

*

*CSS (with limited, as of writing, browser support),

*jQuery (among other libraries), and

*native JavaScript.

The below example has explanatory comments in the code:

// using jQuery, we select the relevant element via its class, and use the on()
// method to bind the anonymous function as the event-handler for the 'change'
// event:
$('.checkbox-container.with-jQuery').on('change', function(){
  // here we find the <input> element descendant with find(), and then use the
  // is() method to test that element to see if it matches the :checked pseudo-
  // class; this returns a Boolean true/false which is cached in the 'checked'
  // variable:
    let checked = $(this).find('input').is(':checked');

  // here we use toggleClass() to toggle the 'checked' class-name on the element,
  // and use the 'checked' variable to ascertain whether the class should be
  // added/retained (if the Boolean is true) or removed/not-added (if the Boolean
  // is false):
    $(this).toggleClass('checked', checked);
});

// using JavaScript we use document.querySelector to retrieve the element
// with the listed classes; and use EventTarget.addEventListener() to bind the
// anonymous Arrow function as the event-handler for the 'change' event:
document.querySelector('.with-JavaScript.checkbox-container').addEventListener('change',(evt)=>{
  // we cache a reference to the current element (the
):
    let current = evt.currentTarget,
      // we find the <input> descendant, and access its checked property to
      // obtain a Boolean true (if checked) or false (if not-checked) and
      // store that Boolean in the 'checked' variable:
        checked = current.querySelector('input').checked;
  // here we use Element.classList.add() to add the 'active' class-name,
  // with the checked variable to determine if it should be added/retained
  // (if true) or removed/not-added (if false):
    current.classList.add('active', checked);
});
:root {
  --checkedColor: lime;
}

/* here we select the element via classes, and use :has()
   to check if it has a descendant element which matches
   the enclosed selector: */
.with-CSS.checkbox-container:has(input:checked) {
  /* if so, we set the --checkedColor custom property
     as the background-color of the element: */
  background-color: var(--checkedColor);
}

.with-jQuery.checkbox-container.checked {
  background-color: var(--checkedColor);
}

.with-JavaScript.checkbox-container.active {
  background-color: var(--checkedColor);
}

  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox1">
   Mark as reviewed and acknowledged

  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox2">
   Mark as reviewed and acknowledged

  <input type="checkbox" class="checkbox-border" id="personal-info-checkbox3">
   Mark as reviewed and acknowledged

References:

*

*Browser compatibility:

*

*:has().

*CSS:

*

*CSS Custom properties.

*:checked.

*:has().

*var().

*JavaScript:

*

*document.querySelector().

*Element.classList API.

*jQuery@

*

*is().

*on().

*toggleClass().


text:
Q: How to correct run WCF services from javascript? This is my page code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProductType.aspx.cs" Inherits="Application.ProductType" MasterPageFile="~/Main.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <script type="text/javascript">
        function getMainTable() { return document.getElementById("<%= ProductGridMain.ClientID %>"); }
    </script>
    <script type="text/javascript" src="JavaScripts/ProductType.js"></script>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/Services/ProductTypeService.svc" />
            </Services>
    </asp:ScriptManager>
    <asp:Label ID="ProductGridMain" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Button ID="AddNewItemBtn" CssClass="Btn" runat="server" Text="New" OnClientClick="NewAddBtn(); return false;" />
</asp:Content>

This is the ProductType.js file:
$(document).ready(function() {
    var counter = "fast";
    ProductTypeService.GetMainGridProductTypeHtml(counter, ResultLoadTableMainGridHtml, ErrorLoadTableMainGridHtml);
});
function ResultLoadTableMainGridHtml(html) {
    //debugger;
        var tblMainGrid = getMainTable();
        if (tblMainGrid != null && html != null && html != "null" && html != "" && html != " ") {
            tblMainGrid.innerHTML = html;
        }
}
function ErrorLoadTableMainGridHtml(html) {
    alert("Error");
}
function NewAddBtn() {
    //debugger;
    var counter = "test";
    ProductTypeService.GetMainGridProductTypeHtml(counter, ResultLoadTableMainGridHtml, ErrorLoadTableMainGridHtml);
}

The service method returns html code of main grid, then in javascript I insert it into label.
When I click on button everything works correctly like I suppose, but page is reloading. How do I call the service method on button click without page reloading?

A: Why not use HTML button instead of ASP.NET button - that way you can indicate that you don't need submit behavior. For example,
<input type="button" id="AddNewItemBtn" class="Btn" runat="server" value="New" onclick="NewAddBtn()" />

You may eliminate runat="server" if you don't need to refer to the button in the server code.


text:
Q: run length encoding compressing So the point of this code is to compress a string and if it occurs more than 3 times, add a "# + number of occurence". For a letter the format is (#num)(letter) for a number value, they both have "#".
for example, if i have yyyy77777 the output would be #4y#5#7
but my problem is it doesn't print the number values with "#" in front of it, so my output it $4y#57
another problem i have is that when it's less than 3, it just prints the same. so i.e.: nnnnnff should have an output of #5nff
but my code turns it into #5n2f
any help would be appreciated!
public class Compress {

public static void main(String[] args) {
    java.util.Scanner in = new java.util.Scanner(System.in);
    String s = in.next();
    String compressString = compress(s);
    System.out.println(compressString);

}
public static String compress (String original){
    String str = "";
   // int n = (Integer) null;
    int count = 1;
    for(int i=0; i<original.length()-1; i++){

        if(original.charAt(i) == original.charAt(i+1)){
            count++;
            if(i == original.length()-2){
                if(count == 1){
                    str = str + original.charAt(i);
                }
                //if count is equal or greater than 3, print with #
                else if (count >= 3) {
                    str = str + "#" + count +  original.charAt(i);
                }
                else{
                    str = str + original.charAt(i);
                }
            }
        }
        else{
            if(count == 1){
                if(i == original.length() - 2){
                    str = str + original.charAt(i);
                    str = str + original.charAt(i+1);
                }
                else{
                str = str + original.charAt(i);
                }
            }
            else{
                if(i == original.length() - 2){
                    str = str + count + original.charAt(i);
                    str = str + original.charAt(i+1);
                }
                else{
                    str = str +"#"+ count + original.charAt(i);
                }

            }

            count = 1;
        }
    }
    return str;
}

}

A: Your code is currently treating digits and non-digits the exact same way. To fix your code, you just need to add if statements to check if the characters are digits.
You can add the if statements just before you append a #(count)(character) to the result.
Replace this line (there are two lines like this! Replace both of them):
str = str + "#" + count +  original.charAt(i);

with
if (Character.isDigit(original.charAt(i))) {
    str = str + "#" + count + "#" + original.charAt(i);
} else {
    str = str + "#" + count +  original.charAt(i);
}

Here is how I would solve this problem:
public static String compress (String original){
    String str = "";
    int count = 0;
    char currentChar = original.charAt(0);
    for(int i=0; i<original.length(); i++){
        if (currentChar == original.charAt(i)) { // count it if this not a new character
            currentChar = original.charAt(i);
            count++;
        } else { // if we have encountered a new character
            if (count > 2) { // and we have already counted 2 or more of the previous char
                if (Character.isDigit(currentChar)) {
                    str += "#" + count + "#" + currentChar;
                } else {
                    str += "#" + count + currentChar;
                }
            } else if (count == 2) { // if we have only counted two of the previous char
                str += currentChar;
                str += currentChar;
            } else if (count == 1) { // if we have only counted one of the previous char
                str += currentChar;
            }
            currentChar = original.charAt(i);
            count = 1;
        }
    }
    // treat the end of the string as a new char
    if (count > 2) {
        if (Character.isDigit(currentChar)) {
            str += "#" + count + "#" + currentChar;
        } else {
            str += "#" + count + currentChar;
        }
    } else if (count == 2) {
        str += currentChar;
        str += currentChar;
    } else if (count == 1) {
        str += currentChar;
    }
    return str;
}


text:
Q: Editable hierarchical grid in Kendo UI I wish to create a grid that each row has grid inside it.
Both grids need to be editable and I managed to do so. However, when I try to add a new row to the outer grid, all the data inside it gone.
You can find the demo here: http://dojo.telerik.com/UqURE
Can you please help with this issue?
Thanks!
var outerDataSource= new kendo.data.DataSource({
        schema: {
            model: {
                field1: { type: "string", validation: { required: true } },
                field2: { type: "boolean", validation: { required: true } },
                field3: { type: "string", validation: { required: true } }
            }
        }
    });

$("#outerGrid").kendoGrid({
    dataSource: outerDataSource,
    detailInit: onExpansion,
    toolbar: ["create"],
    columns: [
        { field: "field1", title: "field1" },
        { field: "field2", title: "field2" },
        { field: "field3", title: "field3" },
        { command: ["destroy"], title: " " }],
    editable: true
});
function onExpansion(e) {
    var insideDataSource= new kendo.data.DataSource({
        schema: {
            model: {
                in1: { type: "string", validation: { required: true } },
                in2: { type: "string", validation: { required: true } }
            }
        },
        data: [{
            in1: "Click to edit",
            in2: "Click to edit"
        }]
    });

    var headers = $("<div/>").appendTo(e.detailCell).kendoGrid({
        dataSource: insideDataSource,
        width: 90,
        toolbar: ["create"],
        editable: true,
        columns: [
          { field: "in1" },
          { field: "in2" },
          { command: ["destroy"], title: " " }]
    });
};

A: Answer from Telerik:

Please note that operations like paging, sorting, filtering and
  editing cause the Grid to rebind and reevaluate all templates inside
  it (including the details). That why in order to preserve the child
  Grid data between rebinds you should either save it to remove service
  (link to documentation here) or add it as navigation property
  collection to the parent Grid model (demo is available here).

http://www.telerik.com/forums/hirarchialy-editable-grids


text:
Q: Black Screen on PrintWindow Can anyone advice on PrintWindow , i'm getting Black Images from the Bitmap.
Background Turns Black When Saving Bitmap - C#
I saw this but what do i replace DrawArea with?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;

namespace RemoteAI
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            IntPtr hWnd = FindWindow(null, "Task Manager");
            Bitmap bmp = PrintWindow(hWnd);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }

        [DllImport("user32.dll")]
        public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
        [DllImport("user32.dll")]
        public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        public static Bitmap PrintWindow(IntPtr hwnd)
        {
            RECT rc;
            GetWindowRect(hwnd, out rc);

            Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
            Graphics gfxBmp = Graphics.FromImage(bmp);
            gfxBmp.Clear(Color.White);

            IntPtr hdcBitmap = gfxBmp.GetHdc();

            PrintWindow(hwnd, hdcBitmap, 0);

            gfxBmp.ReleaseHdc(hdcBitmap);
            gfxBmp.Dispose();

            string outputFileName = "C:\\Users\\XY\\Desktop\\image\\test.bmp";
            using (MemoryStream memory = new MemoryStream())
            {
                using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
                {
                    bmp.Save(memory, ImageFormat.Png);
                    byte[] bytes = memory.ToArray();
                    fs.Write(bytes, 0, bytes.Length);
                }
            }
            return bmp;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            private int _Left;
            private int _Top;
            private int _Right;
            private int _Bottom;

            public RECT(RECT Rectangle) : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
            {
            }
            public RECT(int Left, int Top, int Right, int Bottom)
            {
                _Left = Left;
                _Top = Top;
                _Right = Right;
                _Bottom = Bottom;
            }

            public int X
            {
                get { return _Left; }
                set { _Left = value; }
            }
            public int Y
            {
                get { return _Top; }
                set { _Top = value; }
            }
            public int Left
            {
                get { return _Left; }
                set { _Left = value; }
            }
            public int Top
            {
                get { return _Top; }
                set { _Top = value; }
            }
            public int Right
            {
                get { return _Right; }
                set { _Right = value; }
            }
            public int Bottom
            {
                get { return _Bottom; }
                set { _Bottom = value; }
            }
            public int Height
            {
                get { return _Bottom - _Top; }
                set { _Bottom = value + _Top; }
            }
            public int Width
            {
                get { return _Right - _Left; }
                set { _Right = value + _Left; }
            }
            public Point Location
            {
                get { return new Point(Left, Top); }
                set
                {
                    _Left = value.X;
                    _Top = value.Y;
                }
            }
            public Size Size
            {
                get { return new Size(Width, Height); }
                set
                {
                    _Right = value.Width + _Left;
                    _Bottom = value.Height + _Top;
                }
            }

            public static implicit operator Rectangle(RECT Rectangle)
            {
                return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height);
            }
            public static implicit operator RECT(Rectangle Rectangle)
            {
                return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);
            }
            public static bool operator ==(RECT Rectangle1, RECT Rectangle2)
            {
                return Rectangle1.Equals(Rectangle2);
            }
            public static bool operator !=(RECT Rectangle1, RECT Rectangle2)
            {
                return !Rectangle1.Equals(Rectangle2);
            }

            public override string ToString()
            {
                return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}";
            }

            public override int GetHashCode()
            {
                return ToString().GetHashCode();
            }

            public bool Equals(RECT Rectangle)
            {
                return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;
            }

            public override bool Equals(object Object)
            {
                if (Object is RECT)
                {
                    return Equals((RECT)Object);
                }
                else if (Object is Rectangle)
                {
                    return Equals(new RECT((Rectangle)Object));
                }

                return false;
            }
        }

    }

}


text:
Q: Child component is memoized with useMemo in the parent, how to make child component signal the parent to re-compute the value? I'm in a situation just like this where I need to toggle between two components, both components can get significantly heavy so I memoized them.
Following the first comment from the link above, I'm using the useMemo() hook in the parent of both components so I can show/hide a particular component:
function myComponent() {
  const [activeTab, setActiveTab] = useState('Books');

  const MemoizedBooks = useMemo(() => <Books />, []);
  const MemoizedRequests = useMemo(() => <Requests />, []);

  return (
      <div>{activeTab === 'Books' ? MemoizedBooks : MemoizedRequests}</div>
  )
}

The problem/question
If the <Books/> component updates itself for instance, how will the parent myComponent know of this update and then update memoizedBooks?


text:
Q: Please put the date near the top of the post It is extremely time consuming to have to continually scroll down through the webpage to find the date of the post, before I begin reading the post. In gauging how relevant a post is to my particular problem, I always start with the date.

A: Most posts are short and don't extend off the screen.  Most searches and lists of questions already have dates that you can refer to before even opening the question.

A: You have the "asked xx:xx" displayed in the listing of question. That is sufficient I think.
In interesting mode you also have the last activity registered.

A: Everything is editable here -- so the date is not as important.
We actively suppress "too localized" activity and discussion precisely for this reason, to generate artifacts of (reasonably) lasting value.
While in all fairness, we are a hybrid system, this would be akin to asking Wikipedia to put the date at the top of all their pages.

A: Disagree.  I like it the way it is.

A: They could insert it right above the tagged text on the right.


text:
Q: How to calculate month with fraction in Access VBA I need to write a function that receives two arguments startdate and enddate where it returns the difference between these two dates.
Say that function is monthfractiondiff(startdate,enddate)
e.g. monthfractiondiff(15/01/2016,15/02/2016) will return
((31-15)/31)+(15/29) = 1.0333704116
monthfractiondiff(15/11/2018,15/02/2019) will return
((30-15)/30)+1+1+(15/28) = 3.0357142857
I vainly tried https://access-programmers.co.uk/forums/showthread.php?t=113589

A: UPDATED thanks to other answer WeeBee
Function HowManyMonths(startdate As Date, Enddate As Date) As Double
Dim pctSTARTmonth As Double, pctENDmonth As Double, M As Long

'caputues percentage of month
pctSTARTmonth = Day(startdate) / Day(DateSerial(Year(startdate), Month(startdate) + 1, 1) - 1)
pctENDmonth = Day(Enddate) / Day(DateSerial(Year(Enddate), Month(Enddate) + 1, 1) - 1)

'Use Date difference function to get whole number and then combine perc
HowManyMonths = DateDiff("M", startdate, Enddate) + pctENDmonth - pctSTARTmonth

End Function

A: I would go with datediff().
datediff("d", "01/01/2019", date())/30.5

Today this returns me 4,85245901639344.

A: As the day count of months varies, you have to count by days to get as close as possible, as there never (except within a month or within July/August or December/January) will be an exact value:
' Rounds by default to two decimals, as more decimals has no meaning
' due to the varying count of days of a month.
' Optionally, don't round, by setting Round2 to False.
'
Public Function TotalMonths( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date, _
    Optional Round2 As Boolean = True) _
    As Double

    Dim Months      As Double
    Dim Part1       As Double
    Dim Part2       As Double
    Dim Fraction    As Double
    Dim Result      As Double

    Months = DateDiff("m", Date1, Date2)
    Part1 = (Day(Date1) - 1) / DaysInMonth(Date1)
    Part2 = (Day(Date2) - 1) / DaysInMonth(Date2)

    If Round2 = True Then
        ' Round to two decimals.
        Fraction = (-Part1 + Part2) * 100
        Result = Months + Int(Fraction + 0.5) / 100
    Else
        Result = Months - Part1 + Part2
    End If

    TotalMonths = Result

End Function

' Returns the count of days of the month of Date1.
'
' 2016-02-14. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DaysInMonth( _
    ByVal Date1 As Date) _
    As Integer

    Const MaxDateValue  As Date = #12/31/9999#
    Const MaxDayValue   As Integer = 31

    Dim Days    As Integer

    If DateDiff("m", Date1, MaxDateValue) = 0 Then
        Days = MaxDayValue
    Else
        Days = Day(DateSerial(Year(Date1), Month(Date1) + 1, 0))
    End If

    DaysInMonth = Days

End Function

Results:
? TotalMonths(#2016/01/15#, #2016/02/15#)
 1.03

? TotalMonths(#2018/11/15#, #2019/02/15#)
 3.03


text:
Q: ¿Por que el onClick de un enlace hace referencia a otro enlace? Tengo un ul y dentro de ese ul 3 li que tienen dentro enlaces. Para esos enlaces cada uno tiene una funcionalidad, y el ultimo necesito que cierre sesión (que lo hace) y lleve al index (Que también lo hace). El primero de los li tengo que hacer que vaya a otra página y solo eso, pero cuando le doy me cierra la sesión. Si quito el php del tercer li sigue con la sesión, asi que el php es el problema, alguno sabe que pasa?
Gracias y un saludo

        <input id="menu-toggle" type="checkbox"/>

        introducir el código aquí

ANUNCIATE

LOG IN

<a href="index.php" onclick="<?php destroySession(); ?>">CERRAR SESIÓN

A: Por que no pruebas seguir el metodo que hiciste antes con SubirAnuncio.php y Login.php e implementar el logout.php. Te dejo una idea, espero que te sirva! :) Un saludo!

            <input id="menu-toggle" type="checkbox"/>

            introducir el código aquí

ANUNCIATE

LOG IN

CERRAR SESIÓN

    //authenticate/logout.php

    <?php
    session_start(); //Para asegurarte de que la sesion esta iniciada
    session_destroy(); //Destruir la sesion
    echo 'You have been logged out. Go back';
    ?>


text:
Q: Почему не доступен ввод в textbox? В DataGrid переопределил шаблон ячейки добавив в него TextBox, у которого тоже переопределён шаблон. Один и тот же фрагмент кода, но в .Net Framework исправно работает, а в .Net Core - не работает ввод в TextBox. Отключил всё, что может повлиять - результат не меняется, если добавить новую ячейку и в переопределённый шаблон добавить TextBox из коробки, то работает. Как это поправить?
XAML:
<DataGridTemplateColumn Header="Список объектов"
   Width="*"
   HeaderStyle="{StaticResource CenterDataGridColumnsHeaders}">
      <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
              <TextBox Text="{Binding Character, UpdateSourceTrigger=PropertyChanged}"
                       BorderThickness="0"
                       TextAlignment="Center"
                       VerticalContentAlignment="Center"
                       Background="Transparent"
                       TextWrapping="Wrap">
                   <TextBox.Style>
                      <Style TargetType="{x:Type TextBox}">
                         <Setter Property="Template">
                            <Setter.Value>
                               <ControlTemplate TargetType="{x:Type TextBox}">
                                  <Border x:Name="border"
                                          BorderBrush="{TemplateBinding BorderBrush}"
                                          BorderThickness="{TemplateBinding BorderThickness}"
                                          SnapsToDevicePixels="True">
                                            <ScrollViewer x:Name="Part_ContentHost"
                                                          Focusable="False"
                                                          HorizontalScrollBarVisibility="Hidden"
                                                          VerticalScrollBarVisibility="Hidden"/>
                                  </Border>
                               <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                       <Setter Property="Background" Value="White" TargetName="border"/>
                     </Trigger>
                 <Trigger Property="IsKeyboardFocused" Value="True">
            <Setter Property="Background" Value="Transparent" TargetName="border"/>
    </Trigger>
          </ControlTemplate.Triggers>
     </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

A: Как оказалось, нужно было переопределить шаблон ScrollViewer.
XAML:
<DataGridTemplateColumn.CellTemplate>
  <DataTemplate>
    <TextBox Text="{Binding Character, UpdateSourceTrigger=PropertyChanged}"
             BorderThickness="0"
             TextAlignment="Center"
             VerticalContentAlignment="Center"
             Background="Transparent"
             TextWrapping="Wrap">
        <TextBox.Style>
          <Style TargetType="{x:Type TextBox}">
            <Setter Property="Template">
               <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                  <Border x:Name="border"
                          BorderBrush="{TemplateBinding BorderBrush}"
                          BorderThickness="{TemplateBinding BorderThickness}"
                          SnapsToDevicePixels="True">
                    <ScrollViewer x:Name="PART_ContentHost"
                                  Focusable="false"
                                  HorizontalScrollBarVisibility="Hidden"
                                  VerticalScrollBarVisibility="Hidden"
                                  Background="{TemplateBinding Background}">
                       <ScrollViewer.ContentTemplate>
                         <DataTemplate>
                          <Grid Background="{Binding Background, ElementName=PART_ContentHost}"                                                        RenderOptions.ClearTypeHint="Enabled">
                           <ContentPresenter Content="{Binding Path=Content, ElementName=PART_ContentHost}"/>
                         </Grid>
                        </DataTemplate>
                      </ScrollViewer.ContentTemplate>
                   </ScrollViewer>
                </Border>
              <ControlTemplate.Triggers>
         <Trigger Property="IsMouseOver" Value="True">
          <Setter Property="Background" Value="White" TargetName="border"/>
         </Trigger>
         <Trigger Property="IsKeyboardFocused" Value="True">
           <Setter Property="Background" Value="Transparent" TargetName="border"/>
         </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>


text:
Q: How to apply changes in `/etc/fonts/conf.d` without closing my session? I am investigating a font configuration problem and I would like to test changes I make in /etc/fonts/conf.d and /etc/fonts/conf.avail without closing my session.
Is it possible ? Apparently running fc-cache is not enough.
I run Kubuntu 20.04


text:
Q: Clarification in reference variable downcasting in java Below is the sample code
class Animal {
    void makeNoise() {System.out.println("generic noise"); }
}

class Dog extends Animal {
    void makeNoise() {System.out.println("bark"); }
    void playDead() { System.out.println("roll over"); }
}

class DogTest {
    public static void main(String [] args) {
        Animal animal = new Animal();
        Dog d = (Dog) animal;
        d.makeNoise();
    }
}

Above code compiles well but when i try to run it, i get

java.lang.ClassCastException

My assumption is it should print "generic noise" because at run time it should invoke actual Animal object makeNoise() method without giving any exception.

A: You can't cast an arbitrary Animal instance to a Dog instance, unless the instance you are casting is actually a Dog or a sub-class of Dog.
It would make more sense for the Animal class to be abstract, since an actual Animal that can be instantiated should be a specific Animal, such as Dog, Cat, etc...

A: If you had:
Animal animal = new Dog();
Dog dog = (Dog) animal;

there would be no problem.
You need to understand the difference between compile-time type and runtime type. In the code snippet above, the compile-time time of animal is Animal, while the runtime type is Dog. This is why there's no problem casting to Dog (note that the actual casting happens at runtime).
In your code, however, the runtime type of animal is Animal (same as the compile-time type). This means that the animal will point to an object on the heap, that supports the features of an Animal (which is makeNoise()), but not the features of a Dog and that's why the ClassCastException happens.

A: All answers here are technically correct. But I want to explain this from an other point of view.
First off, you have defined one Animal and one Dog. So far everything is fine. The problem comes when you (within DogTest) create an Animal and cast ti as Dog. Why? Not every Animal is a Dog. I mean, an Animal can be a Bird, a Cat, an Elephant... These Animals do not "bark". Said that, you do can cast a Dog as an Animal because all Dogs are Animals.
I hope I have clarified a bit your mind :)

A: It won't print anything, because you won't reach the line with d.makeNoise(). The java.lang.ClassCastException is thrown in the earlier line, when you try to cast to Dog something, which is not Dog.
Still, without this line, you'll get the expected result: "generic noise".

A: Best possible downcasting i can explain by re-writing your code as follows :-
public interface  Animal {
            public void show();
        }

        public abstract class Dog implements Animal {

            public void display(){
                System.out.println("Dog Called");
            }
        }

        public class Impl extends Dog{

            @Override
            public void show() {
                System.out.println("Impl Called");
            }
        }

            class DogTest {
            public static void main(String [] args) {
               Animal a = new Impl();
               /**
                * child class's method tried to be accessed with the help of
                * parent class's object using downcasting of object
                * */
               ((Dog)a).display();
            }
    }

However real time such requirements can fulfilled without using explicit downcasting of objects instead with the help of Factory Design Pattern in  which we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Complete factory pattern can be pulled from here


text:
Q: iptables fwmark does't work,always route from default table The mangle table:
Chain OUTPUT (policy ACCEPT 9427K packets, 26G bytes)
 pkts bytes target     prot opt in     out     source               destination
  19M   48G CONNMARK   all  --  *      *       0.0.0.0/0            0.0.0.0/0            CONNMARK restore mask 0xff00000
 7717  435K MARK       all  --  *      *       0.0.0.0/0            0.0.0.0/0            mark match 0x0/0xff00000 statistic mode random probability 0.50000000000 MARK xset 0x8100000/0xff00000
 7609  428K MARK       all  --  *      *       0.0.0.0/0            0.0.0.0/0            mark match 0x0/0xff00000 MARK xset 0x8000000/0xff00000
  19M   48G MARK       all  --  *      *       0.0.0.0/0            0.0.0.0/0            MARK xset 0xa0000000/0xf0000000
  19M   48G CONNMARK   all  --  *      *       0.0.0.0/0            0.0.0.0/0            CONNMARK save mask 0xff00000

the nat table:
Chain POSTROUTING (policy ACCEPT 1552 packets, 85467 bytes)
 pkts bytes target     prot opt in     out     source               destination
    2   104 MASQUERADE  all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match src-type LOCAL
    4   208 MASQUERADE  all  --  *      !docker0  172.17.0.0/16        0.0.0.0/0
461K   26M MASQUERADE  all  --  *      *       0.0.0.0/0            0.0.0.0/0              ADDRTYPE match src-type LOCAL

ip rule:
0:  from all lookup local
100:    from 192.168.0.0/24 lookup 9999
198:    from ip1 lookup 10001
199:    from ip2 lookup 10000
200:    from all fwmark 0x8000000/0xff00000 lookup 10000
200:    from all fwmark 0x8100000/0xff00000 lookup 10001
32766:  from all lookup main
32767:  from all lookup default

ip r
default dev ppp1 scope link
default dev ppp0 scope link
default via 192.168.0.1 dev eth0
x.x.x.0/25 dev ppp0 proto kernel scope link src ip1
x.x.x.0/25 dev ppp1 proto kernel scope link src ip2
169.254.0.0/16 dev eth0 scope link metric 1002
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1
192.168.0.0/24 dev eth0 proto kernel scope link src 192.168.0.107

ip r show table 10000:
default via x.x.x.1 dev ppp0

ip route get ip3:
ip3 dev ppp1 src x.x.x.x uid 0
    cache

cat /etc/sysctl.conf:
net.ipv4.conf.default.rp_filter = 2
net.ipv4.conf.all.rp_filter = 2
net.ipv4.ip_forward = 1

it always route from default route table,instead of ppp0,ppp1,ppp0,ppp1.
Any idea?

A: You should start to be sure your routing tables are working with:
ip rule add to 1.1.1.1 table 10000
ping -c 3 1.1.1.1
ip rule del to 1.1.1.1 table 10000
ip rule add to 1.1.1.1 table 10001
ping -c 3 1.1.1.1
ip rule del to 1.1.1.1 table 10001

If they are not, you might need to add x.x.x.0/25 dev ppp0 proto kernel scope link src ip1 in table 10000 and x.x.x.0/25 dev ppp1 proto kernel scope link src ip2 in table 10002.
If they are, you can check if your rules are fine:
ip route get 223.5.5.5 mark 0x10000
ip route get 223.5.5.5 mark 0x10001

If they are not, you might need to change your rules until it can match the marking.
If they are, your marking with netfilter may be wrong, you would have to change it until the mark is the one you want.


text:
Q: What iPhone SDK control is this? Can anybody tell me what the following control is called?
iPhone control http://img535.imageshack.us/img535/6615/checkcontrol.png

A: It's not a standard control, but you could make one with a UIButton with custom images.


text:
Q: Minimizing sum of ratio of linear functions (Sum of Linear Ratios Problem) Given constants $c_i \in \mathbb{R}$ and $d_i \in \mathbb{R}$ and variables $x_i \in \mathbb{R}$, where $c_i > 0, d_i > 0, x_i > 0$ can we easily solve the following optimization problem:
$$min_{x_i} \sum_i \frac{1}{c_i + d_i x_i}
$$
subject to $\sum_i x_i = C$, where $C > 0$ is another constant.
If it helps $C$ and $x_i$ can also be restricted to be integers. In that case there is a naive solution where we enumerate all combinations. This is still too expensive though.
I found the paper A Global Optimization Algorithm for Sum of Linear Ratios Problem that talks about a general version of the above problem but it is somewhat involved.
I am wondering if there is a simpler solution since the above problem looks like a special case.

A: Because the denominator must be positive, the objective function, and hence the optimization problem is convex, and can be readily formulated and solved using CVX or a similar convex optimization tool.
cvx_begin
variable x(n)
minimize(sum(inv_pos(c + d.* x)))
x >= 0
sum(x) == C
cvx_end

You change x >= 0 to x >= small_number if you prefer. Strict inequalities are treated by the solvers as if they are non-strict inequalities.
It does not help to restrict x to integer values. That would make the problem more computationally difficult to solve. Nevertheless, to do so, merely change variable x(n) to variable x(n) integer .
Here is a test problem without integer restriction:
>> n=6; C=7.4 ;c = 5*rand(n,1); d = 2*rand(n,1);
>> disp(c)
   2.107028387658593
   0.400055793339331
   0.396769045866593
   0.361881245993311
   4.501705030405445
   4.846541494332056

>> disp(d)
   0.782613917623122
   0.627170209734511
   1.106627159874890
   1.584096124994781
   1.596628166160420
   1.726517081119803

and here is the output from running the above program:
Calling SDPT3 4.0: 25 variables, 12 equality constraints
   For improved efficiency, SDPT3 is solving the dual problem.
------------------------------------------------------------

 num. of constraints = 12
 dim. of sdp    var  = 12,   num. of sdp  blk  =  6
 dim. of linear var  =  6
 dim. of free   var  =  1 *** convert ublk to lblk
*******************************************************************
   SDPT3: Infeasible path-following algorithms
*******************************************************************
 version  predcorr  gam  expon  scale_data
   HKM      1      0.000   1        0
it pstep dstep pinfeas dinfeas  gap      prim-obj      dual-obj    cputime
-------------------------------------------------------------------
 0|0.000|0.000|1.7e+01|3.4e+00|1.9e+03| 1.261398e+02  0.000000e+00| 0:0:00| chol  1  1
 1|1.000|0.598|3.9e-06|1.4e+00|5.6e+02| 1.429249e+02 -3.878636e+01| 0:0:00| chol  1  1
 2|1.000|0.966|1.0e-06|4.9e-02|7.2e+01| 5.719567e+01 -6.592350e+00| 0:0:00| chol  1  1
 3|1.000|0.540|2.8e-08|2.3e-02|1.0e+01| 3.460381e+00 -5.835158e+00| 0:0:00| chol  1  1
 4|1.000|0.442|1.6e-07|1.3e-02|4.8e+00|-2.227469e-01 -4.589011e+00| 0:0:00| chol  1  1
 5|0.921|0.925|1.7e-08|9.6e-04|4.7e-01|-1.759148e+00 -2.201532e+00| 0:0:00| chol  1  1
 6|1.000|0.575|1.1e-09|4.1e-04|1.7e-01|-1.906104e+00 -2.063560e+00| 0:0:00| chol  1  1
 7|0.981|0.919|3.2e-09|3.3e-05|1.3e-02|-1.939996e+00 -1.951918e+00| 0:0:00| chol  1  1
 8|0.961|0.971|2.6e-10|9.6e-07|3.9e-04|-1.941595e+00 -1.941964e+00| 0:0:00| chol  1  1
 9|0.956|0.918|7.3e-11|9.8e-07|3.3e-05|-1.941656e+00 -1.941686e+00| 0:0:00| chol  1  1
10|0.980|0.964|1.7e-11|8.4e-08|1.6e-06|-1.941660e+00 -1.941661e+00| 0:0:00| chol  1  1
11|1.000|0.966|3.2e-13|3.9e-09|1.3e-07|-1.941660e+00 -1.941660e+00| 0:0:00| chol  1  1
12|1.000|0.984|4.6e-14|3.2e-10|5.5e-09|-1.941660e+00 -1.941660e+00| 0:0:00|
  stop: max(relative gap, infeasibilities) < 1.49e-08
-------------------------------------------------------------------
 number of iterations   = 12
 primal objective value = -1.94166032e+00
 dual   objective value = -1.94166032e+00
 gap := trace(XZ)       = 5.46e-09
 relative gap           = 1.12e-09
 actual relative gap    = 1.02e-09
 rel. primal infeas (scaled problem)   = 4.58e-14
 rel. dual     "        "       "      = 3.23e-10
 rel. primal infeas (unscaled problem) = 0.00e+00
 rel. dual     "        "       "      = 0.00e+00
 norm(X), norm(y), norm(Z) = 2.7e+00, 4.2e+00, 1.0e+01
 norm(A), norm(b), norm(C) = 6.9e+00, 3.4e+00, 1.4e+01
 Total CPU time (secs)  = 0.20
 CPU time per iteration = 0.02
 termination code       =  0
 DIMACS: 7.9e-14  0.0e+00  5.4e-10  0.0e+00  1.0e-09  1.1e-09
-------------------------------------------------------------------

------------------------------------------------------------
Status: Solved
Optimal value (cvx_optval): +1.94166

>> disp(x) % this is the optimal value of x
   0.399054349910791
   2.815385122487830
   2.241149560765849
   1.944410952569123
   0.000000007535945
   0.000000006728979

The last 2 elements of x would be exactly zero if the optimization problem were solved exactly. The slight difference from zero is due to solver optimality tolerance.


text:
Q: Mongoose: sort query results by least occurences of word in array I have a collection of videos :
var VideoSchema = new mongoose.Schema({
  url: {
    type: String, required : true
  },
  orderBy: {
    type: Number
  },
  views: [{
    type: String
  }]
});

'orderBy' lets me define the order in which I serve videos
'views' is a list of usernames, those who have watched the video.
I want to keep users from watching again the same video until they have watched all videos in the collection. So I keep the names of users who have watched the video inside the 'views'.
Now I query for videos using 'sort'.
return this.find(videoQuery)
.skip(offset)
.limit(count || 10) // @todo 10 : param
.sort({views: {$meta: username}, 'orderBy': -1})
.exec();

And I get the error message :
Can't canonicalize query: BadValue bad sort specification

Can you help ?

A: May be wrong but from mongo docs. When you specify $meta in sort you need to include it in projectedFieldName.
https://docs.mongodb.com/manual/reference/operator/projection/meta/#proj._S_meta
So it should looks something like this
return this.find(videoQuery, { views: { $meta: 'textScore' } })
.skip(offset)
.limit(count || 10) // @todo 10 : param
.sort({views: {$meta: textScore}, 'orderBy': -1})
.exec();
UPDATED
Seems that $meta only accepts 'textScore' as @Pierre mentioned.
So another suggestion is to use underscore or native js to sort data when response comes from DB. This will be less efficient and may need some adjustments, but this will work definitely.
Hope this helps.