text:
Q: Create random values in dataframe with different weights by condition I have been trying to create a simulated dataframe with the sex and education as features, generating the data according to some proportions I already know.
Something like this:
weight_sex = [0.55, 0.45]
options_sex = [0, 1] # 0 = Men, 1 = Women

weight_educ = [0.6, 26.8, 23.6, 23.6, 24.1, 1.3]

options_educ = [0, 1, 2, 3, 4, 5] # 0 = None, 5 = Bachelor or more

sex = pd.Series(random.choices(options_sex, weights = weight_sex, k = 100), name = 'sex')
education = pd.Series(random.choices(options_educ, weights = weight_educ, k = 100), name = 'education')
people = pd.concat([sex, education], axis = 1)

Now I want to create a new column which will say if the person is unemployed, has an informal work or has a formal work. I know this proportions to be different depending on the features of the population, to make it simple let's say males with education higher than 3 have a better occupation rate then the rest of the population.
Something like this:
Option_work = [0, 1, 2] # 0 = Unemployed, 1 = informal work, 2 = formal work
weight_work_educated_man = [0.2, 0.3, 0.5]
weight_work_other_people = [0.3, 0.4, 0.3]

So if I say
people['sex'] == 0 & people['education'] > 3 generate the value with the weight_work_educated_man
And if I say
people['education'] <= 3 generate the value with the weight_work_other_people
How can I create a new column randomizing the data with the weights I have but with the features of the row as condition? I've been trying to find a way with random.choice or the sample function from pandas but got stuck. It is important to be randomized so the results don't be exactly the same the next time I run the code.

A: Expanding on your code you can do this:
options_work = [0, 1, 2] # 0 = Unemployed, 1 = informal work, 2 = formal work
weight_educ = [0.2, 0.3, 0.5]
weight_other = [0.3, 0.4, 0.3]

# create two dataframes for both choices «educated» and «other»
work_educ = pd.DataFrame(random.choices(options_work, weights=weight_educ, k=100), columns=['work'])
work_other = pd.DataFrame(random.choices(options_work, weights=weight_other, k=100), columns=['work'])

# create new column «work» and fill with data from one choice
people["work"] = work_other

# filter dataframe on your condition and replace values in column with values from other choice
people.loc[(people.sex==0) & (people.education>3), "work"] = work_educ
people.head()

Print out:
    sex     education   work
0   1       1           1
1   1       4           1
2   1       4           0
3   0       1           2
4   0       4           0


text:
Q: What is the correct If P, then Q translation of In order for A, there must be B? Not sure how to do this translation. For example:
1) In order for you to succeed, you must be determined.
I think this would translate to
1') If you are not determined, then you will not succeed.
Is this correct?

A: Yes, that is correct.
In general, if $P$ is a necessary condition for $Q$, then we have that $\neg P \rightarrow \neg Q$ which by contraposition is equivalent to $Q \rightarrow P$ ... which is just the reverse from $P \rightarrow Q$, which is what we get if $P$ is a sufficient condition for $Q$.
When it says that something $P$ has to be true "in order for" $Q$ to be true, then that is saying that $P$ is a necessary condition for $Q$.
In this case, we are told that you must be determined in order to succceed, and so being determined is a necessary condition for succeeding, meaning indeed that if we are not determined, we won't succeed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Executing Python Script from C++ program in Windows XP I am attempting to execute a python script from a C++ program. The problem that I am having is that I am unable to execute my python script.
If I take out the lpParameter value by setting it equal to NULL everything works fine, my program launches the python terminal and then my program finishes when I exit the python terminal.
I have a feeling that it has to do with the lpParameters field separating arguments with spaces, so I attempted to the entire python script in escaped quotation marks.
#include "windows.h"
#include "shellapi.h"
#include <iostream>

using namespace std;

int main()
{
    cout<<"About to execute the shell command";

    SHELLEXECUTEINFO shExecInfo;
    shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    shExecInfo.fMask = NULL;
    shExecInfo.hwnd = NULL;
    shExecInfo.lpVerb = "runas";
    shExecInfo.lpFile = "C:\\Python25\\python.exe";
    shExecInfo.lpParameters = "\"C:\\Documents and Settings\\John Williamson\\My Documents\\MyPrograms\\PythonScripts\\script.py\"";
    shExecInfo.lpDirectory = NULL;
    shExecInfo.nShow = SW_NORMAL;
    shExecInfo.hInstApp = NULL;
    ShellExecuteEx(&shExecInfo);

    return 0;
}

What happens when I launch this code is my program runs, quickly pops up another terminal that is quickly gone and then my original terminal says the task is complete. In reality though the python script that I specified is never executed.

A: Not really an answer, but too long for a comment.
The problem with those kind of execution in a new window, it the as soon as the program has ended the window is closed. As a window has been opened, it is likely from the point of view of the launching program all is fine.
My advice here would be to use a cmd /k that forces a window to keep opened after the end of the program :
shExecInfo.lpFile = "cmd";
shExecInfo.lpParameters = "/k C:\\Python25\\python.exe \"C:\\Documents and Settings\\John Williamson\\My Documents\\MyPrograms\\PythonScripts\\script.py\"";

At least if there is an error anywhere, you will be given a chance to see it.

A: Turns out the issue was with permissions and setting this parameter:
shExecInfo.lpVerb = "runas";

Instead I left it
shExecInfo.lpVerb = NULL;

and also filled in the directory parameter and it is working now.


text:
Q: How to prove $\int_{0}^{-1} \frac{\operatorname{Li}_2(x)}{(1-x)^2} dx=\frac{\pi^2}{24}-\frac{\ln^2(2)}{2} $ $\def\Li{\operatorname{Li}}$
I wonder how to prove:
$$
\int_{0}^{-1} \frac{\Li_2(x)}{(1-x)^2} dx=\frac{\pi^2}{24}-\frac{\ln^2(2)}{2}
$$
I'm not used to polylogarithm, so I don't know how to tackle it. So any help is highly appreciated.

A: The basic idea behind most polylogarithmic integrals is integration by parts. Note that we have the indefinite integral,
$$\int\frac{1}{(1-x)^2}\,\mathrm{d}x=\frac{1}{1-x}+\color{grey}{constant}.$$
And the derivative of the dilogarithm is of course:
$$\frac{d}{dx}\operatorname{Li}_{2}{\left(x\right)}=-\frac{\ln{\left(1-x\right)}}{x}.$$
Thus, integration by parts can transform this polylog integral into an integral with just ordinary logarithms and rational functions, which can be evaluated by the usual methods such as partial fractions::
$$\begin{align}
\int_{-1}^{0}\frac{\operatorname{Li}_{2}{\left(x\right)}}{(1-x)^2}\,\mathrm{d}x
&=\left[\frac{\operatorname{Li}_{2}{\left(x\right)}}{1-x}\right]_{-1}^{0}+\int_{-1}^{0}\frac{\ln{\left(1-x\right)}}{x(1-x)}\,\mathrm{d}x\\
&=-\frac{\operatorname{Li}_{2}{\left(-1\right)}}{2}+\int_{-1}^{0}\frac{\ln{\left(1-x\right)}}{x(1-x)}\,\mathrm{d}x\\
&=-\frac{\operatorname{Li}_{2}{\left(-1\right)}}{2}+\int_{-1}^{0}\frac{\ln{\left(1-x\right)}}{x}\,\mathrm{d}x+\int_{-1}^{0}\frac{\ln{\left(1-x\right)}}{1-x}\,\mathrm{d}x\\
&=-\frac{\operatorname{Li}_{2}{\left(-1\right)}}{2}+\left[-\operatorname{Li}_{2}{\left(x\right)}\right]_{-1}^{0}+\left[-\frac12\ln^2{\left(1-x\right)}\right]_{-1}^{0}\\
&=-\frac{\operatorname{Li}_{2}{\left(-1\right)}}{2}+\operatorname{Li}_{2}{\left(-1\right)}+\frac{\ln^2{\left(2\right)}}{2}\\
&=\frac{\operatorname{Li}_{2}{\left(-1\right)}}{2}+\frac{\ln^2{\left(2\right)}}{2}\\
&=-\frac{\pi^2}{24}+\frac{\ln^2{\left(2\right)}}{2}.\\
\end{align}$$

A: $\def\Li{{\rm{Li}}_2}$Set $x\mapsto -x$ followed by integration by parts, we have
\begin{align}
\int_0^{-1}\frac{\Li(x)}{(1-x)^2}\,dx&=-\int_0^{1}\frac{\Li(-x)}{(1+x)^2}\,dx\qquad\Rightarrow\qquad u=\Li(-x)\,\,\mbox{and}\,\,dv=\frac{1}{(1+x)^2}\\
&=\left.\frac{\Li(-x)}{1+x}\right|_0^{1}+\int_0^{1}\frac{\ln(1+x)}{x(1+x)}\,dx\\
&=-\frac{\pi^2}{24}+\int_0^{1}\frac{\ln(1+x)}{x}\,dx-\int_0^{1}\frac{\ln(1+x)}{1+x}\,dx\\
&=-\frac{\pi^2}{24}-\Li(-x)\bigg|_0^{1}-\frac{1}{2}\ln^2(1+x)\bigg|_0^{1}\\
&=\frac{\pi^2}{24}-\frac{\ln^22}{2}
\end{align}


text:
Q: How to convert Byte array to ByteArrayOutputStream I need to convert a byte array to ByteArrayOutputStream so that I can display it on screen.

A: byte[] bytes = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.write(bytes, 0, bytes.length);

Method description:

Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

A: You can't display a ByteArrayOutputStream.  What I suspect you are trying to do is
byte[] bytes = ...
String text = new String(bytes, "UTF-8"); // or some other encoding.
// display text.

You can make ByteArrayOutputStream do something similar but this is not obvious, efficient or best practice (as you cannot control the encoding used)

A: With JDK/11, you can make use of the writeBytes(byte b[]) API which eventually calls the  write(b, 0, b.length) as suggested in the answer by Josh.
/**
 * Writes the complete contents of the specified byte array
 * to this {@code ByteArrayOutputStream}.
 *
 * @apiNote
 * This method is equivalent to {@link #write(byte[],int,int)
 * write(b, 0, b.length)}.
 *
 * @param   b     the data.
 * @throws  NullPointerException if {@code b} is {@code null}.
 * @since   11
 */
public void writeBytes(byte b[]) {
    write(b, 0, b.length);
}

The sample code would simply transform into --
byte[] bytes = new byte[100];
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.writeBytes(bytes);


