Q:

anyone know where the git-docker glue is at?

SHORT:
i want something to make my git and docker hookup easier. what tools are there?
LONG:
you can use jenkins to watch a git repo. jenkins runs your build script and your test suite and then does a docker push.
but after the push nothing happens! you pull manually.
on github you can use travis in a similar manner (if travis now supports docker). for those not in the know, think of travis as "jenkins online" but after doing its thing it destroys the build environment - any artifacts etc must be sent somewhere else prior to destruction.
BUT I still need to pull manually.
finally, you can do docker automated builds. However, now I've lost control since even if my build fails the docker build still kicks off!
I think in an automated build I can set webhooks to do something after a new image is received by docker hub but this is now getting very long winded!
is there a simpler approach to tie git and docker together without all the palava?

A:

As your post is rather light on details, only a generic answer can be provided. Travis supports several third party destinations for deployments. You could copy the relevant docker image to a provider of your choice. As Travis also supports before_deploy and after_deploy stages; you could utilize those to put in shell scripts to reload the docker images.
Needless to say, the deploy stage only kicks off when all commands completed successfully.
For the details, have a look at the the following link:
https://docs.travis-ci.com/user/deployment/


Q:

missing shared library in ldd

I compiled Apache httpd on CentOS 6.x. Works fine there.
Then I moved the binary files to CentOS 7. I needed to install some missing libraries and now works fine there.
Then I moved the binary files to Archlinux. As I expected it did not started directly:
httpd: symbol lookup error: /software_pack/httpd-2.2.25/lib/libapr-1.so.0: undefined symbol: dlopen

However, if I do ldd /software_pack/httpd-2.2.25/lib/libapr-1.so.0 it gives different results on CentOS and Archlinux. On Archlinux, libdl.so is not shown at all?
Where from CentOS knows the file needs libdl.so.2 ?
CentOS 6.x:
# ls -la /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0
lrwxrwxrwx 1 root root 21 Jul 30 09:47 /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0 -> libaprutil-1.so.0.5.2
# ldd /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0.5.2
        linux-vdso.so.1 =>  (0x00007fffec400000)
        libexpat.so.0 => /software_pack/httpd-2.2.25/lib/libexpat.so.0 (0x00007f5ec94d8000)
        libapr-1.so.0 => /software_pack/httpd-2.2.25/lib/libapr-1.so.0 (0x00007f5ec92a8000)
        librt.so.1 => /lib64/librt.so.1 (0x00007f5ec9098000)
        libcrypt.so.1 => /lib64/libcrypt.so.1 (0x00007f5ec8e60000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f5ec8c40000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f5ec88a8000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f5ec9928000)
        libfreebl3.so => /lib64/libfreebl3.so (0x00007f5ec8630000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f5ec8428000)   <<<<<<<< Missing in arch

On Archlinux:
# ls -la /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0
lrwxrwxrwx 1 root root 21 Jul 30 10:47 /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0 -> libaprutil-1.so.0.5.2
# ldd /software_pack/httpd-2.2.25/lib/libaprutil-1.so.0.5.2
        linux-vdso.so.1 (0x00007fff7cdd3000)
        libexpat.so.0 => /software_pack/httpd-2.2.25/lib/libexpat.so.0 (0x00007f5aef4e7000)
        libapr-1.so.0 => /software_pack/httpd-2.2.25/lib/libapr-1.so.0 (0x00007f5aef2ba000)
        librt.so.1 => /usr/lib/librt.so.1 (0x00007f5aef084000)
        libcrypt.so.1 => /usr/lib/libcrypt.so.1 (0x00007f5aeee4b000)
        libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007f5aeec2d000)
        libc.so.6 => /usr/lib/libc.so.6 (0x00007f5aee87f000)
        /usr/lib64/ld-linux-x86-64.so.2 (0x00007f5aef934000)

A:

dlopen is normally provided by libdl.so.2. On Arch Linux libdl.so.2 is provided by glibc package. It would be very strange if you didn't have glibc installed, but anyway, check if you have libdl.so.2 on your system.
You can also use readelf command to output a symbol table for a shared object and check if particular symbol is exported:
readelf -Ws /usr/lib/libdl.so.2

Some info on why ldd output for the same binary may differ on different systems can be found here:
https://stackoverflow.com/questions/12714219/ldd-different-output-same-binary-different-distros


Q:

Questions that ask for a specific type of answer

I just wanted to clarify if it's okay to ask questions on Stackoverflow that specifically asked that the answer meet certain requirements regardless of what anybody elses opinion of that would be? And if the answer didn't meet those requirements would I still have to accept it?
For example:
In wordpress.stackexchange.com if I asked a question and specified I wanted a coded solution rather than a solution provided by 3rd party plugin, is that acceptable? Or should I still accept the plugin solution if someone chose to ignore it.

A:

Of course that is acceptable. Those requirements are often the reason for the question.
Not the same as saying your requirements will make sense to people, but still...
and of course you don't need to accept any answer.
However, I would just recommend being open to suggestions. Sometimes people will suggest another way around your requirements.
DISCLAIMER: This answer is given in general, with no knowledge of any specific question/answer.

A:

You can ask for whatever kind of solution you want, and you can make a choice on your own criteria when deciding which answer, if any, you want to accept.
On the other hand the people answering the questions can, as long as its on topic, post any kind of answer they want and so if someone's question is asking for a less than optimal solution then they can try and explain why the scenario posed in such a question is flawed and try to lead the discussion towards a non-flawed solution.


Q:

C# - Getting all enums value by attribute

I have this following enum :
public enum KodEnum
{
    [EnumType(EnumType = "Task")]
    TaskTab,
    [EnumType(EnumType = "Task")]
    TaskReason,
    [EnumType(EnumType = "Action")]
    ActionTab,
    [EnumType(EnumType = "Action")]
    ActionReason
}

public class EnumTypeAttribute : Attribute
{
    public string EnumType { get; set; }
}

And I want to get a list of all the enums that have the EnumType of "Task".
How could I do that?

A:

Something like this should get you on the way...
var enumValues = (from member in typeof(KodEnum).GetFields()
                  let att = member.GetCustomAttributes(false)
                                  .OfType<EnumTypeAttribute>()
                                  .FirstOrDefault()
                  where att != null && att.EnumType == "Task"
                  select member.GetValue(null))
                 .Cast<KodEnum>()
                 .ToList();

If you want the int value, then just cast it:
var enumValues = (from member in typeof(KodEnum).GetFields()
                  let att = member.GetCustomAttributes(false)
                                  .OfType<EnumTypeAttribute>()
                                  .FirstOrDefault()
                  where att != null && att.EnumType == "Task"
                  select (int)member.GetValue(null))
                 .ToList();

And all-lambda solution:
        var enumValues = typeof(KodEnum)
            .GetFields()
            .Select(x => new
                {
                    att = x.GetCustomAttributes(false)
                             .OfType<EnumTypeAttribute>()
                             .FirstOrDefault(),
                    member = x
                })
            .Where(x => x.att != null && x.att.EnumType == "Task")
            .Select(x => (int)x.member.GetValue(null))
            .ToList();


Q:

Adding a blank space in an XML attrib with lxml in Python

from lxml import etree

html = etree.Element("html")
body = etree.SubElement(html, "body")
body.text = "TEXT"
body.set("p style", "color:red")
print(etree.tostring(html))

Gives me the error: ValueError: Invalid attribute name u'p style'

A:

You can't have an attribute with a space in it in XML, which is what lxml and etree are for. The XML specification states what a valid attribute name is here.
If you are trying to achieve this:
TEXT
You can't do that in XML. You can do something similar in HTML: empty attributes. See the HTML5 specification for details. But you wouldn't use the kind of code written above to get that result.

If you are trying to get the following result (which seems more likely):

TEXT

Then it is very easy.
from lxml import etree

html = etree.Element("html")
body = etree.SubElement(html, "body")
p = etree.subElement(body, "p")
p.text = "TEXT"
p.set("style", "color:red")
print(etree.tostring(html))


Q:

What is the appropriate Data URI to use for 0-byte content?

I have a method that generates a data URI from a byte array. In the event the input byte array is empty, what is the appropriate thing for the method to do? Here are the options I see:

return data:,
return an empty String
throw an Exception

By my read, RFC 2397 doesn't explicitly address the notion of empty data.

A:

RFC 2397 explicitly allows empty data. Let's look at the relevant parts of the grammar:
dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
...
data       := *urlchar

The * quantifier means zero or more repetitions, the square brackets contain optional parts. Therefore the shortest data-URL is indeed data:,. In your context, you'll probably use data:text/plain;base64, or something like that instead.


Q:

In C, will a literal string address always be greater than any allocated string address?

I'm attempting to differentiate literal strings from allocated strings so I don't accidentally try to free() literal strings, which would cause a segfault.
The reason I might try to free() literal strings involve a strcat() wrapper that can be embedded thusly:  strcatex("My name ", strcatex("is ", strMyName));
Regardless of the reason, consider:
void* mallocex(int intBytes)
{
    void* newPtr;

    newPtr = malloc(intBytes);

    if(newPtr == 0)
        return 0;
    else if(newPtr > maxPointer)
        maxPointer = newPtr;

    return newPtr;
}

and
int SafeFree(void **ptr)
{
    if((unsigned long) ptr > (unsigned long) maxPointer)
        return 0;
    else
        free(*ptr);

    return 1;
}

example use:
char *newString;
newString = (char*) mallocex(12);

strcpy(newString, "Example one");

SafeFree(&newString);
SafeFree("Example two");

Will this always work, regardless of how large my heap becomes?

A:

There is no such guarantee don't rely on it.
A string literal is allocated memory somewhere in the read-only implementation defined region there is no way to know what that will be in a portable manner and hence you should not make any assumptions about it.


Q:

Using math-mode in pgfplots legend setting (Greek symbol \pi)

As I am a begineer in Latex, I cannot use greek symbol \pi in math-mode of pgfplots. I always receive an error.
\documentclass[12pt,english]{article}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents*}{example.csv}
t,$\pi$,$y$
1972,1.65,1.28
1973,3.14,1.56
1974,3.28,2.24
1975,3.04,2.50
\end{filecontents*}
\clearpage
\begin{document}
\begin{figure}[H]
\centering
\resizebox{0.75\textwidth}{.45\textwidth}{%
\begin{tikzpicture}
\begin{axis}[legend entries={$\pi$, $y$},
legend pos=north west,xlabel=Years,
    ylabel=Log]
\addplot table [x=t, y=$\pi$, col sep=comma] {example.csv};
\addplot table [x=t, y=$poil_{t}^{d}$, col sep=comma] {example.csv};
\end{axis}
\end{tikzpicture}
}
\end{figure}
\end{document}

A:

