Q:

Selected ListBox item to Variable

I've been trying for 2 days now to save the selected value from a listBox to a variable. All suggestions I can find do not work, and the only suggestion that actually does work has been discouraged from using. Can someone please help me and tell me what I am doing wrong?
I have made the code as simple as possible for this posting. Both WPF and C# that is. In de code I show different suggestions of how it could work which I have found on this and other forums.
1.
Test 01 and Test 02 do compile alright but they both give me the same wrong result.
result in TextBox: System.Windows.Controls.ListBoxItem: ListBox Item 02
Looking at the result and the code I can kind of understand the result for 'Test 2'. It looks like a reference to what I actually want and 'SelectedItem' Could suggest this. But then in 'Test 01' I get the same result but I am asking for value instead of reference. Why?
2.
The most common suggested method is 'Test 04'. Everything I have tried gives me more or less the same error.
Error message: Compiler Error CS1061: 'ListBox' does not contain a definition for 'GetItemText' and no extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?).
It is also the shortest and simplest method so I would really like to get this method to work. Maybe I have done something wrong somewhere else (Settings in VS 2015 Maybe???). I have seen the same message before, but I was able to work around it that time.
3.
And just before decided to post this here I wanted to try 1 more thing. 'Test 03' was something I saw in another post on this website with the comment that this is not the way to do it. Ok, the original post has been edited so I do not know what was originally published, but this is the one and only thing that actually did work until now. The original post was advised against though.
I am new to WPF and C#. Normally it may take me time to find out how to do things but I get there eventually, but this time I do not really understand what has happened and something tells me that I am doing something wrong. Can someone be so kind to elaborate on one, some or all of the items outlined above? I got it working now, but is this the best way to go about this?
Code Behind (C#):
    using System.Windows;
    using System.Windows.Controls;

    namespace NLTrader
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                ///textBox.Text = listBox.SelectedValue.ToString();                         ///Test 01
                ///textBox.Text = listBox.SelectedItem.ToString();                          ///Test 02
                textBox.Text = ((ListBoxItem)listBox.SelectedItem).Content.ToString();      ///Test 03
                ///textBox.Text = listBox.GetItemText();                                    ///Test 04
            }
        }
    }

WPF Code:
    <Window x:Class="NLTrader.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:NLTrader"
            mc:Ignorable="d"
            Title="MainWindow" Height="555" Width="900">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <StackPanel
                x:Name="mainSettings"
                Grid.Row="0">
                <ListBox
                    x:Name="listBox"
                    SelectionChanged="listBox_SelectionChanged">
                    <ListBoxItem>ListBox Item 01</ListBoxItem>
                    <ListBoxItem>ListBox Item 02</ListBoxItem>
                    <ListBoxItem>ListBox Item 03</ListBoxItem>
                </ListBox>
            </StackPanel>
            <TextBox
                x:Name="textBox"
                Grid.Row="1">
            </TextBox>
        </Grid>
    </Window>

Thank you very much for your time and help.
Edit: p.s. I just notice that in order to see the comments in the code identifying which is 'Test 01, 'Test 02", 'Test 03' and 'Test 04' you will need to move the scroll bar to the right.
Edit: I also just notice that when I place the above working code in the code where it needs to be (different project) I also get an error. Last bit of euphoria down the drain... lol.
Structure is very very similar. c# code is as follows.
        public void ListingAccounts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            textBoxAccountSettingsAccountName.Text = ((ListBoxItem)ListingAccounts.SelectedItem).Content.ToString();
        }

Error Message: An unhandled exception of type 'System.InvalidCastException' occurred in NLTrader.exe
Additional information: Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ListBoxItem'.
Screenshot from VS2015 Debugger Error Message
So now I am even more at a loss than I already was. Please help me.

A:

What does it say when you hover over the SelectedItem? If it's string (and the InvalidCastException seems to say so), you should be able to do
 textBoxAccountSettingsAccountName.Text = ListingAccounts.SelectedItem.ToString()