text:
Q: Dynamically naming log4j log file - Works, but not without exception from setFile() I have a program that runs for individual customers.  Each customer has an account code (we call it a start code).  The account code is communicated to the program via a commandline parameter.  I'm getting the following exception thrown back at me, which by the way, doesn't cause a program crash, it goes happily on its way.  I want to separate the logging by customer account, which seems to be working.  My log file will get created to "Balancer_990004.log" and log messages certainly build up to the point of Balancer_990004.log.7 being created, BUT, not without this exception.  Scratching my head on this one.  I've included log4j.properties bits and bits of code.
log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException:  (A file or directory in the path name does not exist.)
 at java.io.FileOutputStream.openAppend(Native Method)
 at java.io.FileOutputStream.<init>(FileOutputStream.java:203)
 at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
 at org.apache.log4j.FileAppender.setFile(FileAppender.java:294)
 at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:207)
 at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:165)
 at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307)
 at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:172)
 at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:104)
 at org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:809)
 at org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:735)
 at org.apache.log4j.PropertyConfigurator.parseCatsAndRenderers(PropertyConfigurator.java:639)
 at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:504)
 at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:547)
 at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:483)
 at org.apache.log4j.LogManager.<clinit>(LogManager.java:127)
 at java.lang.J9VMInternals.initializeImpl(Native Method)
 at java.lang.J9VMInternals.initialize(J9VMInternals.java:200)
 at org.apache.log4j.Logger.getLogger(Logger.java:117)
 at Balancer.<init>(Balancer.java:292)
 at Balancer.main(Balancer.java:2370)

*** Sample bit from log4j.properties.  The name of the Java program in question is "Balancer" ***

log4j.rootLogger=debug, devnull
log4j.logger.Balancer=info, BalancerLog

log4j.appender.BalancerLog=org.apache.log4j.RollingFileAppender
log4j.appender.BalancerLog.File=${balancer.log}
log4j.appender.BalancerLog.MaxFileSize=10000KB
log4j.appender.BalancerLog.MaxBackupIndex=10
log4j.appender.BalancerLog.layout=org.apache.log4j.PatternLayout
log4j.appender.BalancerLog.layout.ConversionPattern=%5p %d [%t] (%F:%L) - %m%n

*** How I'm building my log filename and initializing the Logger ***