The error isn't raised due to the \pi in legend entries, but by the \pi in the CSV file header. Simply not using (LaTeX) commands in the header line will result in a working example.
% used PGFPlots v1.14
\documentclass[border=5pt]{standalone}
\usepackage{filecontents}
    \begin{filecontents*}{example.csv}
        % don't use any (LaTeX) commands in the header row
        % simply replacing `pi' by `\pi' here (and commenting the first
        % `\addplot' command) will raise an error
        t,pi,y
        1972,1.65,1.28
        1973,3.14,1.56
        1974,3.28,2.24
        1975,3.04,2.50
    \end{filecontents*}
\usepackage{pgfplots}
    % use this `compat' level or higher to make use of the "advanced"
    % axis label positioning
    \pgfplotsset{compat=1.3}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        % using `$\pi$' here is not a problem
        legend entries={$\pi$, $y$},
        legend pos=north west,
        xlabel=Years,
        ylabel=Log,
        % don't show half years ...
        xtick distance=1,
        xticklabel style={
            % ... and don't use a comma as thousand separator for the years
            /pgf/number format/set thousands separator={},
        },
%        % if you want to show additional ticks without labels ...
%        minor x tick num=1,
        table/col sep=comma,
    ]
        \addplot table [x=t, y=pi] {example.csv};
        \addplot table [x=t, y=y]  {example.csv};
    \end{axis}
\end{tikzpicture}
\end{document}


Q:

R zoo package: na.approx changing length of vector when NA are in the beginning

The zoo package has the function na.approx (or na.spline) which replaces NAs in your data with either approx or spline.
One potential argument is maxgap which gives the biggest gap to fill. This works fine, except that if the NAs are in the beginning of the vector, the function changes the length of the vector.
For example:
require(zoo)
x <- 1:20 + rnorm(20)
x1 <- x
x1[5] <- x1[6] <- NaN
length(na.approx(x1, maxgap = 1)) == length(x) # TRUE
x2 <- x
x2[1] <- x2[2] <- NaN
length(na.approx(x2, maxgap = 1)) == length(x) # FALSE

This is problematic when using this function with data frames. For example:
require(dplyr)
df1 <- tibble(A = 1:20, B = x1)
df1 %>%
  mutate(B_fill = na.approx(B, maxgap = 1))

df2 <- tibble(A = 1:20, B = x2)
df2 %>%
  mutate(B_fill = na.approx(B, maxgap = 1))
# Error: Column `B_fill` must be length 20 (the number of rows) or one, not 18

A:

As I was asking this question, I found the answer, just change the na.rm argument.
df2 %>%
  mutate(B_fill = na.approx(B, maxgap = 1, na.rm = FALSE))


Q:

Users create script from CSV file

Im trying to get this script working but what I get is:

14: Syntax error: "(" unexpected (expecting "fi").

Hope you guys can solve my problem because it's been a while Im looking into the error...
If you need the .csv file let me know.
Here is the script:
#!/bin/bash
filein="proyecto3.csv"
IFS=$'\n'
if [ ! -f "$filein" ]
then
echo "Cannot find file $filein"
else
  groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
  fullnames=(`cut -d: -f 1 "$filein"`)
  userid=(`cut -d: -f 2 "$filein"`)
  usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
fi
for group in ${groups[*]}
do
grep -q "^$group" /etc/group ; let x=$?
if [ $x -eq 1 ]
then
groupadd "$group"
fi
done
  x=0
  created=0
for user in ${usernames[*]}
do
useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
if [ $? -eq 0 ]
then
let created=$created+1
fi
echo "${usernames[$x]}" | passwd --stdin "$user" > /dev/null
echo "Complete. $created accounts have been created."
fi

A:

Simply remove the very last line in your script (also it helps to do a proper indentation to see your errors). Also you forgot to end your last for loop with a done:
#!/bin/bash
filein="proyecto3.csv"
IFS=$'\n'

if [ ! -f "$filein" ]
then
    echo "Cannot find file $filein"
else
    groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
    fullnames=(`cut -d: -f 1 "$filein"`)
    userid=(`cut -d: -f 2 "$filein"`)
    usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
fi

for group in ${groups[*]}
do
    grep -q "^$group" /etc/group ; let x=$?
    if [ $x -eq 1 ]
    then
        groupadd "$group"
    fi
done

x=0 #not sure why you reset x here to zero !?
created=0

for user in ${usernames[*]}
do
    useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
    if [ $? -eq 0 ]
    then
        let created=$created+1
    fi
done

echo "${usernames[$x]}" | passwd --stdin "$user" > /dev/null
echo "Complete. $created accounts have been created."

Up to that I can really advise you to use something like shellcheck on your script ( you can get it from the normal Ubuntu universe repositories).
sudo apt update
sudo apt install shellcheck

It outputs a lot more you can do better on your script:
$ shellcheck test.sh

In test.sh line 9:
    groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
            ^-- SC2006: Use $(..) instead of legacy `..`.

In test.sh line 10:
    fullnames=(`cut -d: -f 1 "$filein"`)
               ^-- SC2006: Use $(..) instead of legacy `..`.

In test.sh line 11:
    userid=(`cut -d: -f 2 "$filein"`)
    ^-- SC2034: userid appears unused. Verify it or export it.
            ^-- SC2006: Use $(..) instead of legacy `..`.

In test.sh line 12:
    usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
               ^-- SC2006: Use $(..) instead of legacy `..`.
                                            ^-- SC2060: Quote parameters to tr to prevent glob expansion.
                                                  ^-- SC2060: Quote parameters to tr to prevent glob expansion.

In test.sh line 29:
    useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
                  ^-- SC2086: Double quote to prevent globbing and word splitting.
                                                      ^-- SC2086: Double quote to prevent globbing and word splitting.

In test.sh line 30:
    if [ $? -eq 0 ]
         ^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

Alternatively, use the online shellcheck tool...


Q:

Converting bits of a byte to single bits and back

I have the struct below
typedef struct fpButtons {

  /**     BYTE 0         **/
  uint8_t       button_1:1;
  uint8_t       button_2:1;
  uint8_t       button_3:1;
  uint8_t       button_4:1;
  uint8_t       button_5:1;
  uint8_t       button_6:1;
  uint8_t       button_7:1;
  uint8_t       button_8:1;

  /** And BYTE 2 which I didn't paste to save SO's space lol **/
  // button_9:1 to button_16:1
} FP_BUTTONS;

And this function that gives an unsigned integer, which its bits should build the struct above
void FP_UpdateData(FP_BUTTONS *data, uint8_t b1, uint8_t b2)
{
  data->button_1 = (b1 & ( 1 << 1 )) >> 1;
  data->button_2 = (b1 & ( 1 << 2 )) >> 2;
  data->button_3 = (b1 & ( 1 << 3 )) >> 3;
  data->button_4 = (b1 & ( 1 << 4 )) >> 4;
  data->button_5 = (b1 & ( 1 << 5 )) >> 5;
  data->button_6 = (b1 & ( 1 << 6 )) >> 6;
  data->button_7 = (b1 & ( 1 << 7 )) >> 7;
  data->button_8 = (b1 & ( 1 << 8 )) >> 8;

  //Do the same thing for button 9 to 16

}

Now after storing, I have to send it somewhere else :
void APP_Send(){

  uint8_t packet[2];

  packet[0] = *((uint8_t*) &FP_BUTTONS_Data);
  packet[1] = *(((uint8_t*) &FP_BUTTONS_Data)+1);

  //Send stuff away.....
}

Despite all the effort, none of the codes above seems to work. I am doing this on an embedded processor and its really hard to debug. I wonder if some C-Guru guys can tell me what can be wrong with this codes?

A:

Bits are 0-indexed, but you coded the shifts as if bits were 1-indexed instead.  You have to use 0 through 7 for the shifts on a uint8_t.
Also, the right-shifts can be removed.
Try this:
void FP_UpdateData(FP_BUTTONS *data, uint8_t b1, uint8_t b2)
{
  data->button_1 = (b1 & ( 1 << 0 )) != 0;
  data->button_2 = (b1 & ( 1 << 1 )) != 0;
  data->button_3 = (b1 & ( 1 << 2 )) != 0;
  data->button_4 = (b1 & ( 1 << 3 )) != 0;
  data->button_5 = (b1 & ( 1 << 4 )) != 0;
  data->button_6 = (b1 & ( 1 << 5 )) != 0;
  data->button_7 = (b1 & ( 1 << 6 )) != 0;
  data->button_8 = (b1 & ( 1 << 7 )) != 0;

  //Do the same thing for button 9 to 16
}

void APP_Send()
{
  uint8_t packet[2];

  uint8_t *data = (uint8_t*) &FP_BUTTONS_Data;
  packet[0] = data[0];
  packet[1] = data[1];

  //Send stuff away.....
}

With that said, all of this manual shifting is unnecessary if you wrap the struct data in unions:
typedef struct fpButtons {

  /**     BYTE 0         **/
  union {
    struct {
      uint8_t       button_1:1;
      uint8_t       button_2:1;
      uint8_t       button_3:1;
      uint8_t       button_4:1;
      uint8_t       button_5:1;
      uint8_t       button_6:1;
      uint8_t       button_7:1;
      uint8_t       button_8:1;
    };
    uint8_t         rawbuttons_1;
  };

  /**     BYTE 1         **/
  union {
    struct {
      uint8_t       button_9:1;
      uint8_t       button_10:1;
      uint8_t       button_11:1;
      uint8_t       button_12:1;
      uint8_t       button_13:1;
      uint8_t       button_14:1;
      uint8_t       button_15:1;
      uint8_t       button_16:1;
    };
    uint8_t         rawbuttons_2;
  };

} FP_BUTTONS;

void FP_UpdateData(FP_BUTTONS *data, uint8_t b1, uint8_t b2)
{
  data->rawbuttons_1 = b1;
  data->rawbuttons_2 = b2;
}

void APP_Send()
{
  uint8_t packet[2];

  packet[0] = FP_BUTTONS_Data.rawbuttons_1;
  packet[1] = FP_BUTTONS_Data.rawbuttons_2;

  //Send stuff away.....
}


Q:

Enable Gzip compression in Dropwizard

i have a REST service , I am using dropwizard 0.6.2.
The pom code is as follow
    <dependency>
        <groupId>com.yammer.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>0.6.2</version>
    </dependency>

I am using a config.yml file.
The code is as follows to start the service
new BrAnalyticsNoSQLControllerService().run(new String[] { "server","src\\main\\java\\config.yml"});

as per the dropwizard documentation i tried to add following code in config.yml to enable gzip
gzip:
  enabled: true
  minimumEntitySize: 256B
  bufferSize: 8KB

But I am getting following error when i try to run my service,

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "gzip" (class com.Breezom.BrAnalyticsNoSQLController.REST.Config.BrAnalyticsNoSQLController), not marked as ignorable (7 known properties: , "mongodb", "mongoport", "loggingConfiguration", "http", "mongohost", "httpConfiguration", "logging"])
   at [Source: N/A; line: -1, column: -1] (through reference chain: com.Breezom.BrAnalyticsNoSQLController.REST.Config.BrAnalyticsNoSQLController["gzip"])
      at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
      at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:579)
      at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:672)
      at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:906)
      at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:328)
      at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
      at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:2765)
      at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1478)
      at com.yammer.dropwizard.config.ConfigurationFactory.build(ConfigurationFactory.java:63)
      at com.yammer.dropwizard.config.ConfigurationFactory.build(ConfigurationFactory.java:48)
      at com.yammer.dropwizard.cli.ConfiguredCommand.parseConfiguration(ConfiguredCommand.java:83)
      at com.yammer.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:51)
      at com.yammer.dropwizard.cli.Cli.run(Cli.java:53)
      at com.yammer.dropwizard.Service.run(Service.java:61)
      at com.Breezom.BrAnalyticsNoSQLController.REST.Service.BrAnalyticsNoSQLControllerService.main(BrAnalyticsNoSQLControllerService.java:162)

I am unable to figure out what the problem is.
Thanks in advance!!

A:

Try changing your YAML to include the http: section like this:
http:
  gzip:
    enabled: true
    minimumEntitySize: 256B
    bufferSize: 8KB


Q:

page is not showing as expected in Wordpress page option

Wanted to show traditional page layout for word press.
If i clicked edit page option then layout looks very weird. Please find the link below

Please suggest. how to switch to traditional look and feel?

A:

That's the new Gutenberg Editor you are seeing which came with WP version 5.0. To avoid it, you can install the "Classic Editor" plugin, which will bring back the "old" editor (i.e. TinyMCE)


Q:

The last digit of pi (in terms of Banach limits)

Let $\phi : l^\infty \to \mathbb C$ be a Banach limit, and define the sequence $\{x_k\}_{k\geq 0}$ to be the digits in the 10-base decimal expansion of $\pi$. Note that
$$\{x_k\}_{k\geq 0} \in l^\infty$$
and so we can talk about $\phi(\{x_k\}_{k\geq 0})$.
What it is? Note that Banach limits don't have to be unique.
Now consider the real number $\sqrt 2$. What is its last number? Finally, consider any element $x\in \mathbb R$. Can we say about the last digit of $x$, in the sense of Banach limits as considered above?

A:

Concerning last question about general $x\in\mathbb{R}$ and concerning the twice upvoted comment (under the original question)  that claims the limit is 4.5 for almost all $x$:
I think the opposite is true (see proof below): almost all (in the sense of the Lebesgue measure) real numbers do not have a unique Banach limit. Unless $\pi$ is an exception to this (and I don't know whether it is), your first question does not have a well-defined answer: The 'last digit' of $\pi$ is different for different choices of the Banach limit $\phi$.
Proof of claim: According to a theorem of Lorentz, a sequence $(x_k)_{k=0}^{\infty}$ has a unique Banach limit $L\in\mathbb{R}$ if and only if its averages $\overline{x}_{n,p}:=\frac{x_n+\dots+x_{n+p-1}}{p}$ converge to $L$ as $p\to\infty$, uniformly in $n$. In formulas $\forall \epsilon>0: \exists p_0\in\mathbb{N}: \forall p\geq p_0: \forall n\in\mathbb{N}:|\overline{x}_{n,p}-L|<\epsilon$. In particular, just by rewriting this definition in set form and choosing $\epsilon:=1$, this implies that $x\in \bigcap_{m\in\mathbb{N}}A_{p_0,m}$ for some $p_0\in\mathbb{N}$, where $A_{p_0,m}:=\{x:|\overline{x}_{mp_0,p_0}-L|<1\}$.
If we assume for simplicity that $(x_k)_{k=0}^{\infty}$ are the digits of $x\in[0,1]$, the events $(A_{p_0,m})_{m\in\mathbb{N}}$ are independent under the Lebesgue probability measure on $[0,1]$ (since the digits themselves are independent random variables) and have probability less than $1$. This shows $P(\bigcap_{m\in\mathbb{N}}A_{p_0,m})=0$ for all $p_0\in\mathbb{N}$, or,  if we denote by $B_L$ the reals with unique Banach limit $L$, that $P(B_L)=0$ for all $L\in\mathbb{R}$. Since $\mathbb{R}$ is uncountable, it could happen that $P(\bigcup_{L} B_L)>0$. However, this is not the case since $P(\bigcup_{L\not= 4.5}B_L)=0$ by the law of large numbers.


Q:

Fade In & Out Animation With The Same UIImageView

I want to know whether I can create any type of animation with the same UIImageView. Whenever the user clicks a button, it will change the photo using a fade in animation.
import UIKit

class ViewController: UIViewController {

var maximum: Int = 2
var number: Int = 0
var imageNames = ["0", "1"]

@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nextButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // Gradient
    nextButton.setGradientBackground(colorOne: UIColor(red:0.00, green:0.78, blue:1.00, alpha:1.0), colorTwo: UIColor(red:0.00, green:0.45, blue:1.00, alpha:1.0))

    // Drop Shadows
    nextButton.layer.shadowColor = UIColor.black.cgColor
    nextButton.layer.shadowOffset = CGSize(width: 1, height: 1)
    nextButton.layer.shadowRadius = 25
    nextButton.layer.shadowOpacity = 0.10

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func changeImages(_ sender: Any) {
    number = Int(arc4random_uniform(UInt32(maximum)))
    mainImage.image = UIImage(named: "\(number).jpg")
}

}

There is no attempt of me trying to create an animation.
I was just hoping someone could help me create one.

A:

you need to animate alpha value. make a fade in and fade out function like this :
 func fadeIn(){
    UIView.animate(withDuration: 3) {
        self.my.alpha = 0.0
    }
}

func fadeOut(){
    UIView.animate(withDuration: 3.0) {
        self.my.alpha = 1.0
    }
}

Then use it when you change your image:
fadeIn()
changeImages() /* your change image logic without animation */
fadeOut()


Q:

Find $f$ such that $\int f^{n}(x)dx=f^{2017}(x)+C$

Determine the polynomial functions $f\in \mathbb{R}[X]$, for which exists $n\in \mathbb{N},n\geq 1$, so that $f^{2017}$ is an antiderivative for $f^n$.
What I did so far:
Let $f=a_{k}X^{k}+a_{k-1}X^{k-1}+...+a_{1}X+a_{0}$.
Then $(f^{2017})'=f^{n}\Leftrightarrow 2017\cdot f^{2016}\cdot f'=f^{n}$.
Hence, we obtain that $(a_{k}X^{k}+...+a_{0})^{n}\cdot \left [  2017\cdot (a_{k}X^{k}+...+a_{0})^{2016-n}\cdot (ka_{k}X^{k-1}+...+a_{1})-1\right ]=0$.
Additionally, for $x:=0$, we find that $2017\cdot a_{0}^{2016}\cdot a_{1}=a_{0}^{n}$.

A:

Beginning from $2017f^{2016}f'=f^n$, we find that $2016\deg f+\deg f-1=n\deg f$, so $(2017-n)\deg f = 1$. This is only possible if $\deg f=1$ and $n=2016$.
So $f(x)=ax+b$ with $a\ne 0$. The the equation becomes $2017 a f^{2016}=f^{2016}$, so $a=\frac1{2017}$ and $b$ is arbitrary.


Q:

What does npm WARN excluding symbolic link mean?

What does npm WARN excluding symbolic link mean? And how do I make it go away?

A:

The message is emitted when npm interacts with a TAR file.
When it detects that a symbolic link is being used, it will emit the warning. For example, an archive you're trying to install through npm may contain a symbolic link. Those links will not be created on your local file system and are ignored.


Q:

Implement possibility to access class member static as well as non-static on a derived class

I have the following classes.
// My baseclass
class Item {
    public:
    virtual const std::string GetItemName() = 0;
};

// My derived class
class Shovel : public Item {
    private:
    static const std::string _ITEM_NAME = "tool_shovel";

    public:
    const std::string GetItemName(){
        return _ITEM_NAME;
    }
}

With this i can access the names of my Item objects like this:
Item* myItem = new Shovel();

myItem.GetItemName(); // Returns "tool_shovel" ofcourse

I would now also like to access the name of an item without having an instance of it like this.
Shovel::GetItemName();

I know it is not possible to implement a virtual static function.
but is there any way to implement this in a 'nice' way or is this more a problem in my concept?
Thanks for the help!

A:

I didn't know it is possible to call a static function directly from an instance, so i solved my problem now with 2 methods.
One public static function, so i can get the name of an item at any time. And another private non-static function to let the baseclass get the name of the current item.
Here is the code:
// My baseclass
class Item {
    protected:
    virtual const std::string _GetItemName() = 0;
};

// My derived class
class Shovel : public Item {
    private:
    static const std::string _ITEM_NAME = "tool_shovel";

    protected:
    const std::string _GetItemName(){
        return _ITEM_NAME;
    }

    public:
    static const std::string GetItemName(){
        return _ITEM_NAME;
    }
};

I hope this helps anyone. If you have questions feel free to ask.


Q:

C# drop downlist selected index changes taking lot of time

I have a web page with a timer control ,1 update panel ,few drop downs etc.
Many of the drop down on selected index changed need to display more than 1 additional controls or hide some controls.The issue is it takes a lot of time in a way that user dont realize that it is yet to complete the event click.Please suggest some ideas.

A:

If it's taking a long time, I assume that you're using a server-side event handler for when your dropdown selection changes. When a server-side event fires, what that means is that your form is posted back to the server, the server re-renders the form and sends it back to the client, and then the client replaces the contents of the update panel. Thus, the user is subject to multiple factors that can cause slowness.
If you have the option, you could rework the page so that the event handling is done client-side. You would have to write some JavaScript code and make sure that the necessary data for updating the page is available to your JavaScript. If you cannot expose all of the data necessary for updating purely client-side, you could do an Ajax call to get just the data you need; that should be more lightweight than a full partial postback.
All of this is a lot of work, but should make your page faster. Of course, maybe you don't really need to solve the page's speed but provide better feedback to let the user know that the page is updating. For example, if you have a "Loading..." indicator while the partial postback is going on, then the user will know to wait.


Q:

I get an error for inserting data into SQL Server via VB.Net

I need to put some data into my SQL Server database using VB.net forms and vb language.
I already have a similar SQL request who is working but this time I get crazy errors.
This is the code who is inserting the data into the database:
Dim strIns As String = "INSERT INTO Entreprise (adresseClient, villeClient, cpClient, telClient, identClient, nomEntreprise, secteurEntreprise, dateCreationEntreprise) VALUES ('"
      strIns &= txtAdresse.Text & ", " & txtVille.Text & ", " & txtCp.Text & ", " & txtNumero.Text & ", " & txtID.Text & ", " & txtNom.Text & ", " & txtSecteur.Text & ", " & txtDateCreation.Text & "')"

Dim con As New SqlConnection
Dim cmd As New SqlCommand

Try
   con.ConnectionString = "Data Source= DESKTOP - KBTD2C1 \ MYDATABASE;Initial Catalog=MyDatabse; Integrated Security=SSPI;"
   con.Open()

   cmd.Connection = con
   cmd.CommandText = strIns

   cmd.ExecuteNonQuery()

Catch ex As Exception
    MessageBox.Show("Error While inserting record On table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try

I get this error:

Error while inserting record on table: Syntax error near 'Infinite'

This is the SQL command I generate in strIns:

I don't find out where is the syntax error ?
Here is my SQL Server database table:

A:

It looks like you are not applying single quote " ' " around each of the values you are passing. You are simply concatenating the textbox's value with the query string.
With current code your SQL query will become something like this:
INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC, XYZ')

But after applying " ' " around values it will become :
INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC', 'XYZ')

which is the correct version.
Also I would say not to concatenate the SQL Query as string as wit will cause SQL injection, please use Query parameters instead.
You can also share the error details here, which will help us to analyze the bug


Q:

Session.getActiveUser().getEmail() workaround for distributing grades from a spreadsheet

My students all have a Google account, but use different emails (like john@hotmail.com).I tried to write a webapp that would get from my grade spreadsheet the row with the webapp's user's email address, so that each student would only see his or her grades. That webapp uses: Session.getActiveUser().getEmail()
This only works for users in the same domain as the script, I have to run the script as the webapp user (which is ok -- my students trust me that far!). Here is that restriction:

Returns a User object describing the current user. In
  limited-privilege executions (such as in response to onOpen or
  onEdit), we only return the identity of the active user if both the
  user and the script owner are part of the same domain. This is to
  protect the privacy of consumer users, who may not want their email
  address exposed.

My script works, but I have to put the table of grades directly in the script and update the webapp each time I update my spreadsheet. Yeck!
I can't share my grade spreadsheet because then they would see each other's grades. So now I am brainstorming other workarounds.
Here is one example:

Share a second spreadsheet, copy the grades from my spreadsheet with an update function that encrypts the grades. The webapp sucks up the data from the shared spreadsheet and decrypts. Now a simple update of a spreadsheet is all that is needed -- the webapp doesn't need to be republished. (There are some simple encryption options, like base64encode with maybe a little scrambling...?)
Find a way to automatically update the webapp and republish. (Don't know how to do that.)
????

Any suggestions?
PS: if 1 seems feasible, some suggestions for simple encryption code?

A:

I dont understand why you say "My script works, but I have to put the table of grades directly in the script and update the webapp each time I update my spreadsheet"
It is very easy to create a webapp that shows a part of a spreadsheet using a flextable for example.  Each instance of the app will have a user related content automatically and you will only have to update your master spreadsheet to get what you want.  I don't know why you want to encode data for this... I think the user identification through the google login should be enough, don't you ?
Here is an example of such a webapp, the numbers you see are taken from a specific column in a master spreadsheet (for this public copy I set the app as running as "me" to avoid the authorization process but in real every user is identified and sees only his data).
The Spreadsheet itself and the code are viewable here, do not hesitate to come back if you need further information.


Q:

If i have a page with different css styles and i want to load it onto a page that has it's own css styles inside of an iframe

Is it possible to change the css in that iframe upon loading through jquery?
This is what I got:

I'm trying to change div.global-header to display:none.. I have several other div's that i would not want to load by simply hiding with css.

A:

You have duplicate ID's, this assumes your iFrame ID is skiptrace.


Q:

The Fragment element contains an unhandled extension element 'util:RegistrySearch'

Learning how to create Wix Booloader so that I can install .NET framework with my msi install package. Anyway I am stuck with an error for an unhandled extension element. Code is below
<?xml version="1.0" encoding="utf-8"?>
<!--
# This comment is generated by WixEdit, the specific commandline
# arguments for the WiX Toolset are stored here.

candleArgs: "<projectfile>" -ext WixBalExtension
lightArgs: "<projectname>.wixobj" -ext WixBalExtension
-->
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

<Bundle UpgradeCode="80B0ECBE-CAAE-4B6A-9705-49F0232B0C24"
        Version="0.0.1">
    <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" />
    <Chain>
        <PackageGroupRef Id="Netfx45" />
    </Chain>
</Bundle>

<Fragment>
    <util:RegistrySearch Root="HKLM"
                         Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full"
                         Value="Version"
                         Variable="Netfx4FullVersion" />
    <util:RegistrySearch Root="HKLM"
                         Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full"
                         Value="Version"
                         Variable="Netfx4x64FullVersion"
                         Win64="yes" />
    <!-- .NET 4.5 only installed if Vista or higher AND it's not already installed-->
    <!-- .NET 4.5 only installed if Vista or higher AND it's not already installed-->
<PackageGroup Id="Netfx45">
        <ExePackage Id="Netfx45"
                    Cache="no"
                    Compressed="yes"
                    PerMachine="yes"
                    Permanent="yes"
                    Vital="yes"
                    InstallCommand="/q"
                    SourceFile="C:\Users\ProRip\Downloads\dotnetfx45_full_x86_x64.exe"
                    DetectCondition="(Netfx4FullVersion="4.5.50709") AND (NOT VersionNT64 OR (Netfx4x64FullVersion="4.5.50709"))"
                    InstallCondition="(VersionNT >= v6.0 OR VersionNT64 >= v6.0) AND (NOT (Netfx4FullVersion="4.5.50709" OR Netfx4x64FullVersion="4.5.50709"))" />
    </PackageGroup>
</Fragment>

Error message is
error CNDL0200 : The Fragment element contains an unhandled extension element 'util:RegistrySearch'.  Please ensure that the extension for elements in the 'http://schemas.microsoft.com/wix/UtilExtension' namespace has been provided.
error CNDL0200 : The Fragment element contains an unhandled extension element 'util:RegistrySearch'.  Please ensure that the extension for elements in the 'http://schemas.microsoft.com/wix/UtilExtension' namespace has been provided

Can anyone please explain what my error is I have included the correct namespace and I can't see a reason for the error!

A:

The WiX extension for the namespace xmlns:util="http://schemas.microsoft.com/wix/UtilExtension is provided by a dll named WixUtilExtension (this assuming you are using Visual Studio).  Right-click on the References node in your project and add a reference to the WixUtilExtension dll.


Q:

BeautifulSoup4: Missing Parsed Table Data

I'm trying to extract the Earnings Per Share data through BeautifulSoup 4 from this page.
When I parse the data, the table information is missing using the default, lxml and HTML 5 parsers. I believe this has something to do with Javascript and I have been trying to implement PyV8 to transform the script into readable HTML for BS4. The problem is I don't know where to go from here.
Do you know if this is in fact my issue? I have been reading many posts and it's been a very big headache for me today. Below is a quick example. The financeWrap includes the table information, but beautifulSoup shows that it is empty.
import requests
from bs4 import BeautifulSoup

url = "http://financials.morningstar.com/ratios/r.html?t=AAPL&region=usa&culture=en-US"

response = requests.get(url)
soup_key_ratios = bs(response.content, 'html5lib')
financial_tables = soup_key_ratios.find("div", {"id":"financeWrap"})
print financial_tables

# Output: <div id="financeWrap">
#           </div>

A:

The issue is that you're trying to get data that is coming in through Ajax on the website. If you go to the link you provided, and looked at the source via the browser, you'll see that there should be no content with the data.
However, if you use a console manager, such as Firebug, you will see that there are Ajax requests made to the following URL, which is something you can parse via beautifulsoup (perhaps - I haven't tried it or looked at the structure of the data).
Keep in mind that this is quite possibly against the website's ToS.


Q:

Question on uniform intergrability

Consider a probability measure $m$ over $W \subseteq{R^m}$, so that $m(W) = 1$.
Consider a function $f: X \times W \rightarrow \mathbb{R}_{\geq 0}$, with compact $X \subset \mathbb{R}^n$, such that the following proposition holds true.
For any $\epsilon > 0$ there exists $c > 0$ such that $m(\{w \in W \mid f(x,w) \geq c  \}) < \epsilon \ $ for all $x \in X$.
In other words, the measure of $\{f\geq c\}$ can be made arbitrarily small, uniformly on $X$.
What are the (weakest) conditions to have the family $\{f(x,\cdot)\}_{x \in X}$ Uniformly Integrable?

A:

[Old answer] It is convenient to consider $\epsilon=2^{-n}$. Let $c_n$ be the corresponding $c$. You need the sum $\sum_{n}2^{-n}c_n$ to converge.
[New answer] It is convenient to consider $\epsilon_n=\sup_{x\in X} m(\{w\in W\colon f(x,w)\ge 2^n\})$. We know that $\epsilon_n\to 0$ as $n\to \infty$. I claim that the condition $\sum_{n=0}^\infty 2^n \epsilon_n<\infty$ is sufficient for uniform integrability.
Fix $x$ and consider the sets $W_n=\{w\in W\colon 2^n\le f(x,w)< 2^{n+1}\}$, $n=0,1,2,\dots$. Note that $m(W_n)\le \epsilon_n$. Since
$$\int_W f(x,w)\,dm(w) = \int_{\{f<1\}} f(x,w)\,dm(w) + \sum_{n=0}^\infty \int_{W_n} f(x,w)\,dm(w) $$
we can estimate the integral
$$\int_W f(x,w)\,dm(w) \le 1 + \sum_{n=0}^\infty 2^{n+1}\epsilon_n<\infty$$
Moreover, if instead of $W$ we integrate over the set $\{f\ge 2^N\}$, the estimate becomes
$$\int_{f\ge 2^N} f(x,w)\,dm(w) \le \sum_{n=N}^\infty 2^{n+1}\epsilon_n<\infty$$
which is uniformly small.


Q:

FabricJs: object border grows beyond grid cell

Using FabricJS, I am working on a prototype where in objects are drawn with border. Border size is an exposed property which can be changed by user. Canvas has Grid. Objects are drawn within grid cell. My issue is, border goes beyond grid cell. Please see the screenshot
Overridden _render method from fabricJS to decrease object height and width with that of border size. Here is the code..
_render(ctx: CanvasRenderingContext2D, noTransform: boolean) {
        if (this.width === 1 && this.height === 1) {
            ctx.fillRect(-0.5, -0.5, 1, 1);
            return;
        }

        var rx = 5,
            ry = 5,
            //MODIFIED CODE - START
            w = this.width - (this.borderThickness * 2), // 2: Left + Right
            h = this.height - (this.borderThickness * 2),// 2: Top + Bottom
            //w = this.width,
            //h = this.height,
            //MODIFIED CODE - END
            x = noTransform ? this.left : -this.width / 2,
            y = noTransform ? this.top : -this.height / 2,
            isRounded = rx !== 0 || ry !== 0,
            k = 1 - 0.5522847498;

        ctx.beginPath();

        ctx.moveTo(x + rx, y);

        ctx.lineTo(x + w - rx, y);
        isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);

        ctx.lineTo(x + w, y + h - ry);
        isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);

        ctx.lineTo(x + rx, y + h);
        isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);

        ctx.lineTo(x, y + ry);
        isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);

        ctx.closePath();

        /**** Render Fill *****/
        //this._renderFill(ctx);

        if (!this.fill) {
            return;
        }

        ctx.save();
        ctx.fill();
        ctx.restore();

        /**** Render Fill *****/

        //render text
        var textSize = 16;
        var textY = y + (h / 2) + (textSize / 2);
        var textX = x + (w / 2);

        ctx.fillStyle = "#010101";
        ctx.font = textSize + "px Arial";

        ctx.fillText(this.currentValue.toString(), textX, textY);

        this._renderStroke(ctx);
    }

But the result is not as expected..

What my requirement is, object should not grow more that that of grid cell. If user increases border thickness, object should shrink and accommodate border within grid cell.
Thanks in advance.

A:

Here is one way to do it by adjusting the object width & height:
var borderSize = 30, //here is a new border width
    absWidth = rect.width + rect.strokeWidth,
    absHeight = rect.height + rect.strokeWidth;

rect.strokeWidth = borderSize;
rect.width = absWidth - borderSize;
rect.height = absHeight - borderSize;
rect.setCoords();
canvas.renderAll();

See plunker here: https://plnkr.co/edit/jlBQoEfShjpS00JobVbY?p=preview


Q:

Red markings in reviewboard

Does anyone knows what these red markings in reviewboard mean ?
I've seen them popping up inconsistently.
The showing file is a .html file in an csproj, it contains a JavaScript underscore template.

A:

I was also searching for the same and got this link
https://groups.google.com/forum/?fromgroups=#!topic/reviewboard/sOR_-EGmDok ,
where they say that it is because of the pygments  which is the highlighter reviewboard uses internally. I went ahead searching for to validate this answer and found that it was a pygments problem failing to recognize utf8 characters .
please see
1) https://code.google.com/p/minted/issues/detail?id=55
2) https://tex.stackexchange.com/questions/14166/red-box-drawn-around-question-mark-operator-in-minted-erlang-code
both support the answer posted in the google groups link .


Q:

Cross sub domain cookies on azure

My applications consists of 2 parts:

The web API, written in .NET Core
The web app, written in React and rendered using a nodejs express server

I am hosting these parts on azure, each on it's own sub domain so we have:

api.azurewebsites.net
app.azurewebsites.net

When the user logs in I set a cookie, to my understanding a cookie can be used accross sub domains. The cookie is set the following way:
Response.Cookies.Append("token", "token value", new CookieOptions
{
    Expires = DateTimeOffset.Now.AddDays(7),
    SameSite = SameSiteMode.None,
    Domain = "azurewebsites.net"
});

But the cookie is not sent along with requests to either sub domain. How can this be?
If this is the wrong approach how do I authenticate with a SSR app and a rest api? When the app gets rendered in node it fetches data the exact same way as in the browser using isomorphic-fetch, the cookie is passed along with it.
All this works flawlessly on localhost, the problem starts when the app in on a different sub domain from the api.
UPDATE:
The cookie header looks like this:
Set-Cookie: token=<token>; expires=Sat, 22 Jun 2019 05:35:18 GMT; domain=azurewebsites.net; path=/; secure

On firefox it works different from chrome. On chrome i do the authentication api request, get the token get the cookie header and then the cookie does not get sent along any subsequent requests.
In firefox the cookie does get sent with subsequent requests, however upon refreshing the page the cookie is gone.

A:

I found this ASP.NET Core Sharing Identity Cookie across azure web apps on default domain (*.azurewebsites.net)
Cross sub domain cookies are blocked for the azurewebsites.net domain for security reasons.


Q:

How to show some WPF User Control as a Modal Window?

How to show some WPF User Control as a Modal Window?
Thank you!

A:

You put them in a new window shell and call ShowDialog on it.


Q:

create multiple elements (list) with onclick event

I'm trying to add multiple elements to a list and each element should execute the same on click function with different parameters, the problem is the variable x gets always contains the same value for all elements of the list.
How can I add elements and call the onclick event with a different parameter?
var addQuickLabelList =  function(txtList,ul) {

for (i = 0; i<txtList.length ; i++) {
        var li = document.createElement("li");
        li.setAttribute("data-icon", "false");

        var a = document.createElement("a");
        a.innerHTML = txtList[i];
        li.appendChild(a);

        var x = "#"+txtList[i];

        a.addEventListener("click", function(){
            y = x.clone();
            alert(x);
            } , false);// add

        $(ul).append(li);
    }
};

A:

x always gets the same value because all your event handlers share the same var x variable. To scope a variable to a block, use let (or const if it won't change) instead of var.
Or you could use .forEach() on the txtList Array so that the var is scoped to the invocation of the callback.
var addQuickLabelList =  function(txtList,ul) {
    txtList.forEach(function(txtItem) {
        var li = document.createElement("li");
        li.setAttribute("data-icon", "false");

        var a = li.appendChild(document.createElement("a"));
        a.innerHTML = txtItem;

        var x = "#"+txtItem;

        a.addEventListener("click", function(){
            console.log(x);
        } , false);

        ul.appendChild(li);
    });
};

But you also don't really even need the x variable. You already set the text as the content of the a, so you can just grab that instead. Which means you could also reuse the function, which is nicer.
function handler() {
   console.log("#" + this.textContent);
}

var addQuickLabelList =  function(txtList,ul) {
    txtList.forEach(function(txtItem) {
        var li = document.createElement("li");
        li.setAttribute("data-icon", "false");

        var a = li.appendChild(document.createElement("a"));
        a.innerHTML = txtItem;

        var x = "#"+txtItem;

        a.addEventListener("click", handler, false);

        ul.appendChild(li);
    });
};


Q:

Get Higher Level Object from Object Array Item

I have 2 class which both extend an abstracted class. Both classes has a private method called "content" which is an array of items of the other class.
Once I add an object B into the "content" array of class A I need to get the parent object A from the item object B.
Here is the example, it's easier to look at it:

<?php

abstract class heroes {
    private $tag;
    private $content = array();

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

    public function getContents() {
        return $this->content;
    }

    protected function addContent($obj) {
        $this->content[] = $obj;
        return $obj;
    }

}

final class batman extends heroes {

    public function addPartner() {
        return $this->addContent(new robin());
    }
}

final class robin extends heroes {

    private $capes;

    public function dieAtFirstFight() {
        return BATMAN OBJ???
    }

}

$batman = new batman();
$batman = $batman->addPartner()->dieAtFirstFight();

?>

I tried in the abstract class to add a private method called $father in which everytime I add a partner I set $self (which is Batman object) but in the php error log I get the error "Object of class Batman could not be converted to string"

A:

U have to use "$this" to add the father. There is not $self in php.

<?php

abstract class heroes {
    private $tag;
    private $content = array();
    protected $father;

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

    public function getContents() {
        return $this->content;
    }

    protected function addContent($obj) {
        $this->content[] = $obj;
        $obj->setFather($this);
        return $obj;
    }

    protected function setFather($father) {
        $this->father = $father;
    }

}

final class batman extends heroes {

    public function addPartner() {
        return $this->addContent(new robin('tag'));
    }
}

final class robin extends heroes {

    private $capes;

    public function dieAtFirstFight() {
        return $this->father;
    }

}

$batman = new batman('tag');
$batman = $batman->addPartner()->dieAtFirstFight();

?>


Q:

Is there a way to use item weight in a Shopping Cart Price Rule condition?

I have a product that has two weights options, 1lbs and 2lbs. Is it possible to set a Shopping Cart Price Rule condition for only the 2lbs item?

A:

Here is a best way to apply Shopping Cart Price Rule condition.

add new attribute (Catalog > Attributes > Manage Attributes)
ex)item_att_weight
at the properties :  Input type = dropdown, Use for Promo Rule Conditions = yes.. (others can be set you want)

set weight value at the Manage Label / Options

New attribute that you made add to attribute set (Catalog > Attributes > Manage Attributes Sets)
When you add a product, have to use Configurable Product and select attribute set that you made.

under Shopping Cart Price rules.

setup condition whatever you want
Go to Actions and setup conditions as below

Select attribute "item_att_weight" that you made
Select Value 2(lb)

then It should be worked as you desired. I hope it helps you...


Q:

Parsing list object file paths for file name

I am trying to automate a naming process that takes the file name from a list of file paths to name other folders, geodatabases, zipfiles, etc.
The problem I'm running into is that, I assume, I am trying to run string functions on list object and I can't figure out how to get the script to do what I need it to do.
For example, I have the file path C:\TEMP\Durham.shp. I want to name a geodatabase, folder, and zipfile "Durham". Instead I get a folder and geodatabase named "C".
Can someone take a look at my script and tel me what I'm doing wrong?
The following script is that last incarnation of several attempts.
import arcpy, os
import zipfile
from arcpy import env
from os.path import basename

BASELAYERS = arcpy.GetParameterAsText(0)
CLIPLAYERS = arcpy.GetParameterAsText(1)
OUTFOLDERMASTER = arcpy.GetParameterAsText(2)
FILETYPES = ["*.shp", "*.dbf", "*.shx", "*.prj", "*.sbn", "*.sbx", "*.xml"]

env.workspace = OUTFOLDERMASTER
for LAYERS in CLIPLAYERS:
    LAYERSSTR = ''.join(LAYERS)
    BASENAME = LAYERSSTR.split("\\")[-1]
    FOLDER = os.path.join(OUTFOLDERMASTER, BASENAME)
    os.makedirs(FOLDER)
    PGDBNAME = "NCFlood_Effective_" + BASENAME + "_PGDB.mdb"
    arcpy.CreatePersonalGDB_management(FOLDER, PGDBNAME, "9.3")
    PGDB = os.path.join(FOLDER,PGDBNAME)
    for FILES in BASELAYERS:
        FEATURENAMESTR = ''.join(FILES)
        FEATURENAME = os.path.basename(FEATURENAMESTR)
        SHAPEFILENAME = FEATURENAME + ".shp"
        SHAPEFILE = os.path.join(FOLDER, SHAPEFILENAME)
        arcpy.Clip_analysis(FILES, LAYERS, FEATURENAME)
        arcpy.Clip_analysis(FILES, LAYERS, SHAPEFILE)
    ZIPFILELIST = []
    for TYPE in FILETYPES:
        ZIPFILELIST.extend(glob.glob(FOLDER))
    ZIPFILENAME = os.path.join(FOLDER, "NCFlood_Effective_" + FOLDERNAME + "_SHP.zip")
    ARCHIVE = zipfile.ZipFile(ZIPFILENAME, "w")
    for ZIP in ZIPFILELIST:
        ARCHIVE.write(ZIP, os.path.basename(ZIP), zipfile.ZIP_DEFLATED)
    ARCHIVE.close()

I have also tried
    BASENAME = os.path.basename(LAYERS)
    FOLDERNAME = os.path.splitext(BASENAME)[0]

A:

I think your problem is that in its current state CLIPLAYERS is a string and not a list.  This means that when you loop through it using for LAYERS in CLIPLAYERS it is going to give you one character at a time starting with C.
You can avoid this by adding CLIPLAYERS = CLIPLAYERS.split(";") before you loop through CLIPLAYERS.  This will create a list from a semicolon delimited string of layers.


Q:

Counting process which is not a Poisson process

Please construct a counting process N, whose r.v. N(t) are distributed as Poisson(λt) but the process N itself is not a Poisson process.
This is an assignment in our Stochastic Process class. So I suppose this counting process N should meet all but one of a Poisson's process conditions. 1) N(0)=0 2) independent increments 3) At any given time t N(t) ~ Poiss( λt). So making the increments dependent should probably be the way to go. However, I've no idea how that could be done.

A:

Let $\{N_t, t\geq 0\}$ be a homogeneous Poisson process with intensity $\lambda$, it holds that $N_{t+s}-N_s\sim Pois(\lambda t)$. Thus, let $Z_t=N_{t+s}-N_{s}$ for any $t,s\geq 0$. Then clearly $\{Z_t, t\geq 0\}$ is a counting process, $Z_t\sim Pois(\lambda t)$, but most importantly - its increments are dependent, e.g. let $m>s\geq 0,\,t_2>t_1\geq 0$ and then $Z_{t_2}-Z_{t_1}=N_{t_2+s}-N_{t_1+s}$ and $Z_{t_1}-Z_{0}=N_{t_1+m}-N_{m}$, intervals $\left(t_1,t_2\right]$ and $(0,t_1]$ do not overlap, but $N_{t_2+s}-N_{t_1+s}$ and $N_{t_1+m}-N_{m}$ are dependent since $m>s$.


Q:

OMP update vector issue

I have the following snippet of code
!$OMP PARALLEL PRIVATE(i)
  do i = inode1,inode2
     if (mod(CEILING(Rat(1,i)*checkerDivider),2).ne.mod(CEILING(Rat(2,i)*checkerDivider),2)) then
           H0(i) = H0(i)
     else
           H0(i) = H0(i) + onsiteShift
     endif
  end do
  !$OMP END PARALLEL

onsiteShift equals 0.02, and H0(i) is equal to 0. For this example, I work on 16 processors. Whenever I enter the else clause, it should set the values of H0(i) to 0.02, obviously. However, in this case, I end up with random values between 0 and 0.32 (with steps of 0.02). Clearly, I enter the clause more than once for a same value of i. I tried using !$OMP ATOMIC UPDATE as well, but then I end up with a value of exactly of 0.32 (= 16*0.02...).
Also, I thought that by using a temporary H0_temp variable, I would avoid having different threads having this racing condition problem.
!$OMP PARALLEL PRIVATE(i, H0_temp)
  do i = inode1,inode2
     H0_temp = H0(i)
     if (mod(CEILING(Rat(1,i)*checkerDivider),2).ne.mod(CEILING(Rat(2,i)*checkerDivider),2)) then
           H0_temp = H0_temp
     else
           H0_temp = H0_temp + onsiteShift
     endif
     H0(i) = H0_temp
  end do
  !$OMP END PARALLEL

Still, it doesn't work. I have also tried something along the lines of a reduction...
Basically, how to change the value of H0(i) using OMP? The end result of H0 should be either 0 or 0.02. No other value. If I use only one processor there is no problem...
My second question, how big an impact can such problem have on my previous calculations. I only noted the problem for this case, but I suspect I might have the same problem for many of my other loops. Or does it somehow (hopefully) become less a problem when the value of inode2 is very large (around 20 million for my production runs)?

A:

You just forgot the DO in
!$OMP PARALLEL DO PRIVATE(i)

Therefore no worksharing took place and all threads were doing complete loops.
Regarding the additional question: yes, it is a serious problem and you must fix it.


Q:

If the largest positive integer is n such that $\sqrt{n - 100} + \sqrt{n + 100}$ is a rational no. , find the value of $\sqrt{n - 1}$ .

So here is the Problem :-
If the largest positive integer is n such that $\sqrt{n - 100} + \sqrt{n + 100}$ is a rational no. , find the value of $\sqrt{n - 1}$ .
What I tried :- I think that for $\sqrt{n - 100} + \sqrt{n + 100}$ to be a rational no. , both $(n - 100)$ and $(n + 100)$ have to be squares. Suppose :- $(n - 100)$  = $k^2$ and $(n + 100)$ = $m^2$ for some positive integers $k,m$  , and in the end I could only deduce that $(m + 10)(m - 10) = k^2 + 100$ , but then I couldn't proceed .
Also by guesswork, I could deduce that for $n = 125$, both nos. do become squares, although I don't know whether $n = 125$ is the highest or not.
Any hints or explanations to this problem will be greatly appreciated !

A:

Let $\sqrt{n-100} + \sqrt{n+100} = p$, where $p$ is rational.
$$\implies 2n + 2\sqrt{n^2 - 10000} = p^2$$
But that must mean that $2\sqrt{n^2 - 10000}$ is rational.
Which must mean that $\sqrt{n^2 - 10000}$ is rational.
$$\implies n^2 - 10000 = k^2$$
$$\implies (n+k)(n-k) = 10000$$ The problem requires us to maximize $n$, notice that we'll get the maximum value of $n$ if we split $10000 = 5000 \times 2$ and set $n+k = 5000$ and $n-k = 2$ to get $n = 2501$.
Hence, $\boxed{\sqrt{n-1} = 50}$


Q:

If Java is pass by value, how does this swap method work?

OK so I understand that Java is pass by value (including for References, it passes the Object by the VALUE of the reference - i.e. the address).
If so then why does the swap(int[] array) method - passing an array of primitives - work?
public class TestArraySwap {

    public static void swap(int a, int b) {
        int temp =b;
        b=a;
        a=temp;
    }

    public static void swap(int[]a) {
        int temp = a[1];
        a[1]=a[0];
        a[0]=temp;
    }

    public static void main(String[] args) {
        //Test Primitive swap
        int a=1;
        int b=2;
        System.out.println("a="+a +" b="+b);
        swap(a,b);
        System.out.println("a="+a +" b="+b);

        //Test array swap
        int[] array = new int[2];
        array[0]=1;
        array[1]=2;
        System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
        swap(array);
        System.out.println("a[0]="+array[0] +" a[1]="+array[1]);
    }
}

The output is
a=1 b=2
a=1 b=2
a[0]=1 a[1]=2
a[0]=2 a[1]=1

The second swap works - I would expect it not to but perhaps I am missing something?

A:

The main method has a reference to an array:
R1 ------> [1, 2]

Then it calls the swap() method. So a copy of the reference to the same array is created and used by the swap() method:
 R1 -----> [1, 2]
             ^
             |
 R2 ---------|

Then the swap() method changes the content of the array:
 R1 -----> [2, 1]
             ^
             |
 R2 ---------|

And it returns. R1 still references the same array, whose content has been changed.


Q:

Correct format for android:gravity in attrs.xml?

I have the following situation:
in styles.xml:
<style name="fooStyle">
    <item name="android:padding">?fooView.padding</item>
    <item name="android:background">?fooView.background</item>
    <item name="android:gravity">?fooView.gravity</item>
</style>

in attrs.xml:
<attr name="fooView.padding" format="dimension" />
<attr name="fooView.background" format="color|reference" />
<attr name="fooView.gravity" format="????"/>

in themes.xml:
<style name="fooViewTheme" parent="android:Theme">
    <item name="fooView.padding" >2dip</item>
    <item name="fooView.background" >#AA000000</item>
    <item name="fooView.gravity">right|bottom</item>
</style>

The problem is that I cannot figure out what the format for the fooView.gravity should be. I've already tried with string, enum and flag but none seem to work: I always get a java.lang.NumberFormatException: unable to parse 'right|bottom' as integer as soon as the view that uses this theme gets loaded.
All answers are appreciated.

A:

Those are the gravity values used by Android. You can use that in your attrs.xml:
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="gravity">
            <flag name="bottom" value="80" />
            <flag name="center" value="17" />
            <flag name="center_horizontal" value="1" />
            <flag name="center_vertical" value="16" />
            <flag name="clip_horizontal" value="8" />
            <flag name="clip_vertical" value="128" />
            <flag name="end" value="8388613" />
            <flag name="fill" value="119" />
            <flag name="fill_horizontal" value="7" />
            <flag name="fill_vertical" value="112" />
            <flag name="left" value="3" />
            <flag name="right" value="5" />
            <flag name="start" value="8388611" />
            <flag name="top" value="48" />
        </attr>
    </declare-styleable>
</resources>

In your layout XML you can use it this way:
<MyCustomView
        custom:gravity="center|bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

And in Java code you can read the value using this:
int gravity = a.getInt(R.styleable.MyCustomView_gravity, Gravity.NO_GRAVITY);

and directly set it to a sub view, if that makes sense for you:
someSubView.setGravity(gravity);

You can look up those gravity values in the source of android.view.Gravity or here

A:

It's a flag attribute. You need to define it in your attributes xml like this:
    <attr name="gravity">
      <flag name="right" value="0x01" />
      <flag name="bottom" value="0x02" />
      <flag name="left" value="0x04" />
      <!-- etc. -->
    </attr>

...and then access the values using bit masks, like this:
    boolean right = (array.getInt(R.styleable.fooView_gravity, 0) & 0x01) == 0x01;
    boolean bottom = (array.getInt(R.styleable.fooView_gravity, 0) & 0x02) == 0x02;
    boolean left = (array.getInt(R.styleable.fooView_gravity, 0) & 0x04) == 0x04;
    // etc.

...and of course, these values can be used from XML as well:
<style name="fooViewTheme" parent="android:Theme">
    <item name="fooView.gravity">right|bottom</item>
</style>


Q:

Can't authenticate with DefaultHttpClient

I want to add authentication header to my request. I'm using DefaultHttpClient from Apache httpclient 4.0.
I found that's done this way:
URI uri = new URI("http://www.bla.bla/folder/");

String host = uri.getHost();
int port = uri.getPort();

httpClient.getCredentialsProvider().setCredentials(
        new AuthScope(host, port, AuthScope.ANY_SCHEME),
        new UsernamePasswordCredentials("myuser", "mypassword")
        );

This is executed and even with the debugger I see some credentials variable of the httpClient are set at the moment of doing the request. But I inspect web traffic with Charles and there's no authentication header.
Content of vars:
host: www.bla.bla
port: -1
Btw. I enabled Charles as a proxy to see the headers of the request, with:
HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
httpParameters.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

I think that should not be altering my headers, would make no sense for webproxy... anyways if I disable the proxy stuff it also doesn't work (although I can't see the content of the header but I suppose it's the same reason).
Also tried using a request interceptor like described in Softhinker.com's post here: How can I send HTTP Basic Authentication headers in Android?
And I get exactly the same request, without authentification header.
What am I doing wrong?
Thanks in advance.

A:

I got it working setting the header "manually" in the request.
request.setHeader(new BasicHeader("Authorization", authstring));


Q:

Nhibernate Conformist Mapping "Unable to determine type..."

The class:
    public class SOPProcess : ISOPProcess
{
    public virtual Guid Id { get; set; }
    public virtual SOP SOP { get; set; }
    public virtual ProcessType Type { get; set; }

    public virtual SOPProcessInput Input { get; set; }
    public virtual SOPProcessOutput Output { get; set; }
    public virtual SOPProcessMeasures Measures { get; set; }

    public virtual decimal YieldFactor { get; set; }

    public virtual SOPProcess PreviousProcess { get; set; }
    public virtual SOPProcess NextProcess { get; set; }
}

The Mapping:
public class SOPProcessMap : ClassMapping<SOPProcess>
{
    public SOPProcessMap()
    {
        Id(s => s.Id, i => i.Generator(Generators.GuidComb));

        Property(s => s.YieldFactor);

        ManyToOne(s => s.SOP, m =>
                                {
                                    m.Column("SopId");
                                    m.Cascade(Cascade.All);
                                });

        ManyToOne(s => s.Type, m =>
                                {
                                    m.Column("ProcessTypeId");
                                    m.Cascade(Cascade.All);
                                });

        ManyToOne(s => s.NextProcess, m =>
                                        {
                                            m.Column("NextProcessId");
                                            m.Cascade(Cascade.All);
                                        });

        ManyToOne(s => s.PreviousProcess, m =>
                                            {
                                                m.Column("PreviousProcessId");
                                                m.Cascade(Cascade.All);
                                            });
    }
}

The Error:

NHibernate.MappingException: Could not determine type for: MES.ProcessManager.SOP.SOPProcess, MES.ProcessManager, for columns: NHibernate.Mapping.Column(id)

I hope it's something simple, this is my first project using the Conformist mapping, so maybe I'm just overlooking something.

A:

From our discussion on the nhusers mailing list.
I ran across the same problems.
You haven't defined the type of relationship. See the line action => action.OneToMany()); in the mapping below.
public class SportMap : ClassMapping<Sport>
{
    public SportMap()
    {
        Id(x => x.Id, map =>
        {
            map.Column("Id");
            map.Generator(Generators.GuidComb);
        });

        Property(x => x.Name, map =>
        {
            map.NotNullable(true);
            map.Length(50);
        });

        Bag(x => x.Positions, map =>
        {
            map.Key(k => k.Column(col => col.Name("SportId")));
            map.Cascade(Cascade.All | Cascade.DeleteOrphans);
        },
        action => action.OneToMany());

        Property(x => x.CreateDate);
        Property(x => x.CreateUser);
        Property(x => x.LastUpdateDate);
        Property(x => x.LastUpdateUser);
    }
}

A:

It turned out that the problem was in my Set mappings in other classes. If you don't specify the action for the mapping, it throws this (misleading) error.


Q:

Remove file name in a URL

How can i remove a file name in url with mod_rewrite.
ex: searchpage-some+search.html in to some+search.html
This is my .htaccess code code.
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /searchpage\.php\?search=(.*)\ HTTP
RewriteRule ^searchpage\.php$ /searchpage-search-%2.html? [R,L]

#Internal rewrite
RewriteRule searchpage-search-(.*)\.html$ searchpage.php?search=$1 [L]

This is for a search form that uses $_GET request. This works well only thing is that i want to remove the file name. I would really appreciated if anyone can help out.

A:

In your example you have searchpage-some+search.html but in your htaccess you are actually rewriting it to searchpage-search-some+search.html.
But to remove the searchpage-search from links, just remove searchpage-search- from the RewriteRule. Your htaccess would be something like
RewriteEngine On

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /searchpage\.php\?search=(.*)\ HTTP
RewriteRule ^searchpage\.php$ /%2.html? [R,L]

#Internal rewrite
RewriteRule (.*)\.html$ searchpage.php?search=$1 [L]


Q:

Setting localstorage cookie service that contains spaces inbetween words

I can set the cookie fine,how ever if the cookie name that I am setting is "Cookie code 1" it gets saved as
"cookie%20code%201". How do I solve this issue with the spaces in between words?
self.cookie=function(){
    localStorageService.cookie.set("CookieId",decodeURIComponent(self.Id), 100000);

  }

A:

The official doc for $cookieStore says the following:

Provides a key-value (string-object) storage, that is backed by session cookies. Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.

Means, serialize and unserialize (urlEncoded) happens automatically. So i promise you are using this plugin atm https://github.com/grevory/angular-local-storage#cookieget, which also serialize/unserialize. Just use localStorageService.cookie.get(key); to check the callback.
myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function setAndGetItem(key) {
    localStorageService.cookie.set(), "Its a cookie"); // persisted as "Its%20a%20cookie"
    console.log(localStorageService.cookie.get(key)); // returns "Its a cookie"
  }
  //...
});


Q:

Angular : How does ng-click directory parses the expression without doubly curly brace?

I have a view as follwing,

Its working. But my doubt here is, the attribute ng-click should have been set the img inside doubly braces to be executed as in ng-src as ng-click="setImage({{img}})". Its shown below,

But the later is not working.
How the expression is parsed here and how does ng-click vary from ng-src?
I really confused here. Any help highly appreciated.

A:

The difference is the following: Some of the directives use expressions, some don't. This is how they "vary" from each other. You may use the angular documentation to see, which directive use expressions and which don't.
Example for ng-click: https://docs.angularjs.org/api/ng/directive/ngClick It uses an expression:

Example for ng-src: https://docs.angularjs.org/api/ng/directive/ngSrc It doesn't use an expression:

ngClick lets you define a JavaScript-like expression, while ngSource lets you define an usual String, where you also may define an expression, inside the double braces. According to the AngularJS documentation, everything inside of the double braces is also an expression: https://docs.angularjs.org/guide/expression.
I think that the "need" to have the difference between "Expression" for "ngClick" and "String" for "ngSrc" come from the original attributes they derive from: onclick and src.
The attribute src is used to reference a resource as String, while using the attribute onclick, you may use javascript. The usual case is to call a function in onclick, i.e. onclick="doSomething();". I assume that angularjs uses these attributes as a base, this is why the workflow is similar. ngClick lets you use usual javascript expressions, while ngSrc lets you use a String and add a {{}} expression if you need to.
The benefit of using ngSrc with a variable, for example ngSrc="http://localhost/{{myRessource}}" is, that it is evaluated only after $scope.myRessource is set, not before. It uses the observer pattern to render the view as soon as the variable is set, as far as I know.
According to your example, the second one which doesn't work:

It doesn't work because of a syntax error. ngClick uses javascript expression, and the syntax of setImage({{img}}) is not correct - you would not use double brackets around variables either in a javascript function.
Further: $interpolate and $parse
Like stated above, some directives, like ngClick use expressions, while other directives like ngSrc use plain Strings combined with {{}}. The difference between the two on angularJs side is the following:

a directive using an expression is evaluated by angularjs using $parse (Read here from heading "Text and attribute bindings")
a directive using a String is evaluated by angularjs using $interpolate (Read here from heading "Context")

Example:
$scope.varOne = "asdasdasd";
var test1 = $interpolate("http://localhost/{{varOne}}");
$scope.displayOne = test1($scope);

At first, we declare a variable varOne. $interpolate returns a function which needs to be called with the scope, we will bind this to the local variable test1. Then we will call test1 using the $scope. As a result, we will have on displayOne the String http://localhost/asdasdasd.
var test2 = $parse("1+5-3");
$scope.displayTwo = test2($scope);

$parse is evaluating javascript expressions, as a test we may use the calculation "1+5-3". After calling test2, the result will be 3.
I prepared a fiddle, so you can see this: http://jsfiddle.net/wSN54/6/
You may also try using brackets in the $parse evaluation (the same that happens in your second example):
$scope.varTwo = 2;
$scope.varThree = 3;
var test2 = $parse("{{varTwo + varThree}}");
$scope.displayTwo = test2($scope);

This must resolve in an error, because the double braces are not used in usual javascript expression:

Check it out fiddle: http://jsfiddle.net/wSN54/8/


Q:

Higher order functions not working in casperjs

I have function defined like this
casper.executeRemote = (fn,params)->
    ->
        try
            fn.apply(this,params)
        catch e
            console.log(e)

getLinks = ->
    elems = document.querySelectorAll('#pagination-flickr a')

and i am calling the function like below
casper.then ->
    all_links = @evaluate @executeRemote getLinks
    casper.log all_links,'debug'

However I get the below error when i try to run this in casperjs
ReferenceError: Can't find variable: fn

The same code works fine, if i try in a browser console(compiled js). What is that I am doing wrong?

A:

Based on @Artjom's answer. I modified the code as shown below, then it works
executeRemote = (fn,params)->
    ->
        try
            fn.apply(this,params)
        catch e
            console.log(e)

getLinks = ->
    elems = document.querySelectorAll('#pagination-flickr a')
    links = (link.href for link in elems)

remoteWrapper = (excRm,gL)->
        excRm=eval('('+excRm+')')
        gL=eval('('+gL+')')
        fn=excRm(gL)
        fn()

casper.on 'remote.message',(message)->
    @echo message

casper.then ->
    all_links = @evaluate remoteWrapper, executeRemote.toString(), getLinks.toString()
    casper.log all_links,'debug'


Q:

What are the file formats for different mobile platforms

I am trying to learn more about mobile application development. iOS applications are contained in a 'ipa' file.
What are the file formats for android, BlackBerry and Windows Phone Mobile.

A:

We're talking about application distribution format, right?

Windows Phone 7: XAP. It's a renamed ZIP.
Android: APK. It's a renamed ZIP.
Windows Mobile: CAB. Also a compressed format, similar but not identical to ZIP. Many popular archivers can open those.
Blackberry: ALX for sideloading, JAD and COD for over-the-air installation. JAD is a text file, COD is binary but no idea what's in it.
Samsung bada: ZIP. As simple as that.

Note that Windows Phone 7 and Windows Mobile (6.x and below) have quite different app distribution models. WinMo exposes its filesystem, so a specific app distibution format is not, technically, necessary - you can copy an EXE to Program Files and run it all you want. Some old school apps expect you to do just that. CABs are more convenient, though - they install by single click.
WinPhone7 only supports installing from MS Marketplace. XAP is the format the compiler emits and that you submit to the Marketplace.
All those are packaging formats. Those files typically contain the executable, libraries (if any), resources, assets, and a manifest that describes the app. If you're wondering about the format of the executable - that's a whole another question.


Q:

The pilot light won't ignite on my boiler -- what I should check?

We have just brought a new house and I can’t get the pilot light to ignite on the boiler, it is at least a few months since the boiler has been used.  Where to I start on tracking down the problem?
(It is an old UK system –pre electronic , the boiler heats up water that then heats the house)
The gas fire works, so we must have gas!

Update:
The controler is a Honeywell V4600C, I have check at the inlet pressure measure point and there is gas.   Sometimes I can see a flame for a very short time when I try to light the pilot light, then the flame goes out.

A:

It's quite normal for the jets to slowly reduce in size as soot and tar (depending on the gas being used) build up along the walls of the jet opening.
If the jet hasn't been lit for some time the soot can "fluff up" and effectively block the hole, at least to the point where the gas flow is no longer sufficient to establish or maintain combustion. In such a case I prefer to remove the jet and clean it properly, using an appropriately sized cleaning wire and solvent. If you don't have such tools you can try a short blast of compressed air instead.

A:

Any chance the gas is shut off to the boiler (for the summer) and it just needs to be turned back on?  Look for a valve leading to the boiler in that general area (usually there will be a shut off valve on the gas line close to the boiler).

A:

I've never had a boiler, so I'm not sure if this will help, but my furnace's pilot light kept shutting off after it tried to start up. I ended up having to clean the flame sensor, which is a metal bar that sticks into the middle of the pilot light. It had a white buildup on it, and it wasn't able to sense the pilot flame, so it shut down to prevent filling my attic with gas. I softly rubbed it with some steel wool, and it's as good as new.


Q:

How to resolve Git error: "fatal: BUG: get_tempfile_fd() called for inactive object"

When doing a git pull on a repo I work in everyday, I received the following error:
fatal: BUG: get_tempfile_fd() called for inactive object

That's all the error said.  What does it mean and what do I do?

A:

The resolution for me was was deleting .git/index.lock.

A:

The problem for me was that I didn't have permissions for the directory I was in, so switching to the correct user fixed it for me. Simple fix but you can easily overlook it.

A:

This is often a permissions error. On Linux you can chown the folder or switch to the appropriate user.
Use ls -la within the parent folder to see the user permissions. If this is indeed the problem, you can chown the folder recursively.
If my folder name containing the repository was happytimes and my name was daniel I would do:
sudo chown -R daniel:daniel happytimes


Q:

getBoundingClientRect to detect visibility

Background:
I'm currently working on a project where my JS app is embedded into multiple other (parent) JS applications. Some parent app can show/hide my app by setting display:block/none to some element that contains my app. Other parent apps temporarily remove my app from DOM and reattach it later. Few parent apps use shadow dom, so I do not have the access to the elements in the parent app.
I need a way to check if my app is visible (inside DOM and displayed; don't care about visibility:hidden and doesn't have to be inside the viewport), without changing the parent apps, so I looked into getBoundingClientRect.
Question:
At least on chrome, getBoundingClientRect returns (w:0,h:0,l:0,t:0) if an element or its ancestor has display:none or if it is removed from DOM. I could not find any documentation on the guarantee of this behavior, and I am wondering, if it is safe (in the sense the this logic will not change) to use getBoundingClientRect to check for visibility of an element.
Also I need to know if this behavior is consistent across all major browsers, including FF, IE8+, and Safari. Is this documented anywhere?
Lastly, why (0,0,0,0)? I feel like getBoundingClientRect should return null in such cases as (0,0,0,0) actually means something different. Is there a good reason for that?

Edited/Additional Question:
Thanks istos for pointing out that returning null may break some unsuspecting code, such as:
console.log(clientRectObject.height);
// TypeError: Cannot read property 'height' of null

Not to complain about the current behavior, but as a design question: instead of null, can returning some illegal Rect values (such as negative width and height) be a more useful alternative?

A:

First I would look into how popular libraries like jQuery solve a similar problem. Here are some links to jQuery's source:

https://github.com/jquery/jquery/blob/master/src/css/var/isHidden.js
https://github.com/jquery/jquery/blob/master/external/sizzle/dist/sizzle.js#L715
https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

Further more I would search online for any clues including MDN:

https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
http://www.nczonline.net/blog/2008/02/04/getting-element-dimensions-a-follow-up
http://ejohn.org/blog/getboundingclientrect-is-awesome
http://www.quirksmode.org/blog/archives/2008/02/the_cssom_view.html#link5

Unfortunately the best way to check if the behavior of getBoundingClientRect is the same in most Browsers is to actually test inside those Browsers. If you do this, please go back to MDN and add your findings.

I feel like getBoundingClientRect should return null in such cases

Although returning null would seem logical in such cases, it isn't actually ideal because normally it returns a ClientRect object with top, right, bottom, left, width, and height properties, and code like this would break:
console.log(clientRectObject.height);
// TypeError: Cannot read property 'height' of null

In other words, the API wouldn't be consistent that way.


Q:

Rounded corners on table cells

I'm pretty sure the answer to this is 'no' but I'll ask it nevertheless.
I'm designing a form in InDesign (the kind of thing you might get from a bank, a big light grey box, with white spaces to indicate areas that need to be filled out). I want to make the white spaces have slightly rounded corners, but ideally I'd like to build this as a table.
Is there a (hacky) way to give the cells of an InDesign table rounded corners?

A:

Yes, sort of. You can place a textbox inside the table and round that. The technique is a bit tedious but I'm sure somebody has written a script to manage this, if not one could be made.

Image 1: Table with textboxes that have rounded corners


Q:

Chrome Extension: Background.js values get erased/reset?

I declare a global variable in my background.js for my Chrome extension.
I  find that at various points in time it gets reset, as if background.js were run again, and sometimes it is actually NULL when I attempt to use it from within my Popup (but not always). I haven't been able to pinpoint exactly when this reset or loss occurs.
Has anyone noticed similar inconsistent behavior with global Background vars in Chrome extensions?

A:

The answer is that I had the following in my manifest.json:
 "background": { "persistent": false }

When I changed it to TRUE, it started working. For more info, see this link provided by Rob W.:
https://developer.chrome.com/extensions/event_pages


Q:

meaning of phrase "what the Meno wrought"

I am trying to read The Mind's New Science: A History of the Cognitive Revolution by Howard Gardner. The title of chapter 1 is "Introduction: What the Meno Wrought". I don't understand what the chapter title means. The chapter also has, as an epigram, this quotation from Plato's dialogue, the Meno, that I don't understand:

One thing I would fight for to the end, both in word and deed if I were able—that if we believed that we must try to find out what is not known, we should be better and braver and less idle than if we believed that what we do not know it is impossible to find out and that we need not even try.

Could you explain these sentences a little for me, please?

A:

It isn't obvious unless you consult a dictionary, but Merriam-Webster's Eleventh Collegiate Dictionary (2003) reports that wrought is a form of the verb work:

wrought past and past part[iciple] of WORK

So discussing what Plato's Meno wrought amounts to discussing the effects that this dialogue worked (or had) on subsequent philosophy and ideas about the human mind and spirit.
In the included quotation from Meno, the character Socrates asserts that philosophers and others must maintain a spirit of inquiry (what Aristotle later describes as the "desire to know"), and he implies that accepting as a fundamental reality of human existence that we can never know anything with certainty leads to an impoverished, fearful, and idle intellectual life.


Q:

How to access c++ object methods from inside vector with SWIG Python

I have two C++ classes:  Foo and Bar.  The constructor for Foo looks like this:
Foo(std::vector<Bar *> * bars);

The constructor for Bar and one of its member functions are the following:
Bar(int data)
int getData()

In my interface file I have:
%module mySwig
%{
#include "Foo.h"
#include "Bar.h"
#include <vector>
%}

%include "Foo.h"
%include "Bar.h"
%include "std_vector.i"
namespace std {
    %template(VectorOfBars) vector<Bar *>;
}

So then in python I do the following:
import mySwig
myBar = mySwig.Bar(5)

And now I need to create a std::vector<Bar *> * object to pass into the Foo constructor, so I try the following:
vector = mySwig.VectorOfBars()
vector.push_back(myBar)

To test if this was successful I try:
print vector
print vector[0]
print vector[0].getData()

If the result of the third print out is still "5" then it was successful, but instead I get what I'm assuming is a pointer value instead
<mySwig.VectorOfBars; proxy of <Swig Object of type 'std::vector< Bar *,std::allocator< Bar * > > *' at 0xb6a9c4d0> >
<mySwig.Bar; proxy of <Swig Object of type 'std::vector< Bar * >::value_type' at 0xb6a9c3b0> >
3069958048

What am I doing wrong?  How can I create the vector of Bar pointer objects that I need to pass in to make a Foo object?  Why am I getting a pointer value back instead of the actual value?

A:

I figured it out!  The problem was that the type <mySwig.Bar; proxy of <Swig Object of type 'std::vector< Bar * >::value_type' at 0xb6a9c3b0> > translates to a Bar * and not a Bar object.  Normally SWIG handles pointers for you but in this case it didn't so when I called a method on the Bar * object it gave me back bogus data.
In reality this is exactly what I needed to pass to the Foo constructor.  I was just mistaken in thinking that SWIG would automatically dereference the pointer to Bar so that I could access its data attribute.  When I changed the template declaration from
%template(VectorOfBars) vector<Bar *>;

to the line
%template(VectorOfBars) vector<Bar>;

then I was able to access data but then it was incorrect for passing to Foo's constructor.  I had it right all along.


Q:

Is it possible to use javascript popup to accept input in php

Is it possible to use javascript popup to accept input in PHP
<script type="text/javascript">
<!--

function popup(){
var answer = prompt ("What is your name ?","")

    return answer
}
// -->
</script>

<?php

$value = echo "popup()"; // error

?>

A:

Yes, but probably not how you expect it to.
In your code, the PHP will be executed on the server before the page is sent to the browser. The popup() function will only be executed after the page loads and the user enters the input.
If you take input via a JS prompt, you'll have to make a synchronous or asynchronous request to a PHP page on the server.
Check the jQuery ajax page for examples.


Q:

Jquery Event handler not working when calling from page

I have written an event to save the data in a widget.js file & the handler is on the page. There is no error or exception is coming but the handler is not getting called. Please help.
Widget.js :
   (function ($, undefined) {
    $.widget('ui.discussionwidget', {
        options: {
            userID: 'arti.agarwa',
            title: "",
            width: "",
            containerClass: ".ui-content-gutter"
        },
saveData: function (userName, msg, parentID) {
            //Save Discussion History
            $.event.trigger({
                type: "sendMessage",
                userName: userName,
                message: msg,
                parentID: parentID,
                timeStamp: new Date()
            });

        },
        });})(jQuery);

Page Script :
$(document).ready(function () {
        $('#discussionwidget').live("sendMessage", sendMessageHandler);
                // sendMessage event handler
                function sendMessageHandler(e) {
                    debugger;
                    alert(1);
                }});

A:

Looks like event delegation is not working fine with global events
$('#discussionwidget').on("sendMessage", sendMessageHandler);

Demo: Fiddle


Q:

Add existing leaflet polygons to an existing leaflet layer

I have a bunch of polygons which are stored in a database. I would like to add them to the map in such a way that they can be edited using the leaflet-draw toolbar. Although, now the polygons get added to the map, I am unable edit them.
I think this is because they are not added to the layerGroup() to which newly drawn shapes are added.
Please help.

A:

You have to add your polygons to the featureGroup drawnItems ! Let's say,
    var polyLayers = dbArray;

is your database array with polygons. First create a feature group with your drawn items:
    var drawnItems = new L.FeatureGroup();

and add it to the map:
    map.addLayer(drawnItems);

Then you simply need to iterate over your polygons from your database and add them to the drawnItems FeatureGroup:
    for(layer of polyLayers) {
        drawnItems.addLayer(layer);
    };

Now the layers are added to the map and editable.
Here goes an EXAMPLE:
    var drawnItems = new L.FeatureGroup();
    map.addLayer(drawnItems);

    var polyLayers = [];

    var polygon1 = L.polygon([
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047]
    ]);
    polyLayers.push(polygon1)

    var polygon2 = L.polygon([
        [51.512642, -0.099993],
        [51.520387, -0.087633],
        [51.509116, -0.082483]
    ]);
    polyLayers.push(polygon2)

    // Add the layers to the drawnItems feature group
    for(let layer of polyLayers) {
        drawnItems.addLayer(layer);
    }


Q:

SQL Migration of Databases

I'm running SQL Server 2008 R2, I have a test database that I've modified to have new foreign keys and columns etc.
I was wondering what is the best way to map all of the changes to my live db?
Do I have to run a drop and create script individually on each table?
I tried to right click -> tasks -> generate database scripts -> but this gets a lot of errors when I run this.

A:

The best way to compare databases and apply changes from one to the other (in your case test to production) is to use SSDT (SQL Server Data Tools).
With this tool you can easyly compare tow databases, source and target, see the necessary scripts to update each object of the target database, so that it's exactly like the source database, and run all, or only the selected scripts to the target database.
You can also generate an update script, or a dac pac.
Please, see this for more information:

SQL Server Data Tools.
How to: Use Schema Compare to Compare Different Database Definitions
SSDT Schema Compare (youtube video)


Q:

woff font MIME type on live server error

I have an asp.net MVC 4 website where I'm using woff font. Everything works fine when running on VS IIS. However when I uploaded the pate to 1and1 hosting (live server) I get the following:

NetworkError: 404 Not Found -
  http://www.com/Content/font/fontawesome-webfont.woff?v=3.2.1

When I include this in my web.config (as some suggest) my web application stops working completely and load indefinitely.
    <staticContent>
        <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
    </staticContent>

what am I doing wrong?

A:

Have you tried removing the mapping before adding a new one in your web.config?
For Example:
<configuration>
   <system.webServer>
        ...
        <staticContent>
           <remove fileExtension=".woff" />
           <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
        </staticContent>