I'd suggest a look at http://www.wpf-tutorial.com/list-controls/listbox-control/ if you haven't yet.
Just a note: The SelectionChangedEventArgs does have the selection, it's there! :P
EDIT: I can't comment, but just a warning on @funk's answer, e.AddedItems[0] will throw an indexoutofRange exception when the selection is deselected (as nothing is 'added') so you should use `e.AddedItems.FirstOrDefault() and check for null if you use his solution. The same goes for this solution I suppose, SelectedItem will be null when deselection happens


Q:

What decent web-frameworks exists for functional programming?

I would like to do some web programming using functional programming. What decent web-frameworks exists for functional programming languages?

A:

WebSharper (F#)
Yesod (Haskell)
Snap (Haskell)
Ocsigen (OCaml)

There are many many more (even I'm developing one in F#) but I think these (and Lift, already mentioned) are the most complete/popular/documented. I can't comment on Erlang frameworks.

A:

There's a list of web frameworks available for Erlang.  Summarizing that list here:

erlang-web
webmachine
Zotonic (This is actually a CMS.)
nitrogen
Chicago boss
erlyweb (Based on YAWS, but is slightly dead.)

Of those the two that look most of interest to me are webmachine and nitrogen.  YMMV.

A:

Noir is beautiful, functional and simple (in the Rich Hickey "Simple Made Easy" sense):
(defpage "/welcome" []
    "Welcome to Noir!")

(server/start 8080)

I particularly like the way that you can then build your entire web application just using function composition, supported with a few macros to enable a nice declarative DSL.


Q:

Bounding the extrema of polynomials from $\frac{d^n}{dx^n} \exp(-1/x)$

As laid out on Wikipedia, the function
$$f(x):=\begin{cases} \exp(-1/x) & x>0\\ 0 & x\le 0  \end{cases}$$
has the expression for derivatives at $x>0$,
$$ f^{(n)}(x) = \frac{p_n(x)}{x^{2n}}f(x) $$
where the polynomials $p_n$ of degree $n-1$ are recursively defined by $p_1=1$,
$$ p_{n+1} = (1-2nx)p_{n} + x^2 p_{n}'$$
I am interested in bounding $f^{(n)}$ on sets like $[0,a]$. Since its well known that all derivatives vanish at $x=0$, and  $f(x)/x^{2n}$ never vanishes for $x>0$, the local extrema of $f^{(n)}$ occurs at a zero of $p_{n+1}$, so bounding $f^{(n)}(x)$ depends on value of its zeros.
Alternatively, perhaps a crude bound on $p_n$ on these sets $[0,a]$  is obtainable from the recurrence. This sounds easier, but I have yet to make progress here as well.
Question
How do I get a bound on $f^{(n)}$? (Preferrably one that looks like the inequality below)
Motivation
to test my understanding of Gevrey functions, I have decided to check what which space (if any) this function belongs to. This requires getting some bounds on the derivative. My suspicion is that $f$ is Gevrey of order 2, i.e. for any compact set $K$(and in particular any compact set containing $0$) there is a constant $C$ such that
$$ \sup_{x\in K} |f^{(n)}(x)| \le C^{n+1} n!^2 $$
Notable "similar question"(currently unanswered)
Bounding $n$-th derivative of $x \mapsto \exp\left({-\frac{1}{x^2}}\right)$
There is a comment there that reaches somewhat the same idea (the associated recursive polynomial is important) but doesn't say any more.

A:

I thought of this after typing the question...
Let $p_n(x) = \sum_{k=0}^{n-1} p_{n,k} x^k$. We know $p_{n,0} = 1$ for all $n$. Also, $$p_{n+1,n} =-2n p_{n,n-1} + (n-1) p_{n,n-1} = -(n+1) p_{n,n-1} $$ More generally,
$$ p_{n+1,k} =  p_{n,k}-2np_{n,k-1} + (k-1)p_{n,k-1}$$
(with the understanding that for $k>n-1$ or $k<0$, $p_{n,k}=0$.) Thus
$$ P_{n+1} := \sup_k  |p_{n+1,k}| \le 2(n+1) P_n$$
This means that
$$P_{n}\le 2^{n} n! $$
so
$$\sup_{x\in [0,a]} |p_n(x)|\le2^n n!\sum_{k=0}^{n-1}  a^k =\frac{2^n n!(a^{n}-1)}{a-1}$$
Now, recall that for $x>0$, $e^{x} > \frac{x^j}{j!}$. Rearranging,
$$ e^{-x} \le \frac{j!}{x^j}\implies e^{-1/x} \le x^j j! \implies \frac{ e^{-1/x}}{x^{2n} } \le (2n)! \le 4^n n!^2$$
so I'm left with the bound
$$ \sup_{x\in [0,a]} |f^{(n)}(x)| \le C_a^{n+1} n!^3$$
So the function is Gevrey of order 3. Don't know if I can improve it...


Q:

Duplicate property '' for [simple type, on Deserialization

I'm currently facing an issue using Jackson 2.4.4 with the xml module.
The XML I want to deserialize looks like this:
<product>
    <sku>1000668-1</sku>
    <name/>
    <image>/url/or/something.jpg</image>
    <brand>test</brand>
    <sizeCM>36 mm / 19.5 cm</sizeCM>
    <colors>
        <color id="335061" name="Green"/>
    </colors>
    <genders>
        <gender id="362843" name="M"/>
    </genders>
    <occasions>
        <occasion id="322620" name="First"/>
        <occasion id="322621" name="Second"/>
        <occasion id="322627" name="Thrid"/>
        <occasion id="322628" name="..."/>
        <occasion id="322630" name="next"/>
        <occasion id="369680" name="and again"/>
    </occasions>
    <categories>
        <category id="CGO_010_002" name="Stackoverflow"/>
    </categories>
</product>

And my Product Class looks like this:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "product")
@JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders",
        "occasions", "categories" })
public class Product {

    @JsonProperty("sku")
    @JacksonXmlText
    private String sku;

    @JsonProperty("image")
    @JacksonXmlText
    private String image;

    @JsonProperty("brand")
    @JacksonXmlText
    private String brand;

    @JsonProperty("sizeCM")
    @JacksonXmlText
    private String sizeCM;

    @JsonProperty("colors")
    @JacksonXmlProperty(localName = "colors")
    private Colors colors;

    @JsonProperty("genders")
    @JacksonXmlProperty(localName = "genders")
    private Genders genders;

    @JsonProperty("occasions")
    @JacksonXmlProperty(localName = "occasions")
    private Occasions occasions;

    @JsonProperty("categories")
    @JacksonXmlProperty(localName = "categories")
    private Categories categories;

    // setter & getter ...

Next step was to map it during reading it from a file:
public static void main(String[] args) {
    JacksonXmlModule module = new JacksonXmlModule();
    XmlMapper xmlMapper = new XmlMapper(module);
         xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    product(xmlMapper);
}

public static void product(XmlMapper xmlMapper){
    String s = "/tmp/product.xml";
    Product test = null;
    try {
        test = xmlMapper.readValue(new File(s), Product.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(test.getSku());
}

After trying it like that I facing this exception:
com.fasterxml.jackson.databind.JsonMappingException: Duplicate property '' for [simple type, class com.example.jackson.model.Product]
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:266)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:241)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationConexample.java:394)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3169)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3062)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2115)
at com.example.jackson.main.TheMain.product(TheMain.java:32)
at com.example.jackson.main.TheMain.main(TheMain.java:23)

Next thing is - same Method - same ObjectMapper - another pojo + xml works fine (even the list's). Any Help or Hint wanted, I really don't know what I should do - because the exception Duplicate property '' isn't so great because the '' are really empty!

A:

Solution for this was that I switched from @JacksonXmlTextto @JacksonXmlProperty. I misunderstood how @JacksonXmlTextshould be used.
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName="product")
@JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders",
        "occasions", "categories" })
public class Product {

    @JsonProperty("sku")
    @JacksonXmlProperty(localName="sku")
    private String sku;

    @JsonProperty("image")
    @JacksonXmlProperty(localName="image")
    private String image;

    @JsonProperty("brand")
    @JacksonXmlProperty(localName="brand")
    private String brand;

    @JsonProperty("sizeCM")
    @JacksonXmlProperty(localName="sizeCM")
    private String sizeCM;

    @JsonProperty("colors")
    @JacksonXmlProperty(localName = "colors")
    @XmlElement(name="colors")
    private Colors colors;

Allowed me to parse the xml without any problem.


Q:

Pythonic way to compose context managers for objects owned by a class

It's typical to require for some task multiple objects which have resources to be explicitly released - say, two files; this is easily done when the task is local to a function using nested with blocks, or - even better - a single with block with multiple with_item clauses:
with open('in.txt', 'r') as i, open('out.txt', 'w') as o:
    # do stuff

OTOH, I still struggle to understand how this is supposed to work when such objects aren't just local to a function scope, but owned by a class instance - in other words, how context managers compose.
Ideally I'd like to do something like:
class Foo:
    def __init__(self, in_file_name, out_file_name):
        self.i = WITH(open(in_file_name, 'r'))
        self.o = WITH(open(out_file_name, 'w'))

and have Foo itself turn into a context manager that handles i and o, such that when I do
with Foo('in.txt', 'out.txt') as f:
    # do stuff

self.i and self.o are taken care of automatically as you would expect.
I tinkered about writing stuff such as:
class Foo:
    def __init__(self, in_file_name, out_file_name):
        self.i = open(in_file_name, 'r').__enter__()
        self.o = open(out_file_name, 'w').__enter__()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.i.__exit__(*exc)
        self.o.__exit__(*exc)

but it's both verbose and unsafe against exceptions occurring in the constructor. After searching for a while, I found this 2015 blog post, which uses contextlib.ExitStack to obtain something very similar to what I'm after:
class Foo(contextlib.ExitStack):
    def __init__(self, in_file_name, out_file_name):
        super().__init__()
        self.in_file_name = in_file_name
        self.out_file_name = out_file_name

    def __enter__(self):
        super().__enter__()
        self.i = self.enter_context(open(self.in_file_name, 'r')
        self.o = self.enter_context(open(self.out_file_name, 'w')
        return self

This is pretty satisfying, but I'm perplexed by the fact that:

I find nothing about this usage in the documentation, so it doesn't seem to be the "official" way to tackle this problem;
in general, I find it extremely difficult to find information about this issue, which makes me think I'm trying to apply an unpythonic solution to the problem.

Some extra context: I work mostly in C++, where there is no distinction between the block-scope case and the object-scope case for this issue, as this kind of cleanup is implemented inside the destructor (think __del__, but invoked deterministically), and the destructor (even if not explicitly defined) automatically invokes the destructors of the subobjects. So both:
{
    std::ifstream i("in.txt");
    std::ofstream o("out.txt");
    // do stuff
}

and
struct Foo {
    std::ifstream i;
    std::ofstream o;

    Foo(const char *in_file_name, const char *out_file_name)
        : i(in_file_name), o(out_file_name) {}
}

{
    Foo f("in.txt", "out.txt");
}

do all the cleanup automatically as you generally want.
I'm looking for a similar behavior in Python, but again, I'm afraid I'm just trying to apply a pattern coming from C++, and that the underlying problem has a radically different solution that I can't think of.

So, to sum it up: what is the Pythonic solution to the problem of having an object who owns objects that require cleanup become a context-manager itself, calling correctly the __enter__/__exit__ of its children?

A:

I think contextlib.ExitStack is Pythonic and canonical and it's the appropriate solution to this problem. The rest of this answer tries to show the links I used to come to this conclusion and my thought process:
Original Python enhancement request
https://bugs.python.org/issue13585
The original idea + implementation was proposed as a Python standard library enhancement with both reasoning and sample code. It was discussed in detail by such core developers as Raymond Hettinger and Eric Snow. The discussion on this issue clearly shows the growth of the original idea into something that is applicable for the standard library and is Pythonic. Attempted summarization of the thread is:
nikratio originally proposed:

I'd like to propose addding the CleanupManager class described in http://article.gmane.org/gmane.comp.python.ideas/12447 to the contextlib module. The idea is to add a general-purpose context manager to manage (python or non-python) resources that don't come with their own context manager

Which was met with concerns from rhettinger:

So far, there has been zero demand for this and I've not seen code like it being used in the wild.  AFAICT, it is not demonstrably better than a straight-forward try/finally.

As a response to this there was a long discussion about whether there was a need for this, leading to posts like these from ncoghlan:

TestCase.setUp() and TestCase.tearDown() were amongst the precursors to__enter__() and exit(). addCleanUp() fills exactly the same role here - and I've seen plenty of positive feedback directed towards Michael for that addition to the unittest API...
  ...Custom context managers are typically a bad idea in these circumstances, because they make readability worse (relying on people to understand what the context manager does). A standard library based solution, on the other hand, offers the best of both worlds:
  - code becomes easier to write correctly and to audit for correctness (for all the reasons with statements were added in the first place)
  - the idiom will eventually become familiar to all Python users...
  ...I can take this up on python-dev if you want, but I hope to persuade you that the desire is there...

And then again from ncoghlan a little later:

My earlier descriptions here aren't really adequate - as soon as I started putting contextlib2 together, this CleanupManager idea quickly morphed into ContextStack [1], which is a far more powerful tool for manipulating context managers in a way that doesn't necessarily correspond with lexical scoping in the source code.

Examples / recipes / blog posts of ExitStack
There are several examples and recipes within the standard library source code itself, which you can see in the merge revision that added this feature: https://hg.python.org/cpython/rev/8ef66c73b1e1
There is also a blog post from the original issue creator (Nikolaus Rath / nikratio) that describes in a compelling way why ContextStack is a good pattern and also provides some usage examples: https://www.rath.org/on-the-beauty-of-pythons-exitstack.html

A:

Your second example is the most straight forward way to do it in
Python (i.e., most Pythonic). However, your example still has a bug. If
an exception is raised during
the second open(),
self.i = self.enter_context(open(self.in_file_name, 'r')
self.o = self.enter_context(open(self.out_file_name, 'w') # <<< HERE

then self.i will not be released when you expect because
Foo.__exit__() will not be called unless Foo.__enter__() successfully
returns. To fix this, wrap each context call in a
try-except that will call Foo.__exit__() when an exception occurs.
import contextlib
import sys

class Foo(contextlib.ExitStack):

    def __init__(self, in_file_name, out_file_name):
        super().__init__()
        self.in_file_name = in_file_name
        self.out_file_name = out_file_name

    def __enter__(self):
        super().__enter__()

        try:
            # Initialize sub-context objects that could raise exceptions here.
            self.i = self.enter_context(open(self.in_file_name, 'r'))
            self.o = self.enter_context(open(self.out_file_name, 'w'))

        except:
            if not self.__exit__(*sys.exc_info()):
                raise

        return self

A:

As @cpburnz mentioned, your last example is best, but does contain a bug if the second open fails. Avoiding this bug is described in the standard library documentation. We can easily adapt the code snippets from the ExitStack documentation and the example for ResourceManager from 29.6.2.4 Cleaning up in an __enter__ implementation to come up with a MultiResourceManager class:
from contextlib import contextmanager, ExitStack
class MultiResourceManager(ExitStack):
    def __init__(self, resources, acquire_resource, release_resource,
            check_resource_ok=None):
        super().__init__()
        self.acquire_resource = acquire_resource
        self.release_resource = release_resource
        if check_resource_ok is None:
            def check_resource_ok(resource):
                return True
        self.check_resource_ok = check_resource_ok
        self.resources = resources
        self.wrappers = []

    @contextmanager
    def _cleanup_on_error(self):
        with ExitStack() as stack:
            stack.push(self)
            yield
            # The validation check passed and didn't raise an exception
            # Accordingly, we want to keep the resource, and pass it
            # back to our caller
            stack.pop_all()

    def enter_context(self, resource):
        wrapped = super().enter_context(self.acquire_resource(resource))
        if not self.check_resource_ok(wrapped):
            msg = "Failed validation for {!r}"
            raise RuntimeError(msg.format(resource))
        return wrapped

    def __enter__(self):
        with self._cleanup_on_error():
            self.wrappers = [self.enter_context(r) for r in self.resources]
        return self.wrappers

    # NB: ExitStack.__exit__ is already correct

Now your Foo() class is trivial:
import io
class Foo(MultiResourceManager):
    def __init__(self, *paths):
        super().__init__(paths, io.FileIO, io.FileIO.close)

This is nice because we don't need any try-except blocks -- you're probably only using ContextManagers to get rid of those in the first place!
Then you can use it like you wanted to (note MultiResourceManager.__enter__ returns a list of objects given by the passed acquire_resource()):
if __name__ == '__main__':
    open('/tmp/a', 'w').close()
    open('/tmp/b', 'w').close()

    with Foo('/tmp/a', '/tmp/b') as (f1, f2):
        print('opened {0} and {1}'.format(f1.name, f2.name))

We can replace io.FileIO with debug_file as in the following snippet to see it in action:
    class debug_file(io.FileIO):
        def __enter__(self):
            print('{0}: enter'.format(self.name))
            return super().__enter__()
        def __exit__(self, *exc_info):
            print('{0}: exit'.format(self.name))
            return super().__exit__(*exc_info)

Then we see:
/tmp/a: enter
/tmp/b: enter
opened /tmp/a and /tmp/b
/tmp/b: exit
/tmp/a: exit

If we added import os; os.unlink('/tmp/b') just before the loop we'd see:
/tmp/a: enter
/tmp/a: exit
Traceback (most recent call last):
  File "t.py", line 58, in <module>
    with Foo('/tmp/a', '/tmp/b') as (f1, f2):
  File "t.py", line 46, in __enter__
    self.wrappers = [self.enter_context(r) for r in self.resources]
  File "t.py", line 46, in <listcomp>
    self.wrappers = [self.enter_context(r) for r in self.resources]
  File "t.py", line 38, in enter_context
    wrapped = super().enter_context(self.acquire_resource(resource))
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/b'

You can see /tmp/a is closed correctly.


Q:

Can I store government ID numbers according to the PCI DSS?

I am developing a service, a part of which stores the credit card data of it's users. According to the Israeli credit card companies' requirements my users need to present their government ID number when making a transaction.
The PCI Standard prohibits the storage of CVV and credit card PIN numbers, because of information security reasons.
My question is, can I be sure that storing my users' government ID numbers is not against the PCI standard, since it serves almost the same purpose as a CVV or a PIN number - to verify the credit card holder?

A:

PCIDSS publishes how you store payment card data. A government Id is not covered.
However it probably is personally identifiable information and should still be handled with care.
The full set of requirements is buried in a pdf
https://www.pcisecuritystandards.org/document_library?category=pcidss&document=pci_dss
But basically you have to encrypt the card number, and you cannot retain the CVV2 / PIN or any of the data you might read from a card (but that you can't see by looking at it)
Everything else is allowed to be stored unencrypted.


Q:

In which type of variable store time in millis? Choosing a correct data type

in Java I'm trying to compare two different hours by converting them to milliseconds if (20:00 > 19:30) // do anything. In millis, it would be if (72000000 > 70200000) // do anything
But the smartphone doesn't do it well. I'm storing the numbers in variables long, as in the class Calendar, the method myCal.getTimeInMillis() returns a long, but it doesn't work.
I have tried changing the data type of the variables from long to double and it does work, so I figure out that those large numbers simply "doesn't fit" in the variable, but then, why the Java Calendar method getTimeInMillis() returns a long?
How does time work in Java Calendar? Thanks in advance.
Edit:
Thank you for your answers and time, I'm sorry for this question because it does work to compare different hours which are stored in long variables. I have tried again and it does work (I don't know why it didn't work before). I'm making an alarm clock app for Android and I want to compare not only two hours (and minutes and seconds), but also day of the week and so on. So I'm going to mark as the solution of this question the answer of @Sufiyan Ghori because I think it can really help me, and I think I'm gonna delete this question because it has no sense.
I'm new here (and in programming in general), so sorry for this silly question.

A:

instead of comparing hours after converting it into milliseconds you can use Date::before or Date::after methods after setting your time into two separate Date objects.
Date date1 = new Date(); // set time for first hour.
Date date2 = new Date(); // set time for second hour.

You can use Calendar to set time for each Date object, like this,
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,12);
cal.set(Calendar.MINUTE,10);
cal.set(Calendar.SECOND,31);
cal.set(Calendar.MILLISECOND,05);

date1 = cal.getTime(); //set time for first hour

and then use these for comparison,
if(date1.after(date2)){
}

if(date1.before(date2)){
}

and Date::equals,
if(date1.equals(date2)){
}


Q:

Find deprecated API in Google Scripts

I have a message stating our Google Apps domain is using an API that will be deprecated soon.  When I look at the list of upcoming APIs I don't see any I believe we are using, but I have copied some code from various example sources and may be missing something.  Outside looking at every line of code in the various spreadsheets, forms, etc, is there a way to determine what code in what files might be using an API which is about to go away?  If I have o manually look at them all I am sure to miss something.  And if it i in an old test script I can gladly throw them away.  Just trying to most efficiently find any problems as we area  non-profit and all my time has been volunteer time that is better spent on new directions.
Regards,
Karl S

A:

You can run a report from your admin console to see where in your domain scopes have been authorized.
https://admin.google.com/AdminHome?#Reports:subtab=token-audit
Here you can search for the scopes of the depreciating apis.  If found it will return the app associated with them
Here are the scopes that are depreciating.
https://apps-apis.google.com/a/feeds/.*?/(user|nickname|emailList)/

And
https://apps-apis.google.com/a/feeds/(group|user|alias|customer|orgunit|orguser)/


Q:

download CSV from google Insight?

I successfully did that before in the past 4-5 maybe 6 months back, but now i see the site has changed .I am able to get the desired search result using HTTPWEBREQUEST the issue is with downloading the CSV file.
The download wont work i replicate exact same using WEBCLIENT get all the cookies but still it wont work .
When i do so i get this in the file

.....meta http-equiv="refresh" content="0; url='http://www.google.com/trends#content=1&geo=US-AL&q=snooker&cmpt=q&hl=en-AU'">

      location.replace("http://www.google.com/trends#content\x3d1\x26geo\x3dUS-AL\x26q\x3dsnooker\x26cmpt\x3dq\x26hl\x3den-AU")

The code to download file is as follows:
public void downloadsheet(string url, string path)
    {
        try
        {
            using (WebClient client = new WebClient())
            {

                string tmpCookieString = string.Empty;

                string[] array = webBrowser1.Document.Cookie.Split(new char[]
                        {
                            ';'
                        });
                for (int i = 0; i < array.Length; i++)
                {
                    string cookie = array[i];
                    string name = cookie.Split(new char[]
                            {
                                '='
                            })[0];
                    string value = cookie.Substring(name.Length + 1);

                    //client.Headers.Add(name, value);
                    if (i < array.Length - 1)
                    {
                        tmpCookieString = tmpCookieString + name + "=" + value + ";";
                    }
                    else
                    {
                        tmpCookieString = tmpCookieString + name + "=" + value;
                    }
                }

                client.Headers.Add(HttpRequestHeader.Cookie, tmpCookieString);
                client.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
                client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");
                client.Headers.Add("Accept-Language", "en-US");
                using (FileStream file = File.Create(path))
                {
                    byte[] bytes = client.DownloadData(url);
                    file.Write(bytes, 0, bytes.Length);
                }
            }
        }
        catch (Exception exp_DE)
        {
        }
    }

The url is use  is:

http://www.google.com/trends/trendsReport?hl=en-AU&q=snooker&geo=US-AL&cmpt=q&content=1&export=2

Any help much appreciated.
MORE INFO:
If i use WebBrowser control to navigate to the respective link above it does open up a dialogue box..

A:

The problem is the HttpOnly cookies (i.e. SID and HSID) are missing from WebBrowser.Document.Cookie for security purpose.
Here is the solution:
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

private static string GetGlobalCookies(string uri)
{
    uint datasize = 2048;
    StringBuilder cookieData = new StringBuilder((int)datasize);
    if (InternetGetCookieEx(uri, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)
        && cookieData.Length > 0)
    {
        return cookieData.ToString();
    }
    else
    {
        return null;
    }
}

public void downloadsheet(string url, string path)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            string tmpCookieString = GetGlobalCookies(webBrowser1.Url.AbsoluteUri);

            client.Headers.Add(HttpRequestHeader.Cookie, tmpCookieString);

            client.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
            client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");
            client.Headers.Add("Accept-Language", "en-US");
            using (FileStream file = File.Create(path))
            {
                byte[] bytes = client.DownloadData(url);
                file.Write(bytes, 0, bytes.Length);
            }
        }
    }
    catch (Exception exp_DE)
    {
    }
}

Of course, you should sign in your account before calling InternetGetCookieEx.


Q:

Should we make exceptions for the "lesser" Stack Exchange sites?

Most of my time is spent on the Stack Overflow site.  I find that when I ask a question that is off topic it is closed fairly quickly.  For a site that has over one million questions and has such a dedicated fan base this is fine.
When you are on a less used Stack Exchange site, it seems like it might make sense to relax some of the controls we have put in place in order to gain a wider audience.
I guess a summarized version of my question would be:

Would we prefer to have a site that
  strictly focuses on one topic but gets
  little use or a site that has a more
  relaxed focus and gets a larger
  audience?

This question is spawned from my personal experiences from:

Why do Zinc Lozenges make everything taste like cardboard? on the Cooking Stack Exchange, Seasoned Advice.

A:

The site scope is decided by regular users of the site, and not by the people who happend to be walking by or even Jeff.
So, if feel like cooking.se could benefit from expanding its scope, you should appeal to the cooking folks directly: they have their own meta. None of the decisions we might make here will have any value.

A:

No, we shouldn't. The idea is that those questions asked during the early days establish the focus, and essentially become/define the site itself, and its 'acceptable' questions.
Allowing easy, off-topic, tangential or borderline questions into the site in those early days — and even worse, during the private beta — serves to reduce the incentives for experts to come to the site, as it's littered with 'fun' or 'trivial' questions, rather than questions targeted towards a professional audience.
This is touched on in Jeff's blog entry.
It's worth noting that, while I think off-topic/easy (etc.) questions should not be asked, it's absolutely fine to ask questions which re-focus the community. As, again, Jeff noted: Stack Overflow is you; re-focusing is fine, reducing the quality, it seems, is not.

A:

You don't get a wider audience by having more questions, you get a wider audience by having more good questions. “Good” isn't an absolute term here, the question has to fit the site somehow. If you allow too many questions that don't appeal to the core audience, you'll lose the experts. Without experts, there is no site..
Now it's sometimes possible to stretch the boundaries a little. But you have to tailor your question to your audience. Your question looks like an interesting question for a medical audience. For a chef, taste is a central preoccupation, but not the mechanics of it. If you're interested in how colds and medicines affect taste, try framing your question around food: what kinds of foods remain tasteful when you have a cold? How can you adapt your cooking to eaters who are taking this particular medicine?


Q:

Handle List in Redis

A large collection of Master Data (50K records in a list) needs to be cached using Redis. but the application will retrieve single records from master data. Does it make sense to serialize the 50K records in a list and store it in Redis and every time Get the serialized string and deserialize to List object and query using linq and return one data?
e.g.
store
IDistributedCache _cache

// data is list<object> of size 50K
var jsonString = JsonConvert.SerializeObject(data);
await _cache.SetStringAsync(key, jsonString, options);

retrieve
var cachedItem = await _cache.GetStringAsync(key);
var result = JsonConvert.DeserializeObject<T>(cachedItem);
...
return result.where(x=>x.Id=id)

because the DeserializeObject of a large string is not efficient. If I store one by one in redis and if there is a requirement to also needs to be stored as whole then I am worried there will be a data duplication storing same data twice. so thats why I prefer to store 50K as whole.
any advice?

A:

The usage:
var result = JsonConvert.DeserializeObject<T>(cachedItem);
...
return result.where(x=>x.Id=id)

strongly suggests that something very inefficient is happening here. If you want to be able to fetch by a key, the more obvious model here would be a redis hash, using the Id as the key, and the serialized payload for each value (HashSet[Async]). Then you can fetch, add, update or remove indivudual elements individually; you can also still get everything if needed (HashGetAll[Async]/HashScan[Async]).
You could also store each item individually (StringSet[Async]) using the id as part of the key, but if you do that, then there is no good mechanism to get the entire list.


Q:

fetchEntityByKey not making any requests to the server

I'm trying to create a filemanager using Angularjs and I recently discovered Breezejs and was interested in trying to use it to communicate with my backend and manage my model relations. The backend is a rest api over which I have full control.
I am however running into a problem. I know the id of the file, so I would like to make a request to url of the form backend_url/files/:fileId where :fileId is the url of the file base64 encoded. According to the documentation I should use EntityManager.fetchEntityByKey() for this purpose. This is the function that i use to create the Angularjs service:
var FilestoreService = function () {

    var dataService, manager;

    dataService = new breeze.DataService({
        serviceName: "../VFS-Symfony-Backend/web/app_dev.php/filesystems/local/",

        hasServerMetadata: false
    });

    manager = new breeze.EntityManager({
        dataService: dataService
    });

    manager.metadataStore.addEntityType(fileEntityType);

    return {
        findOneById: function (id) {
            /* I have tried to leave the 3th argument empty or changing it to false with the same results */
            return manager.fetchEntityByKey("File", id, true).then(function(){console.log("success");}).fail(function(){console.log("failure");});

            /* I have also tried the following approach with the same result:
            var type, key, query;

            type = manager.metadataStore.getEntityType("File");
            key = new breeze.EntityKey(type, id);
            query = breeze.EntityQuery.fromEntityKey(key);

            return manager.executeQuery(query);
             */
        }
    };
};

where fileEntityType is defined as:
var FileEntityType = new breeze.EntityType({
    shortName: "File"
});

FileEntityType.addProperty(new breeze.DataProperty({
    name: "uri",
    dataType: breeze.DataType.String,
    isNullable: false
}));
FileEntityType.addProperty(new breeze.DataProperty({
    name: "mTime",
    dataType: breeze.DataType.Int16,
    isNullable: false
}));
FileEntityType.addProperty(new breeze.DataProperty({
    name: "type",
    dataType: breeze.DataType.String,
    isNullable: false
}));
 FileEntityType.addProperty(new breeze.DataProperty({
    name: "size",
    dataType: breeze.DataType.int16,
    isNullable: true
}));

However, when I call findOneById no request is made to the server and 2 lines are logged to the console:

Should be empty:[] by q.js
failure (as per the fail() callback function)

A 'normal' query (manager.executeQuery(new breeze.EntityQuery().from("Files"));) does result in a request to the server as expected.
I am really quite lost here. I have searched for a solution all weekend and finaly decided to post on SO hoping someone might be able to help me.
Thanks very much for reading.

A:

At least one problem is that you haven't identified the key ('id'?) in your metadata description of the "File" entity type. You have defined every other property except the 'id' property.

You know this but let me tell other readers of this question who may not understand that you are defining the metadata on the JS client rather than retrieving it from the server.

I'm also curious why you are using int16? Is that really the right type? Do you really need to shave off the two bytes?
Finally, Breeze's fetchEntityByKey won't make a request URL in the form "backend_url/files /:fileId". Instead, the request URL will be "backend_url/files /?id=:fileId" as befits an OData query. See the network traffic for Id queries in the queryTests.cs of the DocCode sample.
You can still get that file if the server expects the URL you specified. You won't be using the Breeze query syntax. You'll just hit the service with the URL it expects, e.g.,

function findOne(id) {
    // check cache first
    var file = manager.getEntityByKey('File', id);
    if (file) {
       console.log("got it from cache");
       return Q(file); // got it; return in resolved promise
    }
    // not in cache; get from server
    return breeze.EntityQuery
        .from('Files/'+id) // constructs the URL you want
        .using(manager).execute()
        .then(function(data){
            console.log("success");}
            // return the file in a resolved promise
            return data.results[0] || null;
         })
        .fail(function(error){
            console.log("failure: "+ error.message);
         });
}

This is a variation on the getByIdCacheOrRemote method in queryTest.cs in the DocCode sample.
Yes, it's longer. You're reimplementing fetchEntityByKey so you can hit the remote service the way it expects.
The method begins by looking for the file in cache. The getEntityByKey is a synchronous search of the cache. The findOne method has async syntax ... returns a promise ... because it might have to go to the server. So if we find the file in cache (synchronously), we wrap the result in a resolved Q.js promise for the benefit of the caller which is expecting findOne to be asynchronous.
If the file is not found in cache, you go to the server with a "query" that is really just a request on the URL of your choice.
I haven't tried this a long time. I'm sure you'll tell me if it works ... or does not. If it doesn't, it should and we'll fix it so it does.

A:

As Ward suggested the EnityType I created did need one of its field to be marked as the key field. Besides that the EntityType also needs to have a defaultResourceName to be supplied to its constructor. I think this explains why the 'normal' query did work (the resourceName is supplied by from()) and why fetchEntityByKey did not work. The updated FileEntityType now looks like  this:
var FileEntityType = new breeze.EntityType({
    shortName: "File",
    defaultResourceName: "files"
});
FileEntityType.addProperty(new breeze.DataProperty({
    name: "id",
    dataType: breeze.DataType.String,
    isNullable: false,
    isPartOfKey: true
}));

// These properties were not altered
FileEntityType.addProperty(new breeze.DataProperty({
    name: "uri",
    dataType: breeze.DataType.String,
    isNullable: false
}));
FileEntityType.addProperty(new breeze.DataProperty({
    name: "mTime",
    dataType: breeze.DataType.Int16,
    isNullable: false
}));
FileEntityType.addProperty(new breeze.DataProperty({
    name: "type",
    dataType: breeze.DataType.String,
    isNullable: false
}));
FileEntityType.addProperty(new breeze.DataProperty({
    name: "size",
    dataType: breeze.DataType.int16,
    isNullable: true
}));


Q:

Access violation using a C++ function from a DLL

I have a game engine written in C++ which I'm porting to Windows (from Mac). It uses C++11 and OpenGL, and for all intents and purposes, it runs!
I'm using a DLL for my game engine which is linked implicitly to the game .exe at runtime. The problem is, when I try to use a utility class from the DLL, FileSystem, to find a resource file (a texture, but I don't think it's important), I get this error:
First-chance exception at 0x00007FF9CF988830 (PocoFoundation64.dll) in TestEquinox.exe: 0xC0000005: Access violation reading location 0x000000136A4FF000.
The problem comes when I call this method of my FileSystem class from the DLL (it's designed to take a filename/partial path and it looks in various places to find the full path):
Poco::Path FileSystem::Get(const std::string &filename) {
std::vector<Poco::Path> paths = {
        filename,
        ResourceFolder() / filename //<<<<< ERROR HERE
    };

    for (const Poco::Path &path : paths) {
        try {
            if (Poco::File(path).exists()) {
                return path;
            }
        } catch (...) { }
    }

    Logger("FileSystem", std::cerr) << "Could not find file '" << filename << "'!";
    return {};
}

Visual Studio shows the error as being at the call of ResourceFolder(), another method from the same class, also in the DLL. This appears so:
Poco::Path FileSystem::ResourceFolder() {
    Poco::Path userData;

    //--SNIP-- (other OS's #ifdef'd here)
    // GAME->StartupPath is a std::string containing the exe's parent folder
    userData = (Poco::Path(GAME->StartupPath).parent() / "Resources").makeDirectory();
    //--SNIP-- (and here)

    try {
        if (!Poco::File(userData).exists()) {
            Poco::File(userData).createDirectories();
        }
    } catch (...) {}

    return userData;
}

From the looks of it, it's to do with Poco's data types not being instantiated properly? I've built it from source with all the same compiler settings (64-bit, multi-byte character set, VS2013), so I don't see how it could be a name mangling/data layout issue.
One more thing to note - I copied the entire FileSystem class from the DLL to a class local to my game project, called FileSystem2. Calling FileSystem2::Get with the same parameters worked correctly and without crashing, despite being the same code.
Hoping someone can point me in the right direction?!

A:

Usually errors like this stem from using incompatible runtime libraries that your module uses.  Please check the following for all of your modules in the Visual Studio properties:
Project Properties -> C/C++ -> Code Generation -> Runtime Library.
The runtime setting (Multithread DLL, Multithread Debug DLL, etc.) must match up with all the modules you're compiling.  If they do not match, choose one runtime, and rebuild all of your modules using that runtime.


Q:

Get the pull request ID of a continuous deployment release [Azure Pipelines]

I am trying to setup azure pipelines to trigger a build on every PR update, and a release on every merge. For a couple of reasons when the PR is merged, i need to access data saved by the latest validation build of the PR.
However to do that i need the PRid during the run of the Release pipeline. How can one achieve that?

A:

Based on your scenario, to my knowledge, it is complex to get related build information in your release. Besides, it may cause unexpected result if not cover all possible scenarios.
I'd suggest that you could refer to these steps blow:

Remove publish build/pipeline artifact or unnecessary tasks, just remain tasks for validation, which will save a lot of time. (Because, in general, the validation build will be triggered too many times, waste too much time to publish useless artifact or other data)
Create a new build pipeline and enable Continuous integration for target branch (e.g. master)
Add publish build/pipeline artifact task
Edit release pipeline and link this build pipeline and enable Continuous deployment. (Could add additional filters)

With this way, after completing the pull request, this new build pipeline will be triggered and will publish necessary artifact, then the release will be triggered.
For pull request validation builds, they just do tasks to validate the code (e.g. build project), but not publish artifact.
Simple scenario for saving time:
A pull request has 50 validation builds

old way: publish artifact of each takes 1 minutes, then total time is 50 minutes
new way: the new pipeline do tasks for build and publish, it just run once and may just takes 10 minutes.

Then you can save 40 minutes.


Q:

Сильно тормозит Visual Studio(2017)

При написании кода студия начинает сильно тормозить (1-2) секунды, потом отлагивает, и так все время.Проблема появилась пару дней назад.Обновлена до последней версии.Такая же проблема и в visual studio 2010 года, но нет в visual C#.Переходить на эти старые версии не вариант.Заранее буду благодарен за помощь!

A:

Всё зависит от характеристик вашего железа, а именно: производительности процессора, частоты и количества оперативной памяти, скорости работы жёсткого диска / твердотельного накопителя. Также, проверьте, не заполнен ли диск C, а также диск установки Visual Studio.
Если честно - студия всегда лагает, даже на самом сильном железе. Вопрос в том, насколько тяжело это дело происходит и конечно-же частота таких "лагов" - в зависимости от железа это происходит с определённой периодичностью.
По своему опыту скажу, что переустановка зачастую помогает (возможно лаги спровоцированы ошибками в ПО).
Также, плагин ReSharper ужесточает лаги из-за своей "тяжести". Если он у вас установлен - попробуйте отключить его.


Q:

Comparator breaching general contract

The below code is a edited version of Dave Koelle's AlphanumComparator. The edit contains code which sorts empty strings to the end of the list, or bottom of the JTable in my case. The problem is a java.lang.IllegalArgumentException: Comparison method violates its general contract! occurs.
To fix my problem I looked into it and found reasons such as the comparator doesn't have a return 0; in the correct place. I also found a comment in the Java bug database which read

The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation.
  If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behavior

import java.util.Comparator;
import javax.swing.JTable;
import javax.swing.SortOrder;

public class AlphanumComparator implements Comparator<String> {
    JTable table;

    public AlphanumComparator(JTable table) {
        this.table = table;
    }

    private final boolean isDigit(char ch) {
        return ch >= 48 && ch <= 57;
    }

    private final String getChunk(String s, int slength, int marker) {
        StringBuilder chunk = new StringBuilder();
        char c = s.charAt(marker);
        chunk.append(c);
        marker++;
        if (isDigit(c)) {
            while (marker < slength) {
                c = s.charAt(marker);
                if (!isDigit(c))
                    break;
                chunk.append(c);
                marker++;
            }
        } else {
            while (marker < slength) {
                c = s.charAt(marker);
                if (isDigit(c))
                    break;
                chunk.append(c);
                marker++;
            }
        }
        return chunk.toString();
    }

    public int compare(String s1, String s2) {
        boolean swapInt = table.getRowSorter().getSortKeys().get(0).getSortOrder() == SortOrder.ASCENDING;

        int thisMarker = 0;
        int thatMarker = 0;
        int s1Length = s1.length();
        int s2Length = s2.length();

        if(s1Length != 0 && s2Length != 0) {
            while (thisMarker < s1Length && thatMarker < s2Length) {
                String thisChunk = getChunk(s1, s1Length, thisMarker);
                thisMarker += thisChunk.length();

                String thatChunk = getChunk(s2, s2Length, thatMarker);
                thatMarker += thatChunk.length();

                int result = 0;
                if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) {
                    int thisChunkLength = thisChunk.length();
                    result = thisChunkLength - thatChunk.length();
                    if (result == 0) {
                        for (int i = 0; i < thisChunkLength; i++) {
                            result = thisChunk.charAt(i) - thatChunk.charAt(i);
                            if (result != 0) {
                                return result;
                            }
                        }
                    }
                } else {
                    result = thisChunk.compareTo(thatChunk);
                }

                if (result != 0)
                    return result;
            }

            return s1Length - s2Length;
        } else {
            if(swapInt) {
                if(s1Length == 0) {
                    return 1;
                } else {
                    return -1;
                }
            } else {
                if(s1Length == 0) {
                    return -1;
                } else {
                    return 1;
                }
            }
        }
    }
}

Would someone be able to help fix my problem and explain why this comparator is violating the Comparable contract
Exception stack trace if needed
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.ComparableTimSort.mergeLo(ComparableTimSort.java:744)
    at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:481)
    at java.util.ComparableTimSort.mergeForceCollapse(ComparableTimSort.java:422)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:222)
    at java.util.Arrays.sort(Arrays.java:1246)
    at javax.swing.DefaultRowSorter.sort(DefaultRowSorter.java:607)
    at javax.swing.DefaultRowSorter.setSortKeys(DefaultRowSorter.java:319)
    at javax.swing.DefaultRowSorter.toggleSortOrder(DefaultRowSorter.java:480)
    at javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler.mouseClicked(BasicTableHeaderUI.java:112)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
    at java.awt.Component.processMouseEvent(Component.java:6538)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

A:

I think the problem is that your code never examines s2Length when s1Length is zero. You need to add another check to see if both strings are empty, like this:
if(swapInt) {
    if(s1Length == 0 && s2Length != 0) {
        return 1;
    } else if (s2Length == 0 && s1Length != 0) {
        return -1;
    } else {
        return 0;
    }
} else {
    if(s1Length == 0 && s2Length != 0) {
        return -1;
    } else if (s2Length == 0 && s1Length != 0) {
        return 1;
    } else {
        return 0;
    }
}

Your current implementation returns 1 or -1 even when the two strings are empty (meaning that they must compare as equal and return zero). New sorting algorithm detects this problem, and throws an exception.
Note:
You should be able to simplify this code further by making swapInt an int that is either 1 or -1, depending on the getSortOrder result:
if(s1Length == 0 && s2Length != 0) {
    return swapInt;
} else if (s2Length == 0 && s1Length != 0) {
    return -swapInt;
} else {
    return 0;
}


Q:

String Replace not work

I have a string (an example of its value is {"id":"123241077871_4423423423414"}) and I only require the part with the numbers and the underscore. However, my way of doing it with the String.Replace method doesn't work. Can anyone help me?
This is what I've tried:
Settings.Default["lastid"].ToString().Replace('{"id":"'+"}',null);

A:

Your code should be
Settings.Default["lastid"].ToString().Replace("{\"id\":\"", "").Replace("\"}","");

As Jon Skeet said, currently, it's not a valid string literal. In addition, Replace only searches for one string of text. You can't do both of them in one pass.


Q:

AmChart StartDuration doesn't work

I'm having trouble with the startDuration property of an AmChart serial chart.
My code for setting the chart at the loading of the entire page:
function setBasicPropertiesAverageScoreChart() {

    //Basic properties
    averageScoreChart = new AmCharts.AmSerialChart();
    averageScoreChart.dataProvider = [];
    averageScoreChart.balloon.textAlign = 'left';
    averageScoreChart.startDuration = 1;
    averageScoreChart.numberFormatter = {
      precision:2,decimalSeparator:",",thousandsSeparator:"."
    };
    averageScoreChart.gridAboveGraphs = true;

    //Graph
    var graph = new AmCharts.AmGraph();
    graph.balloonText = "[[balloonText]]";
    graph.valueField = "score";
    graph.fillColorsField = "fillcolor";
    graph.type = "column";
    graph.lineAlpha = 0.2;
    graph.fillAlphas = 0.8;
    averageScoreChart.addGraph(graph);

    //CategoryAxis
    var catAxis = averageScoreChart.categoryAxis;
    //catAxis.gridCount = averageScoreChart.dataProvider.length;
    catAxis.gridPosition = "start";
    catAxis.gridAlpha = 0;
    catAxis.tickPosition = "start";
    catAxis.tickLength = 20;

    // ValueAxis
    var valueAxis = new AmCharts.ValueAxis();
    valueAxis.minimum = 0;
    //valueAxis.axisAlpha = 0;
    valueAxis.gridAlpha = 0.2;
    valueAxis.gridColor = "#FFFFF";
    valueAxis.dashLength = 0;
    //valueAxis.minimum = 0;
    averageScoreChart.addValueAxis(valueAxis);

    averageScoreChart.write('chartaveragescore');

}

I call this function on the $(document).ready like this:
$(document).ready(function () {
    setBasicPropertiesAverageScoreChart();
    setBasicPropertiesAllScoresChart();
});

The filling of the actual chart is done in another function that is triggerd when a listbox or other html element is being changed. This function is:
function updateAverageScore() {

    showLoader();

    var organization = $("#organization").val();
    var indicator = $("#indicators").val();
    var funcid = "fill_chart_average_score";

    $.getJSON('functions/getfunctions.php', {
        "organization":organization,
        "indicator":indicator,
        "funcid":funcid},

    function(dataChart) {
        if (dataChart == null) {
            bootbox.alert("Er ging iets fout. Probeer het nogmaals");
        } else {
            averageScoreChart.dataProvider = dataChart;
            averageScoreChart.categoryField = "organisatie";
            averageScoreChart.validateData();
          }
    });

    hideLoader();
}

Most important goal of this function is to get json data from MySQL and set this data as the dataProvider for the chart.
When this function is called for the first time I get the bouncy effet of the filling of the chart, but all the changes after the first one, the effect doesn't appear anymore.
I can't seem to figure out why the effect only performs the first time.

A:

I found the solution: in the function that changes the dataProvider I again call the function that sets the basic properties of the AmChart.
My function now is:
function updateAverageScore() {

    showLoader();

    var organization = $("#organization").val();
    var indicator = $("#indicators").val();
    var funcid = "fill_chart_average_score";

    $.getJSON('functions/getfunctions.php', {
        "organization":organization,
        "indicator":indicator,
        "funcid":funcid},

    function(dataChart) {
        if (dataChart == null) {
            bootbox.alert("Er ging iets fout. Probeer het nogmaals");
        } else {
            setBasicPropertiesAverageScoreChart();
            averageScoreChart.dataProvider = dataChart;
            averageScoreChart.categoryField = "organisatie";
            averageScoreChart.validateData();
          }
    });

    hideLoader();
}

This works :).


Q:

TCPDF and FPDI with multiple pages

This looks like the simplest thing but I can't get it to work.
I need to add text to the first page of a multi-page pdf (could be any number of pages)
Using this code on a two page pdf (without the for loop, just using $pdf->importPage(2)) I end up with two pages but the second page is a repeat of page one. The text is written on the first page only which is good but I need all pages included in the output pdf. Here is my code
// Original file with multiple pages
$fullPathToFile = 'full/path/to/file.pdf';

class PDF extends FPDI {

    var $_tplIdx;

    function Header() {

        global $fullPathToFile;

        if (is_null($this->_tplIdx)) {

            $this->setSourceFile($fullPathToFile);
            $this->_tplIdx = $this->importPage(1);

        }
        $this->useTemplate($this->_tplIdx);

    }

    function Footer() {}

}

// initiate PDF
$pdf = new PDF();
$pdf->setFontSubsetting(true);

// add a page
$pdf->AddPage();

// The new content
$pdf->SetFont("helvetica", "B", 14);
$pdf->Text(10,10,'Some text here');

// How to get the number of pages of original pdf???
// $numPages = $pdf->getNumPages(???);

// Carry on adding all remaining pages starting from page 2
for($i=2;$i<=$numPages;$i++) {
    // Add another page
    $pdf->AddPage();
    // Do I need to declare the source file here?
    // $pdf->setSourceFile($fullPathToWD);
    $pdf->importPage($i);
}

// Output the file as forced download
$pdf->Output('theNewFile.pdf', 'D');

Links to docs
TCPDF Classes
http://www.tcpdf.org/doc/code/classTCPDF.html#a5171e20b366b74523709d84c349c1ced
FPDI Classes
http://www.setasign.de/support/manuals/fpdi/
FPDF_TPL Classes
http://www.setasign.de/support/manuals/fpdf-tpl/

A:

Solved my problem...
// Original file with multiple pages
$fullPathToFile = 'full/path/to/file.pdf';

class PDF extends FPDI {

    var $_tplIdx;

    function Header() {

        global $fullPathToFile;

        if (is_null($this->_tplIdx)) {

            // THIS IS WHERE YOU GET THE NUMBER OF PAGES
            $this->numPages = $this->setSourceFile($fullPathToFile);
            $this->_tplIdx = $this->importPage(1);

        }
        $this->useTemplate($this->_tplIdx);

    }

    function Footer() {}

}

// initiate PDF
$pdf = new PDF();
$pdf->setFontSubsetting(true);

// add a page
$pdf->AddPage();

// The new content
$pdf->SetFont("helvetica", "B", 14);
$pdf->Text(10,10,'Some text here');

// THIS PUTS THE REMAINDER OF THE PAGES IN
if($pdf->numPages>1) {
    for($i=2;$i<=$pdf->numPages;$i++) {
        $pdf->endPage();
        $pdf->_tplIdx = $pdf->importPage($i);
        $pdf->AddPage();
    }
}

// Output the file as forced download
$pdf->Output('theNewFile.pdf', 'D');

You get the number of pages by adding the first part of this line
$this->numPages = $this->setSourceFile($fullPathToFile);

And see the second last block of code - the for loop adds the remainder of the pages.
Don't know if this is how it should be done? I read in a few places that it wasn't even possible to achieve this, also the code is not supplied in the docs. However, this works, hope it helps someone.

A:

I struggled with this a little and tried to come up with simplest way to add some text to the last page of a multi-page document.  Here is the very simple code that worked for me:
require_once('fpdf/fpdf.php');
require_once('fpdf/fpdi.php');
$pdf = new FPDI();
$fullPathToPDF = '/usr/local/common/my.pdf';
$pageCount = $pdf->setSourceFile($fullPathToPDF);
for ($i = 1; $i <= $pageCount; $i++) {
    $pdf->importPage($i);
    $pdf->AddPage();
    $pdf->useTemplate($i);
}
$pdf->SetFont('Helvetica');
$pdf->SetXY(110, 225);
$pdf->Write(8, 'A complete document imported with FPDI');
$pdf->Output($fullPathToPDF);

Just change the full path to file to a location where you have a multi-page PDF.


Q:

What is the alternate to hex values in java

how do i use hex value replacement in my code
and also is there any issues while using the hex values, regarding the Pointer from the main activity?
such errors like NullPointerExceptions ...

A:

You can use the prefix 0x for variables to specify that they're hex values, e.g:
int x = 0x12F8

In Java you do not have to set pointers, therefore there can be no NullPointerExceptions from simply assigning a variable a hex value.


Q:

ES6 classes don't work on Chrome 47

Google Chrome claims to support ES6 classes since version 42, but it gives Uncaught SyntaxError: Unexpected token class(…) when i run the simple code from below in the console:
class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }

Firefox also doesn't work. Microsoft Edge works just fine. Is this normal?

A:

Are you in "use strict" mode?

ES6 classes solve this by providing JavaScript a clean, standardized syntax for classes. This new syntax is available in Chrome 42 for JavaScript written in strict mode.


Q:

how to check DEBUG true/false in django template - exactly in layout.html

I would like distinguish a look of some toolbar in layout.html depending if DEBUG = True or not.
I am aware of this answer using django.core.context_processors.debug but it forces me to use RequestContext instead of Request what I not really like, btw how can I use RequestContext for layout.html which extends base.html?
And generally is there some better way to that than mentioned one or the one using custom template tag?
I am currently on Django 1.7

A:

In newer versions of Django it is possible just by specifying INTERNAL_IPS in settings.
For example:
INTERNAL_IPS = (
    '127.0.0.1',
    '192.168.1.23',
)

and then in template just:
{% if debug %}

because context processors responsible for that by default, and the answers from How to check the TEMPLATE_DEBUG flag in a django template? are bit deprecated.


Q:

Аналог нативной функции array_unique без использования встроенных функций для работы с массивами

Написать аналог нативной функции array_unique без использования встроенных в PHP функций для работы с массивами. Нужно написать оптимально, т.к. во входящем массиве может быть до 1 000 000 элементов
Мой вариант:
// аналог встроенной ф-ции in_array
function myInArray($needle, array $haystack, $strict = false)
{
    foreach ($haystack as $item) {
        if ($strict ? ($needle === $item) : ($needle == $item)) {
            return true;
        }
    }
    return false;
}

function myArrayUnique(array $array)
{
    $unique_array = array();
    foreach ($array as $item) {
        if (!myInArray($item, $unique_array)) {
            $unique_array[] = $item;
        }
    }
    return $unique_array;
}

echo '<pre>';
print_r(myArrayUnique($array));
echo '</pre>';

Почему не подходит мой вариант (из комментария)
Мой метод не сохранит ключи например в работе с массивом:
$arr = array("a" => "green", "red", "b" => "green", "blue", "red");

Результат должен быть:

Array([a] => green [0] => red [1] => blue).

А мой вариант кода вернет:

Array( [0] => green [1] => red [2] => blue )

A:

Если проблема только в ключах, то вот немного измененный код, который вернет и ключи, которые вам нужны (функция myArrayUnique):
foreach ($array as $key => $item) {
    if (!myInArray($item, $unique_array)) {
        $unique_array[$key] = $item;
    }
}

Также я написал другую реализацию нужной функции и сделал небольшой тест производительности для массива с 1000000 элементов:
<?php

$array = array();
$size = 1000000;
$min = 1;
$max = 100;

for ($i = 0; $i < $size; $i++) {
    $array[] = rand($min, $max);
}

function myInArray($needle, array $haystack, $strict = false)
{
    foreach ($haystack as $item) {
        if ($strict ? ($needle === $item) : ($needle == $item)) {
            return true;
        }
    }
    return false;
}

function myArrayUnique(array $array)
{
    $unique_array = array();
    foreach ($array as $key => $item) {
        if (!myInArray($item, $unique_array)) {
            $unique_array[$key] = $item;
        }
    }
    return $unique_array;
}

function myArrayUnique2(array &$array)
{
    $uniqueArray = array();
    $usedItems = array();

    foreach ($array as $key => $item) {
        if (empty($usedItems[$item])) {
            $uniqueArray[$key] = $item;
            $usedItems[$item] = true;
        }
    }

    return $uniqueArray;
}

$start = microtime(true);
$result = myArrayUnique($array);
$timeElapsedSecs = microtime(true) - $start;

echo "Test 1: {$timeElapsedSecs} sec \n";

$start = microtime(true);
$result = myArrayUnique2($array);
$timeElapsedSecs = microtime(true) - $start;

echo "Test 2: {$timeElapsedSecs} sec \n";

На моей системе результат был такой:
$ php test.php
Test 1: 10.178105831146 sec
Test 2: 0.10400199890137 sec

Т.е. ускорение примерно в 100 раз по сравнению с вашим вариантом. Примененные в моем варианте оптимизации вам уже указывали в первом комментарии.


Q:

Is it possible to convert DAX functions into a Measure so I can filter with a slicer?

I'm just getting my feet wet with DAX and the like, and I know the solution I'm looking for is probably very simple and elegent, but it's at the very edge of my knowledge.
I really hope you can help me out :)
The data I'm working with is a large list of claims.
The data gives a Timestamp when a 'Claim ID' is 'Ready for Review' and 'Complete'
Because the nature of the business, sometimes a claim goes back into 'Ready for Review' after it's been 'Complete'ed, so some 'Claim ID's can have multiple lines that are marked 'Ready for Review'.
Right now I have three DAX functions to calculate if a claim is currently 'Ready for Review'

Columns and such:
RFE State History is the table
Timestamp gives the date and time down to the second
Claim Id is the claim number
Status Label will either be "Ready for Review" or "Complete"

MaxDate: =
CALCULATE (
    MAX ( 'RFE State History'[Timestamp] ),
    FILTER (
        'RFE State History',
        'RFE State History'[Claim Id] = EARLIER ( 'RFE State History'[Claim Id] )
    )
)

This filters by claim number, then outputs the latest date of the lot.
IsLatest: =
IF('RFE State History'[Timestamp]='RFE State History'[MaxDate],"Latest")

When the MaxDate value equals the date on this line, output "Latest"
Ready for Review: =
IF (
    'RFE State History'[Status Label] = "Ready for Review"
        && 'RFE State History'[IsLatest] = "Latest",
    1
)

When the column IsLatest is "Latest", output "1"

I then use 'Redy for Review' in a Pivot Table to sum up how many claims are Ready to Review at that particular moment.
What I need to do from here:
I want to be able to use a Slicer to tell how many claims were Ready to Reiew on any particular day in the past (and seperately: in each hour of the day as well so we can track progress throughout the day).
After Googling about for a couple weeks I ran across these:
~Is it possible to use a slicer as a parameter to a DAX Summarize function?
~DAX Fridays! #93: MAXX | Fill down with DAX and Power Query (YouTube)
~This blog entry on SUMMARIZECOLUMNS
~This PowerBI Post on SUMMARIZECOLUMNS
Which leads me to believe I need to write a Measure that basically does the three DAX functions (MaxDate, IsLatest, and Ready for Review) all at the same time using FILTER and SUMMARIZECOLUMNS so they can be filtered with a Slicer.
Like I said up top there: I'm pretty sure the solution is really simple; I've tried my hand at adapting them to a Measure with no luck. I am only really starting in the DAX world, so I know there's a lot I don't know and don't have a proper grasp on quite yet.
I am really hoping you can help me out here by pointing me in the right direction.
Thanks in advance :)

A:

If I understand you correctly, you want to count the number of Ready for Review claims at a given day or hour you selected with a slicer?
If that is the case  you can can:

Create a new calculated table with the following code. You can find it right next to the button for a calculated column in the modelling menu
DateTime =
ADDCOLUMNS (
    CROSSJOIN (
        CALENDAR ( DATE ( 2000, 1, 1 ), DATE ( 2025, 12, 31 ) ),
        UNION (
            ROW ( "Time", TIME ( 1, 0, 0 ) ),
            ROW ( "Time", TIME ( 2, 0, 0 ) ),
            ROW ( "Time", TIME ( 3, 0, 0 ) ),
            ROW ( "Time", TIME ( 4, 0, 0 ) ),
            ROW ( "Time", TIME ( 5, 0, 0 ) ),
            ROW ( "Time", TIME ( 6, 0, 0 ) ),
            ROW ( "Time", TIME ( 7, 0, 0 ) ),
            ROW ( "Time", TIME ( 9, 0, 0 ) ),
            ROW ( "Time", TIME ( 10, 0, 0 ) ),
            ROW ( "Time", TIME ( 11, 0, 0 ) ),
            ROW ( "Time", TIME ( 12, 0, 0 ) ),
            ROW ( "Time", TIME ( 13, 0, 0 ) ),
            ROW ( "Time", TIME ( 14, 0, 0 ) ),
            ROW ( "Time", TIME ( 15, 0, 0 ) ),
            ROW ( "Time", TIME ( 16, 0, 0 ) ),
            ROW ( "Time", TIME ( 17, 0, 0 ) ),
            ROW ( "Time", TIME ( 18, 0, 0 ) ),
            ROW ( "Time", TIME ( 19, 0, 0 ) ),
            ROW ( "Time", TIME ( 20, 0, 0 ) ),
            ROW ( "Time", TIME ( 21, 0, 0 ) ),
            ROW ( "Time", TIME ( 22, 0, 0 ) ),
            ROW ( "Time", TIME ( 23, 0, 0 ) ),
            ROW ( "Time", TIME ( 24, 0, 0 ) )
        )
    ),
    "DateTime", [Date] + [Time],
    "Hour", HOUR ( [Time] )
)

Thanks for the answer in this post: https://community.powerbi.com/t5/Desktop/how-to-build-a-calendar-table-with-date-and-time/td-p/241728

Create a measure for you previous calculations
Ready for Review =
var _selectedPeriod = MAX ( DateTime[DateTime] ) // Grab DateTime from the selected value in DateTime. This can be a single value or the end of a period. Default is last available date in DateTime
RETURN
    COUNTX (
        'RFE State History' ,
        var _maxDate =
            CALCULATE(
                MAX ( 'RFE State History'[Timestamp] ) ,
                ALL ( 'RFE State History' ) ,
                'RFE State History'[Claim Id] = EARLIER( 'RFE State History'[Claim Id] ) ,
                'RFE State History'[Timestamp] <= _selectedPeriod
            )

        var _isLast =
            _maxDate = 'RFE State History'[Timestamp]

        RETURN
            IF( AND ( _isLast = TRUE() , 'RFE State History'[Status Label] = "Ready for Review" ) , 1 )
    )

Create a slicer using DateTime from your calendar table and have a visual with the above produced measure


Q:

Difference between console.log enabled verification

I have seen jquery-ui-1.8.11.js verify console.log functionality by doing
if (this.debug)
   console.log()

I have also seen people define an anonymous function that is a no-op for browsers with no console logging like IE7.
if(typeof console === "undefined") {
    console = { log: function() { } };
}

Is there a technical difference or are both functionally equivalent?

A:

In the first example you've given, this.debug will be a reference to a debug variable in the jQueryUI code. This debug variable will have been set elsewhere, possibly by checking whether console is defined, but also possibly with other settings.
In any case, the first example is specific to the application; if you want to do a generic check to see whether the console is available, you'll need to use the second technique. You don't have to define an empty console object as per the example, but doing it that way does mean that you won't have to do the if() condition every time you want to call console.log().
Having said all of that, I would counsel you strongly to avoid putting any code into production which contains calls to the console. The console should only be used for debugging purposes while you are working on the code. It should not be necessary in final release, and doing so can be a sign that either your code is unstable or you're unconfident of it, neither of which is a good sign if you're releasing the code for live use.
(libraries such as jQueryUI are an exception to this rule, as they need to provide functionality for developers to do debugging while writing code using their library)

A:

Both of those do something else. The first code suppresses logging messages unless a flag is set. The people who develop jQuery UI need logging when working on it, and turn it on. But people using the library don't want to have their console cluttered by log messages from libraries, so it's off by default. It lets you turn off logging even when the browser supports it – that regular users on IE7 don't get script errors is a (possibly intended) side effect.
The second code defines a dummy console.log(), so you can call the method without checking if it exists everywhere. It will not suppress logging on browsers where it's supported.


Q:

best practice: reportservers and sql servers

we have three SQL servers serving a variety of applications on different webservers.
Each application is using reporting services functionality.
The average load per server per month is about 40.000 reports, taking an average of 3.1 secs to deliver a report.
At this moment the the situation is as follows:

Application A has his database on SQLServer A and is using Reporting
Services on SQLServer A. (SQL 2008)
Application B has his database on    SQLServer B and is using
Reporting Services on SQLServer B. (SQL 2008R2)
Application C has his database on SQLServer C and is using
Reporting Services on SQLServer C.  (SQL 2008R2).

We have just bought a new server, runnning SQL 2012.
Would it be wise to move all reporting to the Reporting Server 2012?
My idea is that there would be a significant performance-gain. Also, There would be only one reporting server to manage. But is that so? Are there penalties when running reports on one server while the database feeding the reports is on another server? Is it a problem if the Reporting Services version is different then that of the database server?
I would like very much to hear your thoughts on this.
Performance and manageability are two key-components.
Greetings and thanks for thinking with me,
Henro

A:

Are you using the Enterprise Edition of SSRS 2012 (so that could take advantage of scale out via deploying parts of the SSRS implementation on different servers)?  Here's a SSRS 2012 feature list by edition.  Also, are you using any scheduled (i.e. snapshot or scheduled delivery) of reports to balance the load requests?


Q:

document.querySelectorAll select id of specific input

I have a table which has two separate checkbox inputs. When selecting the first input there is a cumulative amount which calculates. If you select the second checkbox, the function errors (because of the duplicate input).
Function
function updateTotals() {
    var sum = Array.prototype.reduce.call(document.querySelectorAll("input.check:checked"),(a,v) => a + parseFloat(v.dataset.totalAmount), 0);
    $('#checkedTotal').val(sum);
};

What I need to do is separate the inputs, maybe using a class. I cant seem to get the syntax, or may be barking up the wrong tree. Something like...
function updateTotals() {
    var sum = Array.prototype.reduce.call(document.querySelectorAll ('.input').check:checked,(a,v) => a + parseFloat(v.dataset.totalAmount), 0);
    $('#checkedTotal').val(sum);
};

I would add this as an jsfiddle example, but the table is in a Salesforce Visualforce Page, using apex fields.
Thanks in advance
UPDATE
Added HTML

<form id="j_id0:j_id2" name="j_id0:j_id2" method="post">
<input type="hidden" name="j_id0:j_id2" value="j_id0:j_id2">

    <input disabled="disabled" id="checkedTotal" name="amount" placeholder="Selected Amount" step=".02" type="number">

                Select
                Date
                Type
                Order
                Amount
                id
                Select2

                        <input id="j_id0:j_id2:j_id4:0:inputId" type="checkbox" name="j_id0:j_id2:j_id4:0:inputId" class="check" onchange="updateTotals();" style="font-size:26px;" data-total-amount="458.00">

                    19/04/2018

                    Invoice

                        00006648

                    $458.00
                    8015D000000CsiH
                    <input type="checkbox" name="j_id0:j_id2:j_id4:0:j_id20" class="check" style="font-size:26px;">

                        <input id="j_id0:j_id2:j_id4:1:inputId" type="checkbox" name="j_id0:j_id2:j_id4:1:inputId" class="check" onchange="updateTotals();" style="font-size:26px;" data-total-amount="200.00">

                    21/06/2018

                    Invoice

                        00006849

                    $200.00
                    8015D000000DEuB
                    <input type="checkbox" name="j_id0:j_id2:j_id4:1:j_id20" class="check" style="font-size:26px;">

                        <input id="j_id0:j_id2:j_id4:2:inputId" type="checkbox" name="j_id0:j_id2:j_id4:2:inputId" class="check" onchange="updateTotals();" style="font-size:26px;" data-total-amount="500.00">

                        22/06/2018

                    Credit

                        00006852

                    $500.00
                    8015D000000DHKW
                    <input type="checkbox" name="j_id0:j_id2:j_id4:2:j_id20" class="check" style="font-size:26px;">

</form>

A:

Add class first to first checkbox in
 and add class second to second checkbox in
.
updateTotals only query checkbox which has class first to avoid second.

function updateTotals() {
    var sum = Array.prototype.reduce.call(document.querySelectorAll("input.check.first:checked"),(a,v) => a + parseFloat(v.dataset.totalAmount), 0);
    $('#checkedTotal').val(sum);
};

<form id="j_id0:j_id2" name="j_id0:j_id2" method="post">
<input type="hidden" name="j_id0:j_id2" value="j_id0:j_id2">

    <input disabled="disabled" id="checkedTotal" name="amount" placeholder="Selected Amount" step=".02" type="number">

                Select
                Date
                Type
                Order
                Amount
                id
                Select2

                        <input id="j_id0:j_id2:j_id4:0:inputId" type="checkbox" name="j_id0:j_id2:j_id4:0:inputId" class="check first" onchange="updateTotals();" style="font-size:26px;" data-total-amount="458.00">

                    19/04/2018

                    Invoice

                        00006648

                    $458.00
                    8015D000000CsiH
                    <input type="checkbox" name="j_id0:j_id2:j_id4:0:j_id20" class="check second" style="font-size:26px;">

                        <input id="j_id0:j_id2:j_id4:1:inputId" type="checkbox" name="j_id0:j_id2:j_id4:1:inputId" class="check first" onchange="updateTotals();" style="font-size:26px;" data-total-amount="200.00">

                    21/06/2018

                    Invoice

                        00006849

                    $200.00
                    8015D000000DEuB
                    <input type="checkbox" name="j_id0:j_id2:j_id4:1:j_id20" class="check second" style="font-size:26px;">

                        <input id="j_id0:j_id2:j_id4:2:inputId" type="checkbox" name="j_id0:j_id2:j_id4:2:inputId" class="check first" onchange="updateTotals();" style="font-size:26px;" data-total-amount="500.00">

                        22/06/2018

                    Credit

                        00006852

                    $500.00
                    8015D000000DHKW
                    <input type="checkbox" name="j_id0:j_id2:j_id4:2:j_id20" class="check second" style="font-size:26px;">

</form>


Q:

Is there popState to back browser history stack in AMP?

Is there Any way to back browser history when use AMP.pushState()?
Is the AMP.popState() (or window.history.back()) function implemented in AMP project?

A:

According to AMP document AMP.goBack is a top-level action that navigates back in history.

Note that it has some limitations: #5225


Q:

Why is freedom obscure for Arendt? How does she prove or illustrate such obscurity?

In her article "What is freedom" she says "The reason for this obscurity is that the phenomenon of freedom does not appear in the realm of thought at all, that neither freedom nor its opposite is experienced in the dialogue between me and myself..." what does this mean?

A:

See Action, Freedom, and Plurality in Hannah Arendt:

or Arendt, action is one of the fundamental categories of the human condition and constitutes the highest realization of the vita activa. [...] The two central features of action are freedom and plurality. By freedom Arendt does not mean the ability to choose among a set of possible alternatives (the freedom of choice so dear to the liberal tradition) [emphasis added] or the faculty of liberum arbitrium which, according to Christian doctrine, was given to us by God. Rather, by freedom Arendt means the capacity to begin, to start something new, to do the unexpected, with which all human beings are endowed by virtue of being born. Action as the realization of freedom is therefore rooted in natality, in the fact that each birth represents a new beginning and the introduction of novelty in the world.

Thus, freedom is not grounded in rationality: "freedom does not appear in the realm of thought".
It is something "deep", grounded in our inner original self.


Q:

ZF2 Form, how to add a custom validator

How can i add a custom validator to a ZF2 form?
I would like to add a custom validator to a zf2 form element or the form class itself to validate multiple elements against each other.
use Zend\Form\Form;
class MyForm extends Form {

    public function init()
    {
        // Add some elements
        $this->add(
            $this->getFormFactory()->create(...);
        }

        // How can i add a custom validator here to the form or element?
    }

}

My Current Solution
is very simpe but effective, the form class or the fieldset has has to implement the interface Zend\InputFilter\InputFilterProviderInterface
Now i can add something like this:
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use \PayrollAccountingValidator;
class MyForm extends Form implements InputFilterProviderInterface {

    public function init()
    {
        $this->getFormFactory()->create(
            array(
                    'name' => 'salary',
                    'type' => 'Zend\Form\Element\Number',
                    'attributes' => array(
                            'min' => 0,
                            'step' => 1
                    ),
                    'options' => array(
                            'label' => _('Salary?')
                    )
            ));
    }

    public function getInputFilterSpecification ()
    {
        return array(
                'salary' => array(
                        'validators' => array(
                                new PayrollAccountingValidator($this)
                        )
                )
        );
    }

}

A:

What I would do:

Create the form
Create a input filter with a dependency of the validator
Add the validator to the field in the filter
Set the filter to the form in a factory.

Example
Form:
Here we merely add the elements to the form.
class SomeForm extends Form {

   public function __construct() {
        parent::__construct('someform');

        $this->add(array(
            'type' => 'Zend\Form\Element\Textarea',
            'name' => 'somelement',
            'options' => array(
                'label' => 'Message',
            )
        ));
    }
}

Filter:
Here we create the filter for the releveant elements in the above form. We add the validator passed in at instantiation when creating the input filter:
namespace SomeModule\Form;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class SomeFormFilter implements InputFilterAwareInterface {

    protected $customValidator;

    protected $inputFilter;

    public function __construct($customValidator) {
        $this->customValidator = $customValidator;
    }

    public function setInputFilter(InputFilterInterface $inputFilter) {
        throw new \Exception("Not used");
    }

    public function getInputFilter() {
        if (!$this->inputFilter) {

            $inputFilter = new InputFilter();
            $factory = new InputFactory();

            $inputFilter->add(
                $factory->createInput(
                    array(
                        'name' => 'somelement',
                        'required' => true,
                        'filters' => array(array(
                                'name' => 'StringTrim')
                        ),
                        'validators' => array(
                            $this->customValidator
                        ),
                    )
                )
            );

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

Module.php
We can now create a factory for the form to manage the filters validator dependency and apply the filter to the form:
public function getServiceConfig() {
     return array(
        'factories' => array(
            'someForm' => function($sm) {
                $form = new SomeForm();
                $validator = new CustomValidator() // or $validator = $sm->get('CustomValidator');
                $formFilter = new SomeFormFilter($validator);
                $form->setInputFilter($formFilter->getInputFilter());
                return $form;
            },
        ),
    );
}

You will obviosly need to make sure you use the correct namespaces in your Module.php or provide the FQCN's.
Now you can get this form, fully configured in you controller with one line of code:
$form = $this->getServiceLocator()->get('SomeForm');
If you have any more questions feel free to ask.


Q:

A function with variable return type

I want to be able to make a function GetInput() which takes a class as a parameter, and returns whatever is input. The function definition would look like this:
GetInput(class type) {
    if (type == string) {
        string stringInput;
        cin >> stringInput;
        return stringInput;
    }
    else if (type == int) {
        int intInput;
        cin >> intInput;
        return intInput;
    }
    else {
        return NULL;
    }
}

I don't know what to write for the return type of the function because it can be either string or int. How can I make this function work?

A:

You can't make it an actual argument, but you can do something similar by creating a function template (also called a template function):
template<class T>
T GetInput() {
    T input;
    cin >> input;
    return input;
}

You can use it like this:
string stringInput = getInput<string>();
int intInput = getInput<int>();

getInput<string> and getInput<int> are considered different functions, generated by the compiler - hence why this is called a template.
Note - if you're using multiple files, the whole template definition must go in a header file and not the source file, because the compiler needs to see the whole template in order to generate functions from it.


Q:

Print Smali values to logcat

In the example code below, how can I add a command to print the values of v0, v1 etc to logcat?
const v1, 0x7f05002e

iget-object v2, p0, Lcom/company/myapp/MainActivity;->d:Lcom/company/myapp/f;

invoke-virtual {v2}, Lcom/company/myapp/f;->getPanelModel()Lcom/company/myapp/h;

move-result-object v2

invoke-virtual {v2}, Lcom/company/myapp/h;->b()I

move-result v2

invoke-virtual {v0, v1, v2}, Lcom/company/e/k;->a(II)V

iget-object v0, p0, Lcom/company/myapp/MainActivity;->c:Lcom/company/e/k;

A:

Add at the end:
const-string v8, "log-tag"

invoke-static {v1}, Ljava/lang/String;->valueOf(I)Ljava/lang/String;
move-result-object v9

invoke-static {v8, v9}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

From your sample v1 is integer so the function String;->valueOf(I) is used to convert it to String before using log. Also Log;->d outputs at debug log level; possibly another level is needed.


Q:

Использование Google Play Services в Qt

Доброго времени суток.
Столкнулся со следующей проблемой: необходимо взаимодействие с сервисами Google Play из-под Qt приложения. Ясное дело, код взаимодействия расположен в Java файле, а Qt вызывает методы этого файла.
Добавил библиотеку Play Services как указано тут, всё собирается нормально, но при вызове методов из библиотеки получаем вот что:
W/dalvikvm(28101): Unable to resolve superclass of Lcom/google/android/gms/common/api/g; (169)
W/dalvikvm(28101): Link of class 'Lcom/google/android/gms/common/api/g;' failed
I/dalvikvm(28101): Could not find method com.google.android.gms.common.api.g.a, referenced from method com.google.android.gms.common.api.GoogleApiClient$Builder.gI
W/dalvikvm(28101): VFY: unable to resolve static method 3384: Lcom/google/android/gms/common/api/g;.a (Landroid/support/v4/app/FragmentActivity;)Lcom/google/android/gms/common/api/g;

и ещё кучу замечательных ошибок...
Так вот вопрос: что пошло не так и как правильно добавить эту библиотеку в проект Qt?

A:

Удалось избавится от ошибок добавлением библиотеки android support в проект.
Для этого просто скопировал её из android-sdk\extras\android\support\v4 в PROJECT_DIR\ANDROID_PACKAGE_SOURCE_DIR\libs.


Q:

Get Timestamp after Insert/Update

In azure table storage.  Is there a way to get the new timestamp value after an update or insert.  I am writing a 3-phase commit protocol to get table storage to support distributed transactions , and it involes multiple writes to the same entity.  So the operation order goes like this, Read Entity, Write Entity (Lock Item), Write Entity (Commit new values).  I would like to get the new timestamp after the lock item operation so I don't have to unecessarily read the item again before doing the commit new value operation.  So does any one know how to efficiently get the new timestamp value after a savechanges operation?

A:

I don't think you need to do anything special/extra. When you read your entity you will get an Etag for it. When you save that entity (setting someLock=true) that save will only succeed if nobody else have updated the entity since your read. Hence you know you have the lock. And then you can do your second write as you please.