public class Balancer {
    static Logger log = null;
    ....

// In constructor...

StringBuilder logName = new StringBuilder("Balancer_");
logName.append(startCode.toString());
logName.append(".log");

// Hopefully in log4j.properties our appender section contains this line:
// log4j.appender.BalancerLog.File=${balancer.log}.  This ${} bit means to get a system property to set the log file
// name.  We set that system property here, then initialize the Logger object.
System.setProperty("balancer.log", logName.toString());

// This is line 292 in the exception trace.
log = Logger.getLogger(Balancer.class);

A: If you can switch to logback, I suggest you use SiftingAppender instead.  This kind of tweaking with log4j is unnatural.

A: I found out why I was getting the exception from setFile().  Maybe this isn't supported in the .properties log4j configuration and I have to use the XML method, but if I set a ".File" property with the recommended syntax for using a system property, I get the error (even though it goes ahead and works anyway).  For instance:
log4j.appender.BalancerLog=org.apache.log4j.RollingFileAppender
log4j.appender.BalancerLog.File=${balancer.log}
log4j.appender.BalancerLog.MaxFileSize=10000KB
log4j.appender.BalancerLog.MaxBackupIndex=10
log4j.appender.BalancerLog.layout=org.apache.log4j.PatternLayout
log4j.appender.BalancerLog.layout.ConversionPattern=%5p %d [%t] (%F:%L) - %m%n

Gives me the error.  Go back to the standard:
log4j.appender.BalancerLog=org.apache.log4j.RollingFileAppender
log4j.appender.BalancerLog.File=Balancer.log
log4j.appender.BalancerLog.MaxFileSize=10000KB
log4j.appender.BalancerLog.MaxBackupIndex=10
log4j.appender.BalancerLog.layout=org.apache.log4j.PatternLayout
log4j.appender.BalancerLog.layout.ConversionPattern=%5p %d [%t] (%F:%L) - %m%n

and "alle ist klar herr kommissar".  So, I am using this code block for the moment until I work out a better solution.  For the moment the configuration will rely on the appender name for this program being "BalancerLog".
// We are dynamically building the name of our log file, if the log4j.properties file is set correctly.
// Should look like "Balancer_997232.log" or any other startcode.  Log file will be created in whatever the current
// IFS directory is when the job gets kicked off.
StringBuilder logName = new StringBuilder("Balancer_");
logName.append(startCode.toString());
logName.append(".log");

// This isn't perfect I guess and am sure it will see revisions in the future.
// What I'm doing here is asking the log object if it has an appender called BalancerLog. Look in
// the log4j.properties file.  You should see a line similiar to :
// log4j.logger.Balancer=info, BalancerLog
// We're getting the the appender object and setting it's file name to be what was built above.
// We don't want to use the default log file name.  You'll see it in the log4j.properties file like:
// log4j.appender.BalancerLog.File=Balancer.log
try {
    Appender appender = log.getAppender("BalancerLog");
    if (appender != null && appender instanceof org.apache.log4j.FileAppender) {
        FileAppender roll = (FileAppender) appender;
        roll.setFile(logName.toString());
        roll.activateOptions();
    }
}
catch (Exception e) {
    System.out.println(e);
}

Feel free to pick this apart and make any suggestions.  BTW, using log4j 1.2 here.

A: It looks like you're trying to access the log before the environment variable is set.
This code will fail without making a single log call:
class Whatever {
    private static Logger log = Logger.getLogger(Whatever.class)
    public Whatever() {
        System.setProperty("balancer.log","C:\\log.txt")
    }
}

So do this:
class Whatever {
    private static Logger log = null
    public Whatever() {
        System.setProperty("balancer.log","C:\\log.txt")
        log = Logger.getLogger(Whatever.class)
    }
}

The basic idea is not to do anything at all with the logging system before the environment variables are set correctly.


text:
Q: Difference between fgets and fscanf? I have a question concerning fgets and fscanf in C. What exactly is the difference between these two? For example:
char str[10];
while(fgets(str,10,ptr))
{
counter++;
...

and the second example:
char str[10];
while(fscanf(ptr,"%s",str))
{
counter++;
...

when having a text file which contains strings which are separated by an empty space, for example: AB1234 AC5423 AS1433. In the first example the "counter" in the while loop will not give the same output as in the second example. When changing the "10" in the fgets function the counter will always give different results. What is the reason for this?
Can somebody please also explain what the fscanf exactly does, how long is the string in each while loop?

A: fgets reads to a newline.  fscanf only reads up to whitespace.

A: In your example, fgets will read up to a maximum of 9 characters from the input stream and save them to str, along with a 0 terminator.  It will not skip leading whitespace.  It will stop if it sees a newline (which will be saved to str) or EOF before the maximum number of characters.
fscanf with the %s conversion specifier will skip any leading whitespace, then read all non-whitespace characters, saving them to str followed by a 0 terminator.  It will stop reading at the next whitespace character or EOF.  Without an explicit field width, it will read as many non-whitespace characters as are in the stream, potentially overruning the target buffer.
So, imagine the input stream looks like this:  "\t abcdef\n<EOF>".  If you used fgets to read it, str would contain "\t abcdef\n\0".  If you usedfscanf, str could contain "abcdef\0" (where \0 indicates the 0 terminator).

A: fgets read the whole line. fscanf with %s read a string, separate by space (or \n,\t,etc...).
Anyway, you should not use them unless you sure that the array you read to is big enough to contain the input.
You wrote When changing the "10" in the fgets function the counter will always give different results. Note that fgets and scanf don't know how much bytes to read. you should tell them. changing the "10" just enlarge the buffer these functions write to.

A: The function fgets read until a newline (and also stores it). fscanf with the %s specifier reads until any blank space and doesn't store it...
As a side note, you're not specifying the size of the buffer in scanf and it's unsafe. Try:
fscanf(ptr, "%9s", str)


text:
Q: Flex style inheriting issue when module include a chart I meet a problem when migrate the application for flex 3.5 to flex 4.5. The char style cannot be apply correctly when set the style in application, it still use columnChart default style. But when I move the fx:Style declaration to ColumnchChartModule, the char style works. Could someone help me to explain why the style inheriting is broken?
BTW: the button style seems working, when I define a button style in application.
Below is my test code:

           xmlns:s="library://ns.adobe.com/flex/spark"

           xmlns:mx="library://ns.adobe.com/flex/mx">

<fx:Style>

    @namespace s "library://ns.adobe.com/flex/spark";

    @namespace mx "library://ns.adobe.com/flex/mx";

    .c01 {

        fill: #0D7393;

        areaFill: #0D7393;

    }

    .c02 {

        fill: #A1B26B;

        areaFill: #A1B26B;

    }

    .c03 {

        fill: #C4843D;

        areaFill: #C4843D;

    }

    .c04 {

        fill: #5A4736;

        areaFill: #5A4736;

    }

    .c05 {

        fill: #994C34;

        areaFill: #994C34;

    }

    .c06 {

        fill: #649DA2;

        areaFill: #649DA2;

    }

    .c07 {

        fill: #D66D2B;

        areaFill: #D66D2B;

    }

    .c08 {

        fill: #C8E8B0;

        areaFill: #C8E8B0;

    }

    .c09 {

        fill: #6BB9D3;

        areaFill: #6BB9D3;

    }

    mx|ColumnChart {

        chartSeriesStyles: c01, c02, c03, c04, c05, c06, c07, c08, c09;

    }

    s|Button{

        color: red;

    }

</fx:Style>

<s:layout>

    <s:VerticalLayout />

</s:layout>

<mx:ModuleLoader url="ColumnChartModule.swf" width="100%" height="100%"/>

---------------------------------------- ColumnChartModule.mxml

       xmlns:s="library://ns.adobe.com/flex/spark"

       xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%">

    <fx:Script><![CDATA[

        import mx.collections.ArrayCollection;

        [Bindable]

        public var expenses:ArrayCollection = new ArrayCollection([

            {Month:"Jan", Revenue:1200, Expenses:500},

            {Month:"Feb", Revenue:1200, Expenses:550},

            {Month:"Mar", Revenue:1240, Expenses:475},

            {Month:"Apr", Revenue:1300, Expenses:600},

            {Month:"May", Revenue:1420, Expenses:575},

            {Month:"Jun", Revenue:1400, Expenses:600},

            {Month:"Jul", Revenue:1500, Expenses:600},

            {Month:"Aug", Revenue:1600, Expenses:750},

            {Month:"Sep", Revenue:1600, Expenses:735},

            {Month:"Oct", Revenue:1750, Expenses:750},

            {Month:"Nov", Revenue:1800, Expenses:800},

            {Month:"Dec", Revenue:2000, Expenses:850}

        ]);

        private function onClick(): void{

            var columnChart:CSSStyleDeclaration = this.styleManager.getStyleDeclaration("mx|ColumnChart");

            var columnChart1:CSSStyleDeclaration = this.styleManager.getMergedStyleDeclaration("mx|ColumnChart");

            var columnChart2:CSSStyleDeclaration = this.styleManager.getStyleDeclaration("s|Button");

            trace(columnChart);

            trace(columnChart1);

            trace(columnChart2);

        }

    ]]></fx:Script>

<s:layout>

    <s:VerticalLayout/>

</s:layout>

<s:Button label="GetChartStyle" click="onClick()" />

<s:Panel title="Floating Column Chart">

    <s:layout>

        <s:VerticalLayout/>

    </s:layout>

    <mx:ColumnChart

        dataProvider="{expenses}"

        showDataTips="true">

        <mx:horizontalAxis>

            <mx:CategoryAxis

                dataProvider="{expenses}"

                categoryField="Month"/>

        </mx:horizontalAxis>

        <mx:series>

            <mx:ColumnSeries

                yField="Revenue"

                displayName="Revenue"/>

            <mx:ColumnSeries

                yField="Expenses"

                displayName="Expenses"/>

        </mx:series>

    </mx:ColumnChart>

</s:Panel>

A: On your module ie. MyCustomModule.mxml put this override code.
override public function get moduleFactory():IFlexModuleFactory{
 return FlexGlobals.topLevelApplication.moduleFactory;
}


text:
Q: Unit test to check for unused properties I have a function that runs through the properties of a class and replaces the keyword between two dollar signs with the same name from a template.
An example of a class:
public class FeedMessageData : IMailObject
{
    public string Username { get; private set;}
    public string SubscriptionID { get; private set; }
    public string MessageTime { get; private set; }
    public string Subject { get; private set; }

    public FeedMessageData(string username, string subscriptionID, DateTime messageTime)
    {
        this.Username = username;
        this.SubscriptionID = subscriptionID;
        this.MessageTime = messageTime.ToShortDateString();

        this.Subject = "Feed " + DateTime.Now + " - SubscriptionID: " + this.SubscriptionID;
    }
}

And this is the function to replace the template with the properties:
private string mergeTemplate(string template, IMailObject mailObject)
{
    Regex parser = new Regex(@"\$(?:(?<operation>[\w\-\,\.]+) ){0,1}(?<value>[\w\-\,\.]+)\$", RegexOptions.Compiled);

    var matches = parser.Matches(template).Cast<Match>().Reverse();
    foreach (var match in matches)
    {
        string operation = match.Groups["operation"].Value;
        string value = match.Groups["value"].Value;

        var propertyInfo = mailObject.GetType().GetProperty(value);
        if (propertyInfo == null)
            throw new TillitException(String.Format("Could not find '{0}' in object of type '{1}'.", value, mailObject));

        object dataValue = propertyInfo.GetValue(mailObject, null);

        template = template.Remove(match.Index, match.Length).Insert(match.Index, dataValue.ToString());
    }
    return template;
}

I'm looking to create a unit test that writes to the console, possible properties that aren't utilized in the template. An example would be if there wasn't a $SubscriptionID$ in the template. I've tried using PropertyInfo, which gives me the properties of the class, but how do I then use this information to check if they have already been used in the template?

A: Moq (https://github.com/moq/moq4/wiki) provides ways to verify property/method access.
Follow the tutorials on this link for more details. To verify that your properties are being consumed in your template, you can make use of the VerifyGet method, an example below:
[Fact]
public void VerifyAllPropertiesHaveBeenConsumedInTemplate()
{
    var mockMailObject = new Mock<IMailObject>();
    var template = "yourTemplateOrMethodThatReturnsYourTemplate";

    var result = mergeTemplate(template, mockMailObject.Object);

    mockMailObject.VerifyGet(m => m.Username, Times.Once);
    mockMailObject.VerifyGet(m => m.SubscriptionID, Times.Once);
    mockMailObject.VerifyGet(m => m.MessageTime, Times.Once);
    mockMailObject.VerifyGet(m => m.Subject, Times.Once);
}


text:
Q: What is the most appropriate journal for publishing a paper about data collection with QGIS and mobile equipment? I am a QGIS user, and a few months ago, we used QGIS on a PC Tablet to collect data on nesting birds on a cliff directly on the field. The principle is to have QGIS installed on a PC-Tablet with an SQL database, and with easy way to write data.
We are still work on it, and to share this example and cite this work, we would like to write a manuscript, but we don't know in which journal.
Does someone have advice as to which journal we could submit this kind of work?

A: I'd recommend deciding first who your target audience is. Are you writing it for the GIS crowd detailing technical issues of QGIS development? Or are you more interested in sharing your developed technique with folks interested in bird/nesting research?
Having decided on that, pick up set of clever keywords that define your topic and use Google Scholar or Web of Knowledge to identify journals that have already published something similar on the topic. Keep in mind that your article will be first seen by an editor, and it is her who decide about its future. Good editor takes care of it's audience and would like a piece that fits into the theme of the journal and will interest its readership.
Once you have a list of journals - you could go for the most prestigious one in your domain (that could mean rejection and resubmission to another journal) or lower this criteria and aim at less prestigious journal with hope of getting through the publishing machinery faster.
Last but not least PLOS ONE or cimilar journal could be (relatively fast, open access, but not cheapest) an option. GIS based articles seem to find their place in PLOS.

A: I can't suggest any specific journal, except to say to first look for an open-access journal option. If you can, ignore large closed-access publishers. See The Cost of Knowledge for the motivation for why one would do this.
For an extensive directory of open-access journals, see http://www.doaj.org
Another resource is Wikipedia's List of open-access journals

A: This is a clear example of QGIS use, and not development of a new tools. Right? So, you must target a journal which describe methodologies. There are generic journals for this in geoscience filed, and I have seen both type of articles (GIS use, and GIS developing) in journals. The top journals on this are:
Computer & Geosciences
GeoInformatica
Environmental Modelling & Software
All depends on the peer reviewers. So you could first present the paper in a conference, to see what the audience believe. You could also meet editors/peer-reviewers which could advise you choosing a specific journal.


text:
Q: longPress decrement crosses 0 In this code i try to reduce the number continuously upto i reach 0 through GestureDetector onTapDown and onTapUp function. This works well but while pressing long it crosses the limit 0.
In this code i try to reduce the number continuously upto i reach 0 through GestureDetector onTapDown and onTapUp function. This works well but while pressing long it crosses the limit 0.
import 'dart:async';
import 'package:flutter/material.dart';

class Container1 extends StatefulWidget {
  @override
  _Container1State createState() => _Container1State();
}

class _Container1State extends State<Container1> {
  int num = 20;
  Timer timer;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '$num',
            style: TextStyle(fontSize: 30.0),
          ),
          SizedBox(
            height: 50.0,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                onTapDown: (TapDownDetails details) {
                  print('Down');
                  if (num >= 0) {
                    timer =
                        Timer.periodic(Duration(milliseconds: 100), (timer) {
                      setState(() {
                        num--;
                      });
                    });
                  }
                },
                onTapUp: (TapUpDetails details) {
                  setState(() {
                    print('Up');
                    timer.cancel();
                  });
                },
                onTapCancel: () {
                  print('Cancel');
                  timer.cancel();
                },
                child: Container(
                  height: 50.0,
                  width: 50.0,
                  color: Colors.grey,
                  child: Icon(Icons.minimize),
                ),
              ),
              SizedBox(
                width: 50.0,
              ),
              GestureDetector(
                onTapDown: (TapDownDetails details) {
                  print('Down');
                  timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
                    setState(() {
                      num++;
                    });
                  });
                },
                onTapUp: (TapUpDetails details) {
                  setState(() {
                    print('Up');
                    timer.cancel();
                  });
                },
                onTapCancel: () {
                  print('Cancel');
                  timer.cancel();
                },
                child: Container(
                  height: 50.0,
                  width: 50.0,
                  color: Colors.grey,
                  child: Icon(Icons.add),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

A: Make the conditional.

if (num > 0) {

You are currently saying that if it is 0 num- -. That will allow it to go negative.

A: You are not stopping the timer. You can do something like this
 Timer.periodic(Duration(milliseconds: 100), (timer) {
      setState(() {
        num--;
        if(num==0){
          timer.cancel();
        }
      });


text:
Q: Add a quick Step for an item In Sharepoint 2013, I have created a quick step for a list, and it shows up just fine, but what I really want is a quickstep when the user is editing one item.  I have tried creating a "Custom Action" in Sharepoint designer and attaching it to the Edit Form Ribbon and expected it to show up in the picture below, but it doesn't   What am I missing?

A: The quick step buttons are visible when you select an item, but not in the edit form.
2013

SP Online


text:
Q: uWSGI installed from pip inside virtual env does not recognize http-auto-gzip Inside a Debian Buster Docker container, I first install python3, python3-pip, and python-venv, which lets me create a python 3.7.3 venv, using
python3 -m venv ./venv_name

which I activate in the typical way. Inside, I use
pip install uwsgi

to install uWSGI (version 2.0.19.1 in this case). I have a uwsgi.ini file which contains:
[uwsgi]
strict = true
master = true
http-auto-chunked = true
http-keepalive = 1
http-auto-gzip = true
http-timeout = 360

etc. When I attempt to start uwsgi from the command line, though:
uwsgi --ini uwsgi.ini

I get the error:
[strict-mode] unknown config directive: http-auto-gzip

What is causing this error? Some searching suggests it is related to a missing plugin, but also that the http plugin is embedded in the pip install. I've tried explicitly naming the plugin by adding
plugins = http

to the ini file, but that results in the error:
!!! UNABLE to load uWSGI plugin: ./http_plugin.so: cannot open shared object file: No such file or directory !!!

A: Based on the source code here http-auto-gzip is only available when uWSGI is compiled with the UWSGI_ZLIB flag.
You will need to have the zlib1g-dev Ubuntu package installed when you install (compile) uWSGI for that to happen.


text:
Q: Which one is better for low latency java applications? Spring boot or just spring? I am planning to create a low latency web backend application using java. I am thinking to use spring boot(probably latest version) for this since it give many features developer ready like JPA, spring-data-mongodb starter packs etc. However i am not sure if it causes issues wrt latency. Does writing a backend java application using spring boot actually affect my application latency against writing the same using spring framework(not spring boot). If you have any links with analysis please do share it.
Also what capabilities do i lose if i choose to write code using spring boot

A: As the Introducing Spring Boot documentation says:

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

That's really all Spring Boot is: It makes it easy to start new Spring Framework projects, by automatically including the appropriate dependencies, and setting up and configuring Spring features in a "good" default way, that should work for most people.
Since Spring Boot will fill in the blanks, it may slow down the startup process, but not by much, and once the Spring application has started, there is no difference vs a manually set up Spring Framework application.


text:
Q: Bison & flex linkage - yylval type I have a school project, building a compiler. There is a header file given by the course staff, "proj.h" including a struct "Node", which should be used to build the parsing tree, and a set of functions.
(That header does not include a #define for YYSTYPE to the Node type, and shouldn't be changed).
I would like to use Node* in my .lex file, such as:
yylval = makeNode(...);

definition of makeNode:
Node *makeNode(const char* type,const char* value, Node *child);

I have tried defining the YYSTYPE both in .lex file and .ypp.
.lex:
#include "proj.h"
#include "parser.tab.hpp"
#define YYSTYPE Node*

.ypp:
#include "proj.h"
#define YYSTYPE Node*

I'm compiling using g++.
It seems that the lval doesn't get the actual defintion as Node* as it should. There is a compilation error when trying to assign lval:
Invalid conversion from 'Node* {aka n*}' to 'YYSTYPE {aka int}'

Any help appreciated.


text:
Q: Same Query-method diffrent results; Can springboot or hibernate block a query if object is (incompletely) loaded in memory? I hope I can make myself clear and get to the core of the problem. So I have an app where I use Spring-boot and hibernate. I use JPA-repository interfaces for DAO.
I have an object called NameSection which is held by 7 diffrent objects.
The NameSection has 3 lists of diffrent name-objects (latin name, common name, swedish name).
When I call my service.getNameSection(30); for instance, I get diffrent results depending on where I call it. If I call it from my controller where I have an incomplete copy of the namesection it doesn't seem to want to make a query to my database even though I call my service and the getNameSection(nameSectionId); (which in turn is calling my JPA-Repositories).
Is it possible that Spring boot or Hibernate stops the query to my database because it has what it thinks is a complete NameSection in it's memory?
The method that I'm struggeling with is called when I in a form submit an object (lets say Plant-object) and want to move on to a related NameSection form.
When I submit my Plant-form I get the plant injected to my method as an modelAttribute.
In this method I get the NameSection-id and make the call service.getNameSection(nameSectionId); and it doesn't give me the complete name section. In the plant-form I do refer to the namesection so in my CommonName-list (in NameSection) I have one loaded CommonName. But there are more to collect which is why I call my service.
I kind of boiled it down to this:
If I submit Plant-form which holds NameSection.id=30 and I call service.getNameSection(30); I will get the nameSection with just the one CommonName.
If I submit another Plant-form which holds another NameSection, but I hardcoded service.getNameSection(30); and logged it anyway just as a test I do get the complete NameSection (30) and fully loaded list.
What is even more frustrating is that the NameSection works as I want for the object type Fish which also holds a NameSection. Both methods follow the exact same flow. In the method below, just replace every "plant" with "fish" and it's the same.
My suspicion is that spring or hibernate or something takes a shortcut. I tried nulling the Plant and the NameSection before calling service.getNameSection(id); as well but it just wont load a complete nameSection if I already have an incomplete copy even if it's nulled. At least this is how it seems to me. I've been stuck for days.
Calling service.getPlant(plantId); will also load the complete NameSection, but this doesn't work either in this specific method. Works fine in my editPlant-method in the same Controller-class for instance.
So, this is the method:
// Process Plant form
@RequestMapping("/processPlantForm")
public String savePlantForm(Model model,
@RequestParam("saveButt") String saveButt,
// plant holds an incomplete namesection at this point
@Valid @ModelAttribute("plant") Plant plant,
BindingResult theBindingResult){

...snipped validation...

plantService.savePlant(plant);

if (saveButt.equals("Edit NameSection")) {

   // Here is the problem section!!

NameSection nameSec =
    plantService.getNameSection(plant.getNameSection().getId());
System.out.println("common names size: " + nameSec.getCommonNames().size());

   // Hardcoded test phrase
   NameSection secNameSec = plantService.getNameSection(30);
   System.out.println("common names size: " + secNameSec.getCommonNames().size());

model.addAttribute("plant", plant);
model.addAttribute("nameSectionForm", new NameSectionForm(nameSec));
model.addAttribute("inflateNameSection", true);
    return "form/create-plant";
}

else {
    return "redirect:/listPlant";
}
}

So, going in to this method with the plant that holds the NameSection with id 30, it will in both "getNameSection(id)"-calls load the NameSection (id=30) with just one CommonName (which matches the incomplete NameSection from modelAttribute).
Going in tho this method with any other plant which does NOT hold NameSection (id=30) it will load a complete NameSection (id=30) with all related CommonNames in my "Hardcoded test phrase".
In both cases I will get all swedish names and all latin names related to the NameSection, probably  because they are both empty Lists in the incomplete NameSection from the ModelAttribute.
So, I expected plantService.getNameSection(nameSectionId); to give the same result always, for the same nameSectionId ofc. But it seems that some "smart short-cut" makes it skip a few steps if pieces are available in memory and that it in this case makes false assumptions, or is it just me?
I could perhaps create a special query to ask for the missing CommonNames, but there must be a neater way. And what's killing me is that it does work 1 out of the 7 diffrent objects that holds the namesection. Of course there should be some diffrence between them, but I just can't find it. The only diffrence I found was that I initially had "Model model" after "BindingResult theBindingResult" in the method injection. I moved it as to match the working method for fishes but it didn't make any diffrence.
I also tried adding a call to getCommonNames().size() in my service.getNameSection(id)-method to "collect Lazy-list" but it made no diffrence.
Any Pro's who got some idea what's up?

A: I didn't want to create more of a wall of text than I did, but I figured someone will want to see the working fish-method mentioned.
    @RequestMapping("/processFishForm")
    public String processFishForm(Model model,
                            @RequestParam("saveButt") String saveButt,
                            @Valid @ModelAttribute("fish") Fish fish,
                            BindingResult theBindingResult) {

    // this is the snipped validation from plant-method example above
    if (theBindingResult.hasErrors()) {
        System.out.println(theBindingResult.getAllErrors());
        return "form/create-fish";
    }

    fishService.saveFish(fish);

    if (saveButt.equals("Edit NameSection")) {
        NameSection nameSec = fishService.getNameSection(fish.getNameSection().getId());

        model.addAttribute("inflateNameSection", true);
        model.addAttribute("fish", fish);
        model.addAttribute("nameSectionForm", new NameSectionForm(nameSec););
        return "form/create-fish";
    }
    else {
        return "redirect:/listFish";
    }
}

Both the FishService and PlantService have the exact same getNameSection(id)-method and they are 100% interchangeable according to my tests.
Update
So I created a new DAO (JpaRepository-interface) for CommonNames (since I had none) and created the custom method:
List<CommonName> findByNameSection(NameSection nameSection);

Then in the service when I call for a NameSection the service will call that method aswell to make sure I get all the CommonNames. Now it works as I want it to. Except that I probably make an unnecessary query to the database to fix something else.
Update 2: I have become a bit wiser and in case somebody stumbles in with similar questions, what I was needing/looking for was a refresh method for my object. Since I use JpaRepository I googled and found the simplest way to implement a refresh-method. It was a little too complicated for me to go trough when probably noone cares, but I used this example which works fine. https://www.javabullets.com/add-entitymanager-refresh-spring-data-repositories/


text:
Q: Returning max from query I'm trying to create a query to return the file with the max version, independent of the value of the server. How could I do that?
actual table data:
server    filename    v4    date
local     code1.zip   41    0000-00-00
remote    code1.zip   39    0000-00-00
local     code1.zip   28    0000-00-00
remote    code1.zip   21    0000-00-00
local     code1.zip   32    0000-00-00
remote    code1.zip   27    0000-00-00

the query:
SELECT
    server,
    filename,
    max(v4) as v4,
    date
FROM
    table
WHERE
    date ='0000-00-00'

GROUP BY
    filename,
    server,
    date

Actual result:
server    filename    v4    date
local     code1.zip   41    0000-00-00
remote    code1.zip   39    0000-00-00

Expected result:
server    filename    v4    date
local     code1.zip   41    0000-00-00

EDIT: It's for MySQL
Thanks in advance.

A: If you just want the row with largest v4 you can use this
SELECT
    server,
    filename,
    v4,
    date
FROM
    `table`
WHERE
    date ='0000-00-00'
ORDER BY v4 DESC
LIMIT 1

to get max V4 for each filename, first you get max(v4) group by filename then INNER JOIN back with table like below
SELECT T1.server,T1.filename,T1.v4,T1.date
FROM
`table` T1 INNER JOIN
    (SELECT filename,max(v4) as maxv4
     FROM `table`
     WHERE date = '0000-00-00'
     GROUP BY filename)T2
ON T1.filename = T2.filename AND T1.v4 = T2.maxV4
WHERE date = '0000-00-00';

A: To get the the max version you only have to do:
SELECT MAX(version) FROM table

If you also want the filename (if you have another column id):
SELECT t2.filename, t2.maxver
FROM table t1 INNER JOIN
(SELECT id, MAX(version) maxver
FROM table
GROUP BY id) t2 ON t1.id=t2.id
ORDER BY t2.maxver DESC
LIMIT 1

If you also want the filename (if you haven't another column id, use filename):
SELECT t2.filename, t2.maxver
FROM table t1 INNER JOIN
     (SELECT filename, MAX(version) maxver
      FROM table
      GROUP BY filename) t2 ON t1.filename=t2.filename
      WHERE t2.maxver = (SELECT MAX(version) FROM table)

There are many ways to do it.

A: You could use this query:
Select Top 1 *
From table
Where v4 = (
SELECT
    max(v4) as v4,
FROM
    table
WHERE
    date ='0000-00-00'

GROUP BY
    v4
)


text:
Q: How to do a React Native count down with animated images? I am trying to create a react native animation with some images as a count down like this:
3 --> ease out down duration 1 second each case
2 --> ease out down
1 --> ease out down

I found a way to do this with react animatable, but the results don't convince me, and if there is a better way to do it please let me know.
I think everytime I run into a new render of the element start counting down I say to react animatable to make an iteration of 3 ease out down for each number changing the image number, this is not a natural way of solving the problem I have.
For the moment is not using redux, may be later I will add it.
The properties of the state: time, current time to begin are not being used yet.
All that I need is the effect that a count down is happening with the images I show, in a well defined animation.
I think is almost getting there, but surely there is a better way to face to this problem, any suggestion is well received, even though it is as a guide. I also tried with react-native-animate-number but no luck...
Thanks in advance
import React from 'react';
import util from '../utils.js';
import * as Animatable from 'react-native-animatable';
import {
  View,
  Dimensions,
  Image,
  StyleSheet
} from 'react-native';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

const styles = StyleSheet.create({
  mainOption: {
  },
  container: {
    width: width,
    height: height,
    flex: 1,
    justifyContent: 'center',
    flexDirection: 'column',
    alignItems: 'center'
  }
});
const timeLapse = [
              <Image source={require('../images/1.png')} key={util.uniqueId()}/>,
              <Image source={require('../images/2.png')} key={util.uniqueId()}/>,
              <Image source={require('../images/3.png')} key={util.uniqueId()}/>
];

export default class StartingGameCountDown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: props.time,
      currentTimeToBegin: props.currentTimeToBegin,
      imagePosition: 0
    };
  }
  componentWillReceiveProps(nextProps) {
    const nextImage = this.state.imagePosition + 1;
    this.setState({
      ...this.state,
      letters: nextProps.time,
      currentTimeToBegin: nextProps.currentTimeToBegin,
      imagePosition: nextImage
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <Animatable.View
               ref='countDown'
               duration={1000}
               delay={0}
               iterationCount={3}
               animation="fadeOutDown"
               style={styles.mainOption}>
          {timeLapse[this.state.imagePosition]}
        </Animatable.View>
      </View>
    );
  }
}

A: Ok after taking a look into the documentation I found out that may be using sequence and timing could be an option:
import React from 'react';
import {
  Animated,
  Text,
  View,
  Dimensions,
  Image,
  Easing,
  StyleSheet
} from 'react-native';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

let counter = 0;
const util = {
  uniqueId: () => {
    return counter++;
  }
};

const styles = StyleSheet.create({
  mainOption: {
  },
  container: {
    width: width,
    height: height,
    top: -100,
    flex: 1,
    justifyContent: 'center',
    flexDirection: 'column',
    alignItems: 'center'
  }
});
const timeLapse = [
  require('../images/1.png'),
  require('../images/2.png'),
  require('../images/3.png')
];

export default class StartingGameCountDown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: props.time,
      countDown: new Animated.Value(0),
      currentTimeToBegin: props.currentTimeToBegin,
      quantity: 3,
      sizes: [],
      duration: props.duration,
      animatedValues: [new Animated.Value(0), new Animated.Value(0), new Animated.Value(0)]
    };
  }
  animations() {
    let result = [];
    state = this.state;
    for(let i = 0; i < state.quantity; i++) {
      //Start
      result.push(Animated.timing(
            state.countDown,
            {
              toValue: 0,
              duration: 0
            }
          )
      );
      let parallel = [];
      //Animate
      for(let j = 0; j < state.quantity; j++) {
        parallel.push(
          Animated.timing(
              state.animatedValues[j],
              {
                easing: Easing.bezier(.07,.42,.85,.5),
                toValue: i === j ? 1 : 0,
                duration: i === j ? state.duration : 0
              }
            )
        );
      }
      //Stop
      parallel.push(Animated.timing(
            state.countDown,
            {
              easing: Easing.bezier(.07,.42,.85,.5),
              toValue: 1,
              duration: state.duration
            }
          )
      );

      result = [...result, Animated.parallel(parallel)];
    }
    return result;
  }
  componentDidMount() {
    Animated.sequence(this.animations()).start();
  }
  shouldComponentUpdate(nextProps, nextState) {
    //I don't to run lifecycle in any case by mistake here
    return false;
  }
  createImagesAnimated() {
    let transitionY = this.state.countDown.interpolate({
      inputRange: [0, 1],
      outputRange: [0, this.props.transition.y]
    });
    let result = [];
    //What to be Animated
    for(let i = 0; i < this.state.quantity; i++) {
      let image = this.state.animatedValues[i].interpolate({
        inputRange: [0, 0.5, 1],
        outputRange: [0, 1, 0]
      });
      result.push(
          <Animated.Image
              key={util.uniqueId()}
              source={timeLapse[i]}
              style={{
                //How to animate it
                  position: 'absolute',
                  opacity: image,
                  transform: [{
                    translateY: transitionY
                  }]
              }}
          />
      );
    }
    return result;
  }
  render() {
    return (
      <View style={styles.container}>
        {this.createImagesAnimated()}
      </View>
    );
  }
}

This would be the implementation of the component:
    <CountDownComponent
      transition={{y:200}}
      duration={5000}
    />

This solves my problem I hope to find in another moment a better solution in the future.
Here is the repo:
https://github.com/jotaoncode/CountDown


text:
Q: How to debug the SharePoint timer job I have an issue. I need to move a SharePoint external list to a custom list. After some research, I decided to use a SharePoint timer job. Not having coded in C# before all of two days ago, I immediately went looking for templates. And found two here:
Timer job for copying list items
https://gooroo.io/GoorooTHINK/Article/16938/Creating-a-Timer-Job-in-SharePoint-complete-guide/24187#.XmQiB6hKhPY
I followed the steps, and have successfully created a timer job, built it, and deployed it to the dev environment. And though it does show up in the site features, it's not doing anything.
I have two main questions:

*

*Are these the right sources to be looking at? Or is there something obviously wrong with them.

*What's the best way to debug a SharePoint timer job? Ultimately, I've got to be able to detect and fix these problems myself, and right now I've got no idea how to do that.

A: Timer job runs under different process, I.e owstimer.exe so in order to debug the timer job we need to attach the owstimer processor under debug menu of process tab in visual Studio,then we need to set the break point where you want in the code file, then press f5 in visual studio.
This is recommended in dev environment but while deploying this into the production server, the best way is to create a custom log function code and call this wherever you want in the timer job code file.
With these being said, I am not sure what is the business requirement for your scenario to go with timer job, even we can go with workflow approach... Timer job is preferred when we need something which should be executed automatically periodically based on the scheduler like every 5,10 minutes etc.
Timer job is invisible to the end user if this fails to run end user cannot re-run but workflow can be executed manually by the end user when it fails to run.


text:
Q: In which scenario should I use both "width" in % and max-width value? Reference Are you using the right CSS units?
I didn't fully understand when to use both width ( in % ) and max-width ?
Why should we use % for width ?

A: The answers are pretty straight forward, if you need something at a fixed size use pixels, if you need something to be dynamic like a navbar, use %. let's say you want the navbar content width to be 80% of the body width. it will now keep the same proportions on any screen size.
in other words, use % to make the size of an element based on its parent, and pixels to make something one fixed size
if this doesn't make sense I recommend looking at a tutorial or experimenting on your own with it


text:
Q: Difficulty connecting to MS SQL Server from Postgresql on Windows (using DBI-Link) Dear Stackoverflow Gurus,
I am having an issue connecting to MS SQL Server (2008) from PostgreSQL 9.3 on Windows. I am trying to connect through DBI-Link DBD::ODBC for Sql Server.
I would like your help on how to solve this issue, or maybe point out another way to Communicate to SQL Server from PostgreSQL on Windows.
The drivers seem to be working because when I add wrong credentials I get:
Severity: ERROR, Code: XX000, Line: 2117, Position:  ErrorMessage: DBI
 connect('Driver={SQL
 Server};Server=10.XX.YY.ZZ\MyInstance','a_user',...) failed:
 [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user
 'a_user'. (SQL-28000) at line 37. at line 35.

The Query I am using to create the connection (in Postgres) is:
UPDATE
    pg_catalog.pg_settings
SET
    setting =
        CASE WHEN 'dbi_link' = ANY(string_to_array(setting, ','))
        THEN setting
        ELSE 'dbi_link,' || setting
        END
WHERE
    name = 'search_path'
;
SELECT make_accessor_functions(
    'dbi:ODBC:Driver={SQL Server};Server=10.XX.YY.ZZ\MyInstance',
    'a_user',
    'Some_Password',
    '---
AutoCommit: 1
RaiseError: 1
',
    NULL,
    NULL,
    NULL,
    'dbo'
);

The error I get (which also looks like it did connect) is:
Severity: ERROR, Code: XX000, Line: 2117, Position:
ErrorMessage: Could not connect to database
data source: dbi:ODBC:Driver={SQL Server};Server=10.XX.YY.ZZ\MyInstance
user: a_user
password: Some_Password
dbh attributes:
---
AutoCommit: 1
RaiseError: 1

[Microsoft][ODBC SQL Server Driver][SQL Server]Changed database context to 'master'. (SQL-01000)
[Microsoft][ODBC SQL Server Driver][SQL Server]Changed language setting to us_english. (SQL-01000) at line 35.

My System:
OS: Windows 7 64-bit
PostgreSQL: 9.3
Perl: Strawberry Perl 5.14.3
Python: 3.4

Thanks


text:
Q: How to use foreach with lambda for Map> How can i use forEach with lamba for something like:
Map<Integer,Map<String,String>

i want to check if Map (this - string,string) contains key in function parameter
thanks for help ;)

A: static boolean containsInnerKey(String key, Map<Integer, Map<String, String>> map) {
    return map.values()
            .stream()
            .anyMatch(m -> m.containsKey(key));
}


text:
Q: Unexpected behavior when adding UnitVector to vector (list) The expression
{v1,v2} + UnitVector[2,x]

evaluates to
{v1 + UnitVector[2, x], v2 + UnitVector[2, x]}

but that is suddenly a list of two lists with length 2. E.g. using
{v1 + UnitVector[2, x], v2 + UnitVector[2, x]} /. x->2

evaluates to
{{1 + v1, v1}, {1 + v2, v2}}.

But I expect to stay in two dimensions when I write
{v1,v2} + UnitVector[2,x]

because clearly UnitVector[2,x] is always a two dimensional vector.
Am I doing something wrong? Can I enforce somehow that this expression stays a two dimensional vector? I can see that lists aren't necessarily vectors but it still seems strange to me to treat the UnitVector[2,x] like a constant.

A: You can use TranslationTransform[] for this:
expr = TranslationTransform[UnitVector[2, k]][{v1, v2}];

expr /. k -> 1
   {1 + v1, v2}

expr /. k -> 2
   {v1, 1 + v2}

A: You could e.g. define a function:
ClearAll[addUnit]
addUnit[vec_, x_Integer] := vec + UnitVector[x]

with this:
addUnit[{1, 1}, 1]
addUnit[{1, 1}, 2]

(* {2, 1}
{1, 2} *)

Alternatively you can as well define:
ClearAll[addUnit]
addUnit[vec_, 1] := vec + UnitVector[1]
addUnit[vec_, 2] := vec + UnitVector[2]


text:
Q: Как установить среду разработки APEX? Участник @Shelest.4VS спрашивал, как полностью удалить Apex после неуспешной установки.
А как установить среду разработки APEX и при этом избежать ошибок?
Читая официальную документацию по установке, некоторые моменты не совсем понятны. Особенно, как подготовить БД для установки. Например, стоит ли устанавливать в корневую БД (CDB), или устанавливать в новую или уже имеющуся подключаемую БД. Или, нужно ли создавать отдельное табличное пространство.
Хочется с наименьшими позаниями в администрировании БД оптимально подготовить ее к установке, провести установку, и в итоге избежать ошибок при установке. Ведь интересно же без особых временных затрат установить среду APEX, попробовать ее или начать обучение с ней.

A: На сегодня последняя версия 21.01. В основу положена оф. документация по установке.
Отличия при установки на Nix* или Win в указании путей и некоторых команд в командной строке, например: /app/apex = C:\app\apex.

*

*Скачайте последнюю версию с оф.сайта в любой каталог. На выбор, или среда только с англ. языком, или мультиязычная.

*Перейдите в ранее выбраный каталог и распакуйте архив любой программой архиватором. Затем перейдите в только что созданный каталог apex:
cd /app/
unzip -q apex_21.1.zip
cd apex

*Выполните подключение как привилигированый пользователь SYS:
# если еще не установлены; в Win команда SET
export ORACLE_SID=oracl
export ORACLE_HOME=/app/oracle/product/19.3.0/home

sqlplus -l / as sysdba

*Рекомендуемый путь - создать новую подключаемую БД и отдельноое табличное пространство:
create pluggable database pdb2 admin user pdbadmin identified by pdb$admin
    file_name_convert = ('pdbseed', 'pdb2');

alter pluggable database pdb2 open;
alter pluggable database pdb2 save state;
alter session set container=pdb2;
create tablespace apex datafile '/dbfiles/cdb193/pdb2/apex01.dbf'
    size 100m autoextend on next 1m;

*Для установки полной среды разработки выполните скрипт:
-- @apexins.sql tablespace_apex tablespace_files tablespace_temp images

@ apexins.sql apex apex temp /i/
...set_appun.sql
[много диагностических сообщений, продолж. ~20 мин.]

Будет создан лог установки, например: install2021-10-09_17-07-04.log

*Изменните ппароль администратора APEX запуском скрипта:
@ apxchpwd.sql
Enter the administrator's username [ADMIN]
User "ADMIN" does not yet exist and will be created.
Enter ADMIN's email [ADMIN]
Enter ADMIN's password []
Created instance administrator ADMIN.

*Измените пароль для общего пользователя APEX:
alter user apex_public_user identified by apex account unlock;

*Конфигурируйте RESTful службы для APEX запуском скрипта:
@ apex_rest_config.sql
Enter a password for the APEX_LISTENER user              []
Enter a password for the APEX_REST_PUBLIC_USER user              []
...set_appun.sql
...setting session environment
...create APEX_LISTENER and APEX_REST_PUBLIC_USER users

На этом установка APEX завершена. Проверить установку можно, либо коротким запросом, либо запустив скрипт проверки:
select version, status
from dba_registry where comp_id='APEX';

VERSION                        STATUS
------------------------------ -----------
21.1.0                         VALID

@ ./utilities/support/apex_verify.sql

Последний создаст в текущем каталоге файл apex_verify_out.html, который можно открыть в любом HTML просмотрщике и получить подробнейшую информацию о установленном APEX.

A: Есть вариант - развёртываниe Oracle APEX в Docker-контейнере. Очень удобно для разработчиков: нужно просто установить Docker и запустить контейнер.
Одна проблема: не существует официальных контейнеров от Oracle со сборками APEX. По крайней мере, я таких не нашёл на hub.docker.com.
Из самого удобного находил такую сборку.
Плюс:

*

*в сборке можно удобно кофигурировать разные комбинации версий БД, Апекса и других подсистем.

Минус:

*

*последняя версия в сборке (по крайней мере пока) только для версии 20.2, и не понятно, будет ли автор обновлять сборку.


text:
Q: How should I allot my attribute points as a Mage in Dragon Age: Origins? I'm starting to play Dragon Age: Origins and I want to know if there is a formula available for adding points to attributes of a Mage. For instance, every N levels, add X points to this attribute and Y to that attribute.
It looks like that Willpower and Magic are the most important ones for a Mage. But which is more important, and should I add the same to both?

A: While willpower and magic were both intended to be the primary mage stats, it didn't play out very well in practice.
Magic increases your spell power, which is definitely a great thing for mages to have.
Willpower, on the other hand, increases your mana pool and mental resistance. Mental resistance isn't all that important and can be effectively ignored. You might think having a huge mana pool would be a boon to mages, but mana potions are so incredibly cheap to make it's far more efficient to ignore willpower, stock up on mana potions, and set up a really liberal tactic slot for them (say, Self: < 50% Mana → Drink mana potion).
So, you have two options:

*

*If you want to play as BioWare probably intended it, do 2 Magic for every 1 Willpower. By the end game, your spell power will still be pretty high and you'll have a decent size mana pool.

*If you want to cheese the game and treat the game as it is, do 2 Magic for every 1 Willpower until you get to ~25 willpower. After that, dump all your points into Magic. Make sure you have someone taking the Herbalism skill, and make mana potions yourself.

A: After a little progress you will find out that there are different types of mages(healer, shapeshifter etc.)
You will definitely need willpower and magic, but try to focus on your type and add your points in the attribute that helps you unlock the higher level skills of your type.
Also whichever type you choose be sure to learn some healing spells too.


text:
Q: java spring mvc 404 not found error for sample Spring MVC I am learning spring MVC and getting the below problem.Even I am not able to run any sample application downloaded from internet as well.
I am getting 404 Not Found "Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."
I have tried the below

*

*Adding the Maven dependencies in Deployment Assembly.

*Changing the Tomcat server path.
 @Controller
 public class ControllerClass{

     @RequestMapping("hello")
     public String redirect() {

         return "Hello";
     }
 }

This is my Controller class
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd ">
  <context:component-scan base-package="com.practice.controllerclasses" />
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value=".jsp" />
  </bean>
  <mvc:resources mapping="/resources/**" location="/resources/" />
  <mvc:annotation-driven />
</beans>

is my DispatcherServletConfiguration xml file
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  <welcome-file-list>

  <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>Spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>Spring</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

is my web.xml file

I am using Eclipse JEE 2019-09 Jre1.8 and Spring 4.1
Any help is appreciated.


text:
Q: maxRequestLength is being exceeded on webservice WCF I'm having some trouble with my  webservice, the request is exceeding the max int size on my webservice I already had set the webconfig to this, but  it didn't work
<httpRuntime targetFramework="4.5.1" executionTimeout="300" maxRequestLength="2147483647" />

is there someway to set this  bigger than 2147483647 ?
Yep, I  already  checked these answers on here  but none of them  had my  solution to this  issue

A: Try to add the below configurations.
Binding configuration.
<binding name="mybinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" />

DataConstractSerializer.
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
      <behavior name="mybehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>

Don't forget to apply the configuration between the client-side and server-side (we are supposed to add this configuration on both the client-side and server-side endpoints).  Add the bindingConfiguration and behaviorConfiguration in the service section.
  <system.serviceModel>
    <services>
      <service name="WcfService2.Service1" behaviorConfiguration="mybehavior">
        <endpoint address="" binding="wsHttpBinding" contract="WcfService2.IService1" bindingConfiguration="mybinding"/>

Feel free to let me know if the problem still exists.

A: After a long search  we found this  solution setting  on webservice web.config file
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="2200000000"/>
        </requestFiltering>
    </security>
</system.webServer>


text:
Q: active class assignment in a menu with submenu JQUERY I have this code for creating a menu with submenu using a json via ajax call but I cannot assign the active class to the menu item when I am in a submenu page.

$(document).ready(function () {

  $.getJSON('../../menu2.html', function (data) {
    $.each(data, function (i, item) {

      let menu = $('#side-menu');
      $('#side-menu').metisMenu('dispose'); //For stop and destroy metisMenu

      var current_page = document.location.href.match(/[^\/]+$/)[0];

      var class_item = "";
      if (item.nomemenu == current_page) {
             var class_item = "active";
           }

      var arrow = "";
      if (item.submenu == "true") {
        var arrow = '';
      }

      var html = '
';

      html += '' +
        '' +
        '' + item.title + '' + arrow + '';

            // SubMenu
            if (item.submenu == "true") {

              html += '
';

                  //SubMenu Loop
                  $.each(item.subitems, function (i, subitem) {

                       if(subitem.link==current_page){
                         var active_link = 'active';
                       }else{ var active_link = ''; }

                   html += '
' + subitem.title + '
';

                  });

              html += '
';

            }

      html += '
';

      menu.append(html);
      $('#side-menu').metisMenu(); //For stop and destroy metisMenu

    });
  });

});

I want to assign the active class to the element that has as id "menu-subitem.nomemenu" when subitem.link = current_page .
I tried to insert the code $('# menu -' + subitem.nomemenu).addClass('active') inside the submenu loop, but i don't know whyinside that loop the jquery selector doesn't work in any way.
Do you know any alternative ways with which I can succeed in obtaining this result?


text:
Q: What is best Option to store Access Token, Refresh tokens?
*

*Platform cache :
I am using platform cache but platform cache is not returning anything after very small period of time ( approx 30 sec- 60 sec ).

*Custom Setting : Custom setting has a limitation of fields can be created max 255 character. Access tokens are more than that.

*Custom Object : Custom Object won't be good solution i think considering it's sensitive data.

*Custom Metadata : I am not sure.

Any Idea what would be the best approach?

A: If possible, use Named Credentials. You don't need to manage the Access Tokens or Refresh Tokens at all, as the platform does it for you, and securely stores the tokens in a way that's non-trivial to retrieve, even for administrators. Also, feel free to read Secure Coding: Storing Secrets for other alternatives. Custom Metadata Types is also a viable solution.


text:
Q: 'distributed=true' property doesn't seem to work with ingest from query I am performing ingest from query in the following manner:-
.append async mytable with(distributed=true) <| myquery

Since this is using 'async' , I got an OperationId to track the progress. So when I issue .show operations command against the OperationsId , I get 2 rows in the resultset. The 'State' column value for both the rows was 'InProgress'. The 'NodeId' column value for one of the rows was blank whereas for the other row it was KENGINE000001. My cluster has 10+ worker nodes. Should I be getting ~ 10 rows as a result of this command , since I am using distribute=true option? And my data load is also heavy , so it's really a candidate for distributed ingestion. So either this property is not working or I am not interpreting its usage correctly?

A:
Should I be getting ~ 10 rows as a result of this command , since I am using distribute=true option?

No

So either this property is not working or I am not interpreting its usage correctly?

likely the latter, or a false expectation from the output of .show operations, see above.
you can track the state/status of an async command using .show operations <operation_id>

*

*If it doesn't reach a final state ("Completed","Failed","Throttled", etc.) after 1hr, that's unexpected - and you should open a support ticket for that.

regardless - it's ill-advised to attempt to ingest a lot of data (multi-GBs or more) using a single command, even if it's distributed.

*

*if that's what you're attempting to do, you should consider splitting your ingestion into multiple commands, each handling a subset of the data.

*see the 'remarks' section here: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/management/data-ingestion/ingest-from-query


text:
Q: Do svg symbols work well in polymer google-map-marker? I have set out to make a Google maps application using Polymer.  But I have run into difficulties because I would like to use vector map markers rather than raster map markers.  icon="dollar_sign.png" works well.  icon="dollar_sign.svg" fails.
I see in Google's map markers documentation that there are certain things I can do to accommodate svg markers.  But I am not sure how they interact with Polymer.  I have a customer waiting for this application.  I can't afford to spend much time experimenting.
Has anyone already been down this road, and can tell me whether I will encounter roadblocks?  At this point, I can either code it using Polymer, or code it without any framework.
.........Thanks, Rick

A: Icon property could be specified using one of the following format:
1) string value, for example:  http://www.primeracoop.com/assets/pin.svg
2) google.maps.Icon object, for example:
{
    url: 'http://www.primeracoop.com/assets/pin.svg',
    anchor: { x: 25, y: 50 },
    scaledSize: { height: 50, width: 50 }
}

3) google.maps.Symbol object, for example:
{
    path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
    fillColor: '#FF0000',
    fillOpacity: .6,
    anchor: { x: 0, y: 0 },
    strokeWeight: 0,
    scale: 1
}

The following example demonstrates how to set svg icon

  google-map {
            height: 100vh;
        }
<head>
    <base href="https://polygit.org/polymer+1.6.0/components/">
    <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
    <link rel="import" href="polymer/polymer.html">
    <link rel="import" href="google-map/google-map.html">
    <link rel="import" href="google-map/google-map-marker.html">
</head>

<body>

    <google-map-svg-marker></google-map-svg-marker>

    <dom-module id="google-map-svg-marker">
        <template>

            <google-map latitude="37.77493" longitude="-122.41942">
                <google-map-marker icon="{{icon}}" latitude="37.779" longitude="-122.3892" title="Go Giants!"></google-map-marker>
            </google-map>

        </template>

        <script>
            HTMLImports.whenReady(function () {
                Polymer({
                    is: 'google-map-svg-marker',

                    ready: function () {
                        //this.icon = "http://www.primeracoop.com/assets/pin.svg";

                        this.icon = {
                            url: 'http://www.primeracoop.com/assets/pin.svg',
                            anchor: { x: 25, y: 50 },
                            scaledSize: { height: 50, width: 50 }
                        };

                        /*this.icon = {
                            path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
                            fillColor: '#FF0000',
                            fillOpacity: .6,
                            anchor: { x: 0, y: 0 },
                            strokeWeight: 0,
                            scale: 1
                        };*/
                    },

                    properties: {
                        icon: {
                            type: Object
                        }
                    }

                })

            });
        </script>

    </dom-module>

</body>


text:
Q: Clean up 'duplicate' data while preserving most recent entry I want to display each crew member, basic info, and the most recent start date from their contracts. With my basic query, it returns a row for each contract, duplicating the basic info with a distinct start and end date.
I only need one row per person, with the latest start date (or null if they have never yet had a start date).
I have limited understanding of group by and partition functions. Queries I have reverse engineered for similar date use partition and create temp tables where they select from. Ultimately I could reuse that but it seems more convoluted than what we need.
    select
Case when P01.EMPLOYMENTENDDATE < getdate() then 'Y'
else ''
end as "Deactivate",
concat(p01.FIRSTNAME,' ',p01.MIDDLENAME) as "First and Middle",
      p01.LASTNAME,
p01.PIN,
(select top 1 TELENO FROM PW001P0T WHERE PIN = P01.PIN and TELETYPE = 6 ORDER BY TELEPRIORITY) as "EmailAddress",
      org.NAME AS Vessel,
case
       WHEN c02.CODECATEGORY= '20' then 'MARINE'
       WHEN c02.CODECATEGORY= '10' then 'MARINE'
       ELSE 'HOTEL' end as "Department",
         c02.name as RankName,
               c02.Alternative RankCode,
convert(varchar, ACT.DATEFROM,101) EmbarkDate,
convert(varchar,(case when ACT.DATEFROM is null then p03.TODATEESTIMATED else ACT.DATEFROM end),101) DebarkDate

FROM   PW001P01 p01
      JOIN PW001P03 p03
           ON  p03.PIN = p01.PIN
      LEFT JOIN PW001C02 c02
           ON  c02.CODE = p03.RANK
         /*LEFT JOIN PW001C02 CCIRankTbl
           ON  CCIRankTbl.CODE = p01.RANK*/
      LEFT JOIN PWORG org
           ON  org.NUMORGID = dbo.ad_scanorgtree(p03.NUMORGID, 3)
     LEFT JOIN PWORGVESACT ACT
     ON  ACT.numorgid=dbo.ad_scanorgtree(p03.numorgid,3)

where P01.EMPLOYMENTENDDATE > getdate()-10 or P01.EMPLOYMENTENDDATE is null

I only need to show one row per column. The first 5 columns will be the same always. The last columns depend on contract, and we just need data from the most recent one.

Deactivate	First and Middle	Lastname	PIN	Email	Vessel	Department	Rank	RankCode	Embark	Debark

 	Martin	Smith	123	msmith@fake.com	Ship1	Marine	ViceCaptain	VICE	9/1/2008	9/20/2008

 	Matin	Smith	123	msmith@fake.com	Ship2	Marine	Captain	CAP	12/1/2008	12/20/2008

 	Steve Mark	Dude	98765	sdude@fake.com	Ship1	Hotel	Chef	CHEF	5/1/2009	8/1/2009

 	Steve Mark	Dude	98765	sdude@fake.com	Ship3	Hotel	Chef	CHEF	10/1/2010	12/20/2010

A: Change your query to a SELECT DISTINCT on the main query and use a sub-select for DebarkDate column:
(SELECT TOP 1 A.DATEFROM FROM PWORGVESACT A WHERE A.numorgid = ACT.numorgid ORDER BY A.DATEFROM DESC) AS DebarkDate
You can do whatever conversions on the date you need to from the result of that sub-query.


text:
Q: Cannot add or update a child row: a foreign key constraint fails while adding another foreign key I am trying to add a foreign key constraint in my table. My table structure are:
table requisition

My next table where i want to add foreign key of requisition table
requisition_approval

When i try to add a foreign key constraint with following sql query:
ALTER TABLE `requisition_approval` ADD  CONSTRAINT `requisition_id` FOREIGN KEY (`requisition_id`) REFERENCES `requisition`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

It gives following error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`proprompt`.`#sql-34e8_3d7`, CONSTRAINT `requisition_id` FOREIGN KEY (`requisition_id`) REFERENCES `requisition` (`id`))

What is the problem here and how can i solve it?

A: Error is in the requisition_approval table more specificly in the requisition_id column. You inserted id 0 which does not references any id in requisition table. Change the value to 1 and this will work :)


text:
Q: About the Mediator in Event-Driven Topology I was reading this article called Variations in event-driven architecture in which they demonstrate both the mediator and broker topologies.
According to the article the mediator topology looks somewhat like this:

The event flow starts with the client sending an event to an event queue, which is used to transport the event to the mediator. The event mediator receives the initial event and orchestrates that event by sending additional asynchronous events to event channels to execute each step of the process. Event processors, which listen on the event channels, receive the event from the even mediator and execute specific business logic to process the event [...] It is important to note that the event mediator doesn't actually perform the business logic necessary to process the initial event, rather, it knows of the steps required to process the event [...] The event channels can be either message queues o message topics.

So, I was studying this diagram, trying to understand how the mediator could determine when a given processor has finished processing a given event, such that it could orchestrate the next step of the process.
The article is not clear enough when it says

For each initial event step, the event mediator creates a processing event, sends that processing event and waits for the processing event to be processed by the corresponding event processor. This process continues until all of the steps in the initial event have been processed.

Now, the article is clear in that the communication is asynchronous, and event messages will travel through message queues, but the diagram does not show any events coming out of the event processor and back to the mediator.
The article says the mediator waits for the event processor to finish, but it is not clear how this is supposed to happen in architectural terms.
Is it asynchronous, queue-based RPC (e.g. Rabbit RPC), or is there another listener waiting for an asynchronous response somewhere?
Any thoughts on how this can be implemented from an architectural standpoint?

A: It seems to me that they just didn't draw the events returning from the event processors, perhaps because they may not specifically be events (like some sort of a callback) or because they may not be normal events (perhaps events that only go back to the mediator and are not visible to any other subscribers), depending on what you use as your mediator.  This part seems to indicate something like that:

The event mediator can be implemented in a variety of ways. Understand each implementation option to ensure that the solution you
  choose for the event mediator matches your needs.
The simplest and most common implementation of the event mediator is
  through open source integration hubs such as Spring Integration,
  Apache Camel, or Mule ESB. Event flows in these open source
  integration hubs are typically implemented through Java code or a DSL
  (domain-specific language). For more sophisticated mediation and
  orchestration, you can use BPEL (business process execution language)
  coupled with a BPEL engine such as the open source Apache ODE. BPEL is
  a standard XML-like language that describes the data and steps
  required for processing an initial event. For very large applications
  requiring much more sophisticated orchestration (including steps
  involving human interactions), you can implement the event mediator
  using a business process manager (BPM) such as jBPM.
Understanding your needs and matching them to the correct event
  mediator implementation is critical to the success of any event-driven
  architecture using this topology. Using an open source integration hub
  to do very complex business process management orchestration is a
  recipe for failure, just as is implementing a BPM solution to perform
  simple routing logic.

They mentioned Spring as a possible implementation - I've never used it, but looking at the documentation (here) I see the concept of a reply channel:

...when the service method returns a non-null value, the endpoint will attempt to send the reply message to an appropriate reply channel.

The goal is to send one or more messages off to be processed asynchronously, then to send other messages off when the results come back.  I don't think it matters too much at the pattern level exactly how those results come back (function callback, 'response' event, web API call, whatever) - that will depend on your specific infrastructure.
To me it sounds quite a bit like the Saga pattern (link).  In that, the Saga (or Mediator) knows the steps needed to complete some task and maintains some state about the progress of that task.
It fires off commands to be processed and listens for responses.  When a response (event) comes in, it updates its state, then uses its state to determine what command(s) need to be fired off next.
That continues until either A) the process is completed, or B) a step in the process fails (in which case it might reverse direction and start firing compensating commands to 'undo' the prior actions).
Using the diagram below from the post your referenced, the "thoughts" of the saga/mediator might be along the lines of...

*

*Relocation event, so fire off the Change Address command and wait.

*AddressChanged event received. Now I've changed the address, but I haven't recalced the quote or updated the claims, so I'll send those off (they don't conflict, so send them both) and wait.

*ClaimsUpdated event received.  Still need the recalc before moving forward, so keep waiting.

*QuoteRecalced event received.  Now that I've updated the address, recalced the quote, and updated the claims, I can send off the Adjust Claims command, and wait.

... and so on.
You would maybe want to add persistence (so it can pick up where it left off in case of a crash), idempotent event processors (so replay of events doesn't cause issues), and/or timeouts (to not get stuck waiting forever if a response event gets missed/lost).

A: I think you have the answer on the diagram itself:
Initial Event step (red color) is the key. Every Event Processor produces an event, which is what gets into the Event Queue and then to the Event Mediator.
The architecture is Event Driven and asynchronous. Single Event Queue handles path to the Event Mediator. And since this is the only way to get the event into the Event Mediator, obviously, anything wanting to send an event to the mediator would need to use this path.
At some point, after certain event, the Event Mediator will declare the operation as successfully complete and will not dispatch more events to the Event Processors.
Although, I must say, you are right, this is not clearly stated in the article. I assume this will be better clarified in the book they are previewing.


text:
Q: Is there a way to break into the debugger on exception in Android emulator? Assuming I didn't start in debug mode, is there a way to make the eclipse debugger automatically start if my app throws an exception inside the emulator?
Alternatively, is there a way to get a more useful error message out of the emulator (something more useful than "Sorry, your app terminated unexpectedly").

A: I don't know how to trigger the debugger, but did you look at the stack trace when the error occurred, either in Eclipse DDMS (if it was already running) or using the "adb logcat" command?
https://developer.android.com/studio/debug/index.html

A: Yes, there is a button to add a Java exception breakpoint from the Breakpoints view in the Eclipse Debug perspective. See here for further details:
http://help.eclipse.org/galileo/topic/org.eclipse.jdt.doc.user/reference/views/breakpoints/ref-addexception_viewaction.htm
The emulator is emulating a real Android device. There is little point in displaying stack traces to an end user, hence the generic message. Use the LogCat view in the DDMS perspective.

A: Looks like you can almost do this in the DDMS perspective via the "Debug Process" button. It still won't break on demand if you aren't already in debug mode.  And it's too late to debug if you're already looking at the "force close" dialog.


text:
Q: Issue using Oracle ODBC driver in Script Task in SSIS 2008 The issue I'm having may not have anything to do with SSIS but I wanted to be thorough.  I am attempting to have essentially the same code (using ODBC) accessing SQL Server, Sybase, and Oracle.  Everything except Oracle is working (not surprising) but I'm at a loss as to how to resolve this issue.
The Oracle driver is the 11.01.00.06 version. I am able to connect successfully to the instance but the call (to the function) fails.  I'm guessing the error has to do with the fact that the cursor is a parameter in this case (not true for SQL Server and Sybase) and I am not accounting for it.  There is no OdbcType for cursor though.
Any help or suggestions would be appreciated.
The error I am getting is - ERROR [07001] [Oracle][ODBC][Ora]ORA-01008: not all variables bound
Calling code (C#)
    NetworkProviderCon = new OdbcConnection(strCon);
    NetworkProviderCon.Open();
    NetworkProviderCmd.Connection = NetworkProviderCon;

    NetworkProviderCmd.CommandType = CommandType.StoredProcedure;

    NetworkProviderCmd.CommandText = "{CALL SP_NETWORK_IDL(?,?)}";

    NetworkProviderCmd.CommandTimeout = this.Variables.CADATABASECORETIMEOUT;

    //parameters to call SP
    NetworkProviderParam1 = NetworkProviderCmd.Parameters.Add("@pdtStartTime", OdbcType.DateTime);
    NetworkProviderParam1.Value = strStartDate;
    NetworkProviderParam2 = NetworkProviderCmd.Parameters.Add("@pdtEndTime", OdbcType.DateTime);
    NetworkProviderParam2.Value = strEndDate;
    sqlDr = NetworkProviderCmd.ExecuteReader();

Procedure Parameters
CREATE OR REPLACE function XXXX.SP_NETWORK_IDL
(
/*************************************************
** Declare Parameters                           **
*************************************************/

   pRESULT_CURSOR IN OUT CURSOR_PACKAGE.RESULT_CURSOR               ,
   pdtStartTime   IN     CMC_NWPR_RELATION.NWPR_TERM_DT%TYPE := NULL,
   pdtEndTime     IN     CMC_NWPR_RELATION.NWPR_EFF_DT%TYPE  := NULL
)
return number

A: Your function requests 3 parameters, but you are passing only 2.
NetworkProviderCmd.Parameters.Add
  ("@pRESULT_CURSOR", OracleType.Cursor).Direction = ParameterDirection.InputOutput;
//NetworkProviderCmd.Parameters["pRESULT_CURSOR"].Value will store your output

UPD:
MSDN: Using Parameters with an OleDbCommand or OdbcCommand
NetworkProviderParam0 = NetworkProviderCmd.Parameters.Add("@pRESULT_CURSOR", OracleType.Cursor);
NetworkProviderParam0.Direction = ParameterDirection.InputOutput;

P.S.: I can not find OdbcType for cursor
UPD2:
NetworkProviderCon = new OdbcConnection(strCon);
NetworkProviderCon.Open();

OdbcCommand NetworkProviderCmd = new OdbcCommand();
NetworkProviderCmd.CommandText = "{? = SP_NETWORK_IDL(?,?,?)}";
NetworkProviderCmd.Connection = NetworkProviderCon;
NetworkProviderCmd.CommandTimeout = this.Variables.CADATABASECORETIMEOUT;
NetworkProviderCmd.CommandType = CommandType.StoredProcedure;

//parameters to call SP
NetworkProviderCmd.Parameters.Add("pRESULT_CURSOR", OracleType.Cursor).Direction = ParameterDirection.InputOutput; //NetworkProviderParam1
NetworkProviderCmd.Parameters.Add("pdtStartTime", OdbcType.DateTime).Value = strStartDate; //NetworkProviderParam2
NetworkProviderCmd.Parameters.Add("pdtEndTime", OdbcType.DateTime).Value = strEndDate; //NetworkProviderParam3
NetworkProviderCmd.Parameters.Add("RETURN_VALUE", OdbcType.Int).Direction = ParameterDirection.ReturnValue; //NetworkProviderParam4


text:
Q: How to change Eclipse .class view without having sources I have a little problem with displaying compiled java classes. In Eclipse the view looks like this:
https://i.imgur.com/qRRtdKk.png
But in Netbeans looks like this ( better for me with compiled code message):
https://i.imgur.com/xyNdQKA.png
Is there is a possibility to change the view to look like in NetBeans?
Edit:
Without adding source ! Because I know that I can add source.


text:
Q: Find the distance between 2 stations and get all the stations that join the stations
Here is the metro Images as you can see
So what i am thinking to make a metro app so i found that how to find stations between two stations. So i found that from some answers that  djkshrtas algorithm i can get distance and station reach list of stations from one point to another. But didn't found that how can i implement it.
As my thinking i have to add all stations in different arrays account to line
const red_stations = ["Miyapur","JNTU College","KPHB",...,"L.B Nagar"]
const blue_line_stations = ["HITECH",...,"NOGOLE"]

After that i am stuck as how can i combine these lines to find station as in the djkshrtas we can work on single array. Please let me anyone can explain me and provide me a logic in the javascript.
How can i find stations between Miyapur to RTC green_line as show in the map. Thanks


text:
Q: If I provide to a function one dict two times and then del key in one of the dict, for some reason the same key are deleted in the 2nd dict. Why? Test function:
def test_dicts(first_dict, second_dict):
    print('\nbefore first_dict_:', first_dict)
    print('before second_dict:', second_dict)

    del second_dict[2]

    print('\nafter first_dict_:', first_dict)
    print('after second_dict:', second_dict)

Test data:
dicts = {1: {11:11}, 2: {22:22}}

Lets test:
>>> tmp.test_dicts(dicts, dicts)

before first_dict_: {1: {11: 11}, 2: {22: 22}}
before second_dict: {1: {11: 11}, 2: {22: 22}}

after first_dict_: {1: {11: 11}}
after second_dict: {1: {11: 11}}

del second_dict[2] clearly says to delete the key from the second_dict, but for some reason Python deletes also this key from the first_dict. Why does it happen?

A: Let's try to attempt an answer.
>>> a = "hello"
>>> b = a
>>> bool(id(a) == id(b))
True

So even if they have different variable names, they are still the same object.


text:
Q: import pandas : ImportError: cannot import name Counter in python 2.6.6 I am using python 2.6.6
I installed pandas as follows
pip install pandas

I got the following success message as well
Building wheels for collected packages: pandas
  Running setup.py bdist_wheel for pandas ... done
  Stored in directory: /root/.cache/pip/wheels/81/18/d5/9f087d2b2763f0573195c75f297cac96125d02dbb5aef2297b
Successfully built pandas
Installing collected packages: six, python-dateutil, pytz, pandas
Successfully installed pandas-0.19.1 python-dateutil-2.6.0 pytz-2016.10 six-1.10.0

However now when am importing it
import pandas as pd

It gives me the following error
>>> import pandas as pd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pandas/__init__.py", line 22, in <module>
    from pandas.compat.numpy import *
  File "/usr/lib64/python2.6/site-packages/pandas/compat/__init__.py", line 333, in <module>
    from collections import OrderedDict, Counter
ImportError: cannot import name Counter

What is missing here?
Edit:
I installed backport_collections 0.1 and tried again. It still gives error

A: The pandas library uses the collections.Counter object which was introduced in Python 2.7; there's nothing to import in 2.6.
I think the easiest way around this is an upgrade to Python 2.7

A: try installing Pandas from this package
https://pypi.python.org/pypi/pandas/0.16.2/


text:
Q: How to forbid "00" or "0123-like" start of input in Android EditText, in Kotlin? I have an EditText object with the numberDecimal input type. The input manipulation (e.g., calculation) is working ok, but inputs starting with "00" and "0123-like" (zero followed by a number, not the dot) are currently permitted.
How can I forbid inputs starting with "00" or "0123-like" (zero followed by a number, not the dot), in Kotlin?
Aftering googling and reading many similar questions and answers, I've tried TextWatcher and InputFilter, but can't really figure out a solution.

A: You can use a TextWatcher and regular expression if the modified string is in the format 0, followed by a number, you can remove the last inserted digit and return to a string containing only the initial 0.
editText.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        val newText = s.toString().trim()

        // Check if the text is 0 followed by another digit, in that case remove the last inserted value
        if (newText.length > 1 && newText.matches("^0[\\d]+".toRegex())) {
            // Unwanted expression: remove last inserted char and reset the cursor position to show after the first character
            editText.setText("0")
            editText.setSelection(1)
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})

EDIT
If you need to apply the same TextWatcher to multiple EditText you could define your CustomTextWatcher class:
class CustomTextWatcher(
    private val editText: EditText
) : TextWatcher {

   override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

   override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

   override fun afterTextChanged(s: Editable?) {
       val newText = s.toString().trim()

        // Check if the text is 0 followed by another digit, in that case remove the last inserted value
        if (newText.length > 1 && newText.matches("^0[\\d]+".toRegex())) {
            // Unwanted expression: remove last inserted char and reset the cursor position to show after the first character
            editText.setText("0")
            editText.setSelection(1)
        }
   }
}

And then add it to your EditTexts with:
editText1.addTextChangedListener(CustomTextWatcher(editText1));
editText2.addTextChangedListener(CustomTextWatcher(editText2));
...