text:
Q: Can I use these @media specifications? I'm trying to construct my first responsive website. I'm wondering whether I can use the following code:
In the head of html:
< meta name="viewport" content="width=device-width, initial-scale=1.0">

In a single CSS:
@media only screen and (max-device-width : 480px) {}
@media only screen and (min-device-width : 480px) and (max-device-width : 960px) {}

This would be for 3 types of devices. Everything with a greater resolution than 960px has a third specification, not specified by @media. I cut down:
@media only screen and (min-device-width : 960px)  {}

Is this OK?
Can I also simplify the code by using only:
@media only screen and (max-device-width : 480px) {}

Because I think that the tablet and PC versions are going to be pretty similar. So the question is, do I need 3 @media or can I only use 1 @media & everything that is not specified by @media is for a PC or a Tablet?
Thanks in advance!

A: Every stylesheet rule which is not nested in media-queries is used on all devices.
You can use @media only screen and (max-device-width : 480px) {} and nest all rules in there which should apply for devices with max-device-width: 480px.
There are two possible ways to create responsive sites with CSS: mobile-first and desktop-first. If you're using your general stylesheets for desktop devices and media-queries for smaller devices it is a desktop-first attempt.
Just to go in more detail, I'm using these stylesheets for my projects, which I found online ( I'm not quite sure where I found it, so if somebody knows I'll add credits ). These seem to be the most accurate media-queries:
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
    /* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

A: @media only screen and (max-
device-width : 480px) {}
@media only screen and (min-
device-width : 481px) and (max-
device-width : 960px) {}
The min-device-width should have a pixel more than the max-device-width as corrected above. Elseb when the screen width is 480px, it will conflict and the second first condition will be overridden by the second condition. This means it will render a pc design for 480px screen resolution which is a mobile device.
Hope it helps.


text:
Q: Removing a JLabel from a subclass Say I have this class:
public class ExitView extends JPanel {

    private static final long serialVersionUID = 1L;

    public ExitView() {
            JLabel title = new JLabel("Exit?");
    title.setFont(new Font("Ariel", Font.PLAIN, 44));
            this.add(title);
    }
}

And this also:
public class EndView extends ExitView {

    public ExitView() {
            this.remove(title);
    }
}

This code is stripped way down, but in my code this is not removing the JLabel in EndView. I am able to just title.setText("") but that's not really getting rid of it. Can anybody explain why it wouldn't remove the label? Thanks.

A: you are creating a label in the base class constructor and adding this directly to the JPanel. But in the later check you don't use the reference to that created JLabel but some other. b/c the variable is out of scope it might be difficult to reference it again. The fix is as Paco mentioned. bring the variable out of the constructor scope and set it globably.
public class ExitView extends JPanel {

private static final long serialVersionUID = 1L;

    public ExitView() {
        JLabel title = new JLabel("Exit?"); // <- here you create a JLabel
                                            // in that scope where is the
                                            // reference for later use??
        title.setFont(new Font("Ariel", Font.PLAIN, 44));
        this.add(title);
    }
}

public class EndView extends ExitView {

     public ExitView() {
        this.remove(title); <- // the reference you create here doesn't
                               // equals the JLabel created earlier
     }
}

A: Try making the jlabel a field of the class:
public class ExitView extends JPanel {

    private static final long serialVersionUID = 1L;
    private JLabel title;

    public ExitView() {
            title = new JLabel("Exit?");
    title.setFont(new Font("Ariel", Font.PLAIN, 44));
            this.add(title);
    }
}

Edited
Look at this minimal example, it works:
public class ExitView extends JPanel{
    protected JLabel label;

    public ExitView() {
        label = new JLabel("your label");
        this.add(label);
    }

    public static void main(String[] args) {
        JDialog dialog = new JDialog();
        EndView endView= new EndView();

        dialog.add(endView);
        dialog.pack();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }
}

class EndView extends ExitView {
    public EndView() {
        this.remove(label);
    }
}

Your error must be on other place. How do you use EndView?

A: When you use the extends (some class) in Java thenthe class that extends
this can see only the variables(Objects) that are out of constructor and other methods and are (public or protected) but not (private).
public class ExitView extends JPanel {

private static final long serialVersionUID = 1L;
public JLabel title=new JLabel("Exit?"); //Here

public ExitView() {
   title.setFont(new Font("Ariel", Font.PLAIN, 44));
        this.add(title);
 }
}

The other class:
@SuppressWarnings("serial")

public class EndView extends ExitView {

public EndView() {
        this.remove(title); //now it can see the JLabel cause
                            //it is out of constructor and other
                           //methods and is (public or protected)
 }
}

Also check this link implements Vs Extends why and why not..

A: You're also using the ExitView constructor in EndView.

A:
Can anybody explain why it wouldn't remove the label? Thanks.

Because:
public class ExitView extends JPanel {

    private static final long serialVersionUID = 1L;

    public ExitView() {
        JLabel title = new JLabel("Exit?"); // local JLabel instance
    title.setFont(new Font("Ariel", Font.PLAIN, 44));
        this.add(title);
    }
}

Then:
@SuppressWarnings("serial")

public class EndView extends ExitView {

    public EndView() {
        this.remove(title); //now it can see the JLabel cause
                            //it is out of constructor and other
                            //methods and is (public or protected)
                            //'title' is not the same 'title' JLabel
                            // set in the superclass.
    }
}

There is a way to actually remove the component but it is messy. What I would suggest you do instead of having a JLabel containing another JLabel, change title to be a String. You can simply change the text property of the label by setting it to empty String, or by setting the visibility to false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hive job not running properly on cassandra cluster, reducer get stuck I have 6 node datastax cassandra cluster(3 cassandra- 3 analytics). I am using hive to generate reports.
The issue is when I run a hive job with count(*) or group by query, mappers get completed but the reducers get stuck to a particular percent. And they never change.
(All the nodes have 60GB of data. The column family on which I am running hive has around 40GB on each node and has 15 columns, each with data size of 50,60 characters.  I am using default hive settings.)
Also is their information available on time taken vs data size of hive job(normal query).
I could find on net.
This is what happens
Query is very simple - select count(*) from table;
It has 300k rows.
Starting Job = job_201305210728_0005, Tracking URL = http://something:50030/jobdetails.jsp?jobid=job_201305210728_0005
Kill Command = ./bin/dse hadoop job  -Dmapred.job.tracker=10.70.41.62:8012 -kill job_201305210728_0005
Hadoop job information for Stage-1: number of mappers: 7; number of reducers: 1
2013-05-22 03:52:58,811 Stage-1 map = 0%,  reduce = 0%
2013-05-22 03:53:02,841 Stage-1 map = 14%,  reduce = 0%, Cumulative CPU 1.87 sec
2013-05-22 03:53:03,863 Stage-1 map = 14%,  reduce = 0%, Cumulative CPU 1.87 sec
2013-05-22 03:53:04,874 Stage-1 map = 29%,  reduce = 0%, Cumulative CPU 2.59 sec
2013-05-22 03:53:05,882 Stage-1 map = 29%,  reduce = 0%, Cumulative CPU 2.59 sec
2013-05-22 03:53:06,894 Stage-1 map = 43%,  reduce = 0%, Cumulative CPU 3.42 sec
2013-05-22 03:53:07,901 Stage-1 map = 43%,  reduce = 0%, Cumulative CPU 3.42 sec
2013-05-22 03:53:08,908 Stage-1 map = 57%,  reduce = 0%, Cumulative CPU 5.13 sec
2013-05-22 03:53:09,919 Stage-1 map = 57%,  reduce = 0%, Cumulative CPU 5.13 sec
2013-05-22 03:53:10,929 Stage-1 map = 71%,  reduce = 0%, Cumulative CPU 5.51 sec
2013-05-22 03:53:11,936 Stage-1 map = 86%,  reduce = 0%, Cumulative CPU 7.79 sec
2013-05-22 03:53:12,943 Stage-1 map = 86%,  reduce = 0%, Cumulative CPU 7.79 sec
2013-05-22 03:53:13,951 Stage-1 map = 86%,  reduce = 0%, Cumulative CPU 7.79 sec
2013-05-22 03:53:14,958 Stage-1 map = 100%,  reduce = 19%, Cumulative CPU 10.25 sec
2013-05-22 03:53:15,965 Stage-1 map = 100%,  reduce = 19%, Cumulative CPU 10.25 sec
2013-05-22 03:53:16,972 Stage-1 map = 100%,  reduce = 19%, Cumulative CPU 10.25 sec
2013-05-22 03:53:17,979 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:18,986 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:19,993 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:20,999 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:22,007 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:23,014 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:24,021 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:25,028 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:26,035 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:27,042 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:28,049 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:29,055 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:30,063 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:31,070 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:32,077 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:33,084 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:34,091 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:35,097 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:36,105 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:37,112 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:38,118 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:39,125 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:40,132 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:41,139 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:42,145 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:43,153 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:44,160 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:45,166 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:46,172 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:47,180 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:48,186 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:49,193 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:50,201 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:51,208 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:52,214 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:53,221 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:54,227 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:55,235 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:56,241 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:57,249 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec
2013-05-22 03:53:58,256 Stage-1 map = 100%,  reduce = 24%, Cumulative CPU 10.25 sec

and continues....

I am attaching hive logs
 Counters plan="{"queryId":"root_20130523051919_5e968691-9119-47fa-9b45-f61a90e86452","queryType":null,"queryAttributes":{"queryString":"select count(*) from suborder_issue"},"queryCounters":"null","stageGraph":{"nodeType":"STAGE","roots":"null","adjacencyList":"]"},"stageList":[{"stageId":"Stage-1","stageType":"MAPRED","stageAttributes":"null","stageCounters":{"CNTR_NAME_Stage-1_REDUCE_PROGRESS":"14","CNTR_NAME_Stage-1_MAP_PROGRESS":"100"},"taskList":[{"taskId":"Stage-1_MAP","taskType":"MAP","taskAttributes":"null","taskCounters":"null","operatorGraph":{"nodeType":"OPERATOR","roots":"null","adjacencyList":[{"node":"TS_0","children":["SEL_1"],"adjacencyType":"CONJUNCTIVE"},{"node":"SEL_1","children":["GBY_2"],"adjacencyType":"CONJUNCTIVE"},{"node":"GBY_2","children":["RS_3"],"adjacencyType":"CONJUNCTIVE"}]},"operatorList":[{"operatorId":"TS_0","operatorType":"TABLESCAN","operatorAttributes":"null","operatorCounters":"}","done":"true","started":"true"},{"operatorId":"SEL_1","operatorType":"SELECT","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"},{"operatorId":"GBY_2","operatorType":"GROUPBY","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"},{"operatorId":"RS_3","operatorType":"REDUCESINK","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"}],"done":"true","started":"true"},{"taskId":"Stage-1_REDUCE","taskType":"REDUCE","taskAttributes":"null","taskCounters":"null","operatorGraph":{"nodeType":"OPERATOR","roots":"null","adjacencyList":[{"node":"GBY_4","children":["SEL_5"],"adjacencyType":"CONJUNCTIVE"},{"node":"SEL_5","children":["FS_6"],"adjacencyType":"CONJUNCTIVE"}]},"operatorList":[{"operatorId":"GBY_4","operatorType":"GROUPBY","operatorAttributes":"null","operatorCounters":"}","done":"false","started":"true"},{"operatorId":"SEL_5","operatorType":"SELECT","operatorAttributes":"null","operatorCounters":"null","done":"false","started":"true"},{"operatorId":"FS_6","operatorType":"FILESINK","operatorAttributes":"null","operatorCounters":"null","done":"false","started":"true"}],"done":"false","started":"true"}],"done":"false","started":"true"}],"done":"false","started":"true"}" TIME="1369303703813"
TaskProgress TASK_HADOOP_PROGRESS="2013-05-23 06:08:24,818 Stage-1 map = 100%,  reduce = 14%, Cumulative CPU 23.04 sec" TASK_NUM_REDUCERS="1" TASK_NAME="org.apache.hadoop.hive.ql.exec.MapRedTask" TASK_NUM_MAPPERS="7" TASK_COUNTERS="org.apache.hadoop.hive.ql.exec.Operator$ProgressCounter.CREATED_FILES:0,Job Counters .Launched reduce tasks:1,Job Counters .SLOTS_MILLIS_MAPS:41820,Job Counters .Rack-local map tasks:8,Job Counters .Launched map tasks:8,File Input Format Counters .Bytes Read:0,FileSystemCounters.FILE_BYTES_WRITTEN:327828,FileSystemCounters.CFS_BYTES_READ:3527,org.apache.hadoop.hive.ql.exec.MapOperator$Counter.DESERIALIZE_ERRORS:0,Map-Reduce Framework.Map output materialized bytes:203,Map-Reduce Framework.Map input records:351783,Map-Reduce Framework.Reduce shuffle bytes:78,Map-Reduce Framework.Spilled Records:6,Map-Reduce Framework.Map output bytes:79,Map-Reduce Framework.Total committed heap usage (bytes):2057568256,Map-Reduce Framework.CPU time spent (ms):23040,Map-Reduce Framework.Map input bytes:351783,Map-Reduce Framework.SPLIT_RAW_BYTES:3527,Map-Reduce Framework.Combine input records:0,Map-Reduce Framework.Reduce input records:0,Map-Reduce Framework.Reduce input groups:0,Map-Reduce Framework.Combine output records:0,Map-Reduce Framework.Physical memory (bytes) snapshot:2163638272,Map-Reduce Framework.Reduce output records:0,Map-Reduce Framework.Virtual memory (bytes) snapshot:7556251648,Map-Reduce Framework.Map output records:6" TASK_ID="Stage-1" QUERY_ID="root_20130523051919_5e968691-9119-47fa-9b45-f61a90e86452" TASK_HADOOP_ID="job_201305220529_0009" TIME="1369303704818"
Counters plan="{"queryId":"root_20130523051919_5e968691-9119-47fa-9b45-f61a90e86452","queryType":null,"queryAttributes":{"queryString":"select count(*) from suborder_issue"},"queryCounters":"null","stageGraph":{"nodeType":"STAGE","roots":"null","adjacencyList":"]"},"stageList":[{"stageId":"Stage-1","stageType":"MAPRED","stageAttributes":"null","stageCounters":{"CNTR_NAME_Stage-1_REDUCE_PROGRESS":"14","CNTR_NAME_Stage-1_MAP_PROGRESS":"100"},"taskList":[{"taskId":"Stage-1_MAP","taskType":"MAP","taskAttributes":"null","taskCounters":"null","operatorGraph":{"nodeType":"OPERATOR","roots":"null","adjacencyList":[{"node":"TS_0","children":["SEL_1"],"adjacencyType":"CONJUNCTIVE"},{"node":"SEL_1","children":["GBY_2"],"adjacencyType":"CONJUNCTIVE"},{"node":"GBY_2","children":["RS_3"],"adjacencyType":"CONJUNCTIVE"}]},"operatorList":[{"operatorId":"TS_0","operatorType":"TABLESCAN","operatorAttributes":"null","operatorCounters":"}","done":"true","started":"true"},{"operatorId":"SEL_1","operatorType":"SELECT","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"},{"operatorId":"GBY_2","operatorType":"GROUPBY","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"},{"operatorId":"RS_3","operatorType":"REDUCESINK","operatorAttributes":"null","operatorCounters":"null","done":"true","started":"true"}],"done":"true","started":"true"},{"taskId":"Stage-1_REDUCE","taskType":"REDUCE","taskAttributes":"null","taskCounters":"null","operatorGraph":{"nodeType":"OPERATOR","roots":"null","adjacencyList":[{"node":"GBY_4","children":["SEL_5"],"adjacencyType":"CONJUNCTIVE"},{"node":"SEL_5","children":["FS_6"],"adjacencyType":"CONJUNCTIVE"}]},"operatorList":[{"operatorId":"GBY_4","operatorType":"GROUPBY","operatorAttributes":"null","operatorCounters":"}","done":"false","started":"true"},{"operatorId":"SEL_5","operatorType":"SELECT","operatorAttributes":"null","operatorCounters":"null","done":"false","started":"true"},{"operatorId":"FS_6","operatorType":"FILESINK","operatorAttributes":"null","operatorCounters":"null","done":"false","started":"true"}],"done":"false","started":"true"}],"done":"false","started":"true"}],"done":"false","started":"true"}" TIME="1369303704818"

A: Two things I can thing of. You either are running out of memory and need to increase your heap size, or you're running out of disk space on your data nodes. Check your log partition and make sure they're not filled up.

A: The only 100% advice is to carefully look inside reducer logs (you should have them on cluster, probably JobTracker web UI is best place to start with). Number of possible reasons is too much.


text:
Q: Conversion into passive voice and order of the words This is a sentence in active voice: He cannot rear any cattle on his farm.
Its passive would be: Any cattle cannot be reared by him on his farm? OR On his farm, any cattle cannot be reared by him? OR Any cattle cannot be reared on his farm by him? Do all the three conversions mean the same thing, does order of words have any effect on the meaning?

A: I would render the passive (if you put a gun to my head) as:

No cattle can be reared by him on his farm.

or

Cattle cannot be reared by him on his farm.


text:
Q: Roslyn Rewrite Method Calls to use await Modifier I a bunch of C# Files that I want to migrate to a new version of an internal framework we use for development. So far I have been able to accomplish certain things But there is a particular method invocation that i have to modify to use await modifier and the method calls come  in different flavors like so
 var a = EntityService.GetBy(Entities.INSTANT_ISSUANCE_REQUEST, requestFilter);
 var b = EntityService.GetBy(Entities.ISSUANCE_SETTINGS, new DejaVuObject()).FirstOrDefault();

I have to modify the above method calls so that they use the following syntax
 var a = await EntityService.GetBy(Entities.INSTANT_ISSUANCE_REQUEST, requestFilter);
 var b = await EntityService.GetBy(Entities.ISSUANCE_SETTINGS, new DejaVuObject()).FirstOrDefault();

I am using Roslyn CSharpSyntaxWriter to traverse the syntax tree.
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
    var variableDeclarations =
        from i in node.DescendantNodes().OfType<VariableDeclaratorSyntax>()
        where i.DescendantNodes().OfType<EqualsValueClauseSyntax>().Any<EqualsValueClauseSyntax>(
            p => p.DescendantNodes().OfType<InvocationExpressionSyntax>().Any<InvocationExpressionSyntax>())
        select i;

    foreach (var syntax in variableDeclarations)
    {
        var equalsToken = syntax.DescendantNodes();
        //now we have the equals token
        foreach (var syntaxNode in equalsToken)
        {
            if (syntaxNode is EqualsValueClauseSyntax)
            {
                var equalsValueSyntax = syntaxNode.DescendantNodes().OfType<InvocationExpressionSyntax>();
                foreach (var invocationExpressionSyntax in equalsValueSyntax)
                {
                    var simpleMemberAcessExpressions = invocationExpressionSyntax
                        .DescendantNodes()
                        .OfType<IdentifierNameSyntax>()
                        .Where(i => i.Identifier.Text == "EntityService");
                    foreach (var simpleMemberAcessExpression in simpleMemberAcessExpressions)
                    {
                        var newExpression = $"{invocationExpressionSyntax.ToFullString()}";
                        Console.WriteLine(newExpression);
                        //TODO: Modify the Node
                    }
                }
            }
        }
    }
    return base.VisitLocalDeclarationStatement(node);
}

My problem here is the output in Console is somewhat duplicative
EntityService.GetBy(Entities.ISSUANCE_SETTINGS, new DejaVuObject()).FirstOrDefault();
EntityService.GetBy(Entities.ISSUANCE_SETTINGS, new DejaVuObject())

Both refer to same InvocationExpression but because of the FirstOrDefault() it shows up twice in the console output
I would like for a way to filter the results so that they contain only unique Method Invocations and perform the actual modification of the method call by adding the await modifier and updating the node.

A: first of all, why override VisitLocalDeclarationStatement? Looks like you should be overriding VisitInvocationExpression.
You shouldn't be doing this:
var simpleMemberAcessExpressions =
    invocationExpressionSyntax.DescendantNodes().OfType<IdentifierNameSyntax>()

Instead, it should be something like:
var identifier =
    (node.Expression as MemberAccessExpressionSyntax)?.Expression as IdentifierNameSyntax;

if (identifier != null && identifier.Identifier.Text == "EntityService")
{
    // process the invocation expression
}

Assuming the invocation expression is called node, your new expression is probably
var newExpression =
    SyntaxFactory.ParenthesizedExpression(SyntaxFactory.AwaitExpression(node))
    .WithAdditionalAnnotations(Simplifier.Annotation)
    .WithAdditionalAnnotations(Formatter.Annotation);


text:
Q: How can I write a Circular Log script in Perl? we are trying to write a script in Perl that makes a circular log. One program generates a really big log file and we want to separate it into 5,6 or so files.
use Log::Dispatch::FileRotate;

  my $file = Log::Dispatch::FileRotate->new( name      => 'file1',
                                       min_level => 'info',
                                       filename  => 'C:\Test\Log.txt',
                                       dir => 'C:\Test',
                                       mode      => 'write' ,
                                       size      => 5,
                                       max       => 6,
                                      );

    $file->log( level => 'info', message => 'Comment');

We found this code online, but it's behaving a bit erratically. Is this script supposed to write a new file whenever the main log file grows by 5MB and into 6 files tops? How can we accomplish this?
Thanks.

A: I tested this code, and think size is in bytes, so if you want to write 5MB logs you need to set size to 5*1024*1024 or something like this. My test code, that writes 6 files 5MB each:
#!/usr/bin/perl

use strict;
use warnings;
use Log::Dispatch::FileRotate;

my $file = Log::Dispatch::FileRotate->new(
                                            name => 'file1',
                                            min_level => 'info',
                                            filename  => '/tmp/log/some.log',
                                            mode => 'append',
                                            size => 5*1024*1024,
                                            max => 6,
                                            newline => 1
                                          );

while (1) {
        $file->log( level => 'info', message => time );
        $file->log( level => 'debug', message => time." debug ".time ); #this will not be logged, because of log level
}

A: I suggest you use something like Log::Rolling or Logfile::Rotate.
Both of these modules are ready-built solutions to your problem and hopefully have all the bugs already ironed out.


text:
Q: Peculiar lack of RHEL 5.8 service management documentation I am needing to see the status of some services on some of our RHEL 5.8 hosts on which I am not an admin.  Much to my surprise, I am not able to get any info how to do it (such as chkconfig or systemctl on Fedora) from Google.  Neither chkconfig nor systemctl are accessible to me, not sure if it is because of permissions or they are just not available on the system but there are no man pages for either.
Why is it that there is such a mysterious lack of service management documentation online for RHEL 5.8 and which commands can I use for simple service listings?

A: Your accusation of a lack of documentation for RHEL is extremely poorly founded; RHEL is one of the best and most comprehensively documented Linux distributions out there.
Information on chkconfig, for instance, is in chapter 18 of the Deployment Guide.
If you find that your installed system doesn't seem to have utilities or man pages that you expect to be there, contact your system administrator.


text:
Q: Changing color or image of marker that are not clustered in android I want to chnage the color of marker that are not being clustered and shown as an individual marker on map.
I tried code from a demo project from android but I am not able get it working in my code.I change icon for one marker it chnaged everywhere and cluster disappears.
Here is the original code which I was trying to use
(Only relevant part from the code)
public class CustomMarkerClusteringDemoActivity extends BaseDemoActivity implements ClusterManager.OnClusterClickListener<Person>, ClusterManager.OnClusterInfoWindowClickListener<Person>, ClusterManager.OnClusterItemClickListener<Person>, ClusterManager.OnClusterItemInfoWindowClickListener<Person> {
private ClusterManager<Person> mClusterManager;
private Random mRandom = new Random(1984);

/**
 * Draws profile photos inside markers (using IconGenerator).
 * When there are multiple people in the cluster, draw multiple photos (using MultiDrawable).
 */
private class PersonRenderer extends DefaultClusterRenderer<Person> {
    private final IconGenerator mIconGenerator = new IconGenerator(getApplicationContext());
    private final IconGenerator mClusterIconGenerator = new IconGenerator(getApplicationContext());
    private final ImageView mImageView;
    private final ImageView mClusterImageView;
    private final int mDimension;

    public PersonRenderer() {
        super(getApplicationContext(), getMap(), mClusterManager);

        View multiProfile = getLayoutInflater().inflate(R.layout.multi_profile, null);
        mClusterIconGenerator.setContentView(multiProfile);
        mClusterImageView = (ImageView) multiProfile.findViewById(R.id.image);

        mImageView = new ImageView(getApplicationContext());
        mDimension = (int) getResources().getDimension(R.dimen.custom_profile_image);
        mImageView.setLayoutParams(new ViewGroup.LayoutParams(mDimension, mDimension));
        int padding = (int) getResources().getDimension(R.dimen.custom_profile_padding);
        mImageView.setPadding(padding, padding, padding, padding);
        mIconGenerator.setContentView(mImageView);
    }

    @Override
    protected void onBeforeClusterItemRendered(Person person, MarkerOptions markerOptions) {
        // Draw a single person.
        // Set the info window to show their name.
        mImageView.setImageResource(person.profilePhoto);
        Bitmap icon = mIconGenerator.makeIcon();
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(person.name);
    }

    @Override
    protected void onBeforeClusterRendered(Cluster<Person> cluster, MarkerOptions markerOptions) {
        // Draw multiple people.
        // Note: this method runs on the UI thread. Don't spend too much time in here (like in this example).
        List<Drawable> profilePhotos = new ArrayList<Drawable>(Math.min(4, cluster.getSize()));
        int width = mDimension;
        int height = mDimension;

        for (Person p : cluster.getItems()) {
            // Draw 4 at most.
            if (profilePhotos.size() == 4) break;
            Drawable drawable = getResources().getDrawable(p.profilePhoto);
            drawable.setBounds(0, 0, width, height);
            profilePhotos.add(drawable);
        }
        MultiDrawable multiDrawable = new MultiDrawable(profilePhotos);
        multiDrawable.setBounds(0, 0, width, height);

        mClusterImageView.setImageDrawable(multiDrawable);
        Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }

Can anyone simplify or explain the process how this works
This is the code for onBeforeClusterRendered which I found after decompiling DefaultClusterRender class
protected void onBeforeClusterRendered(Cluster<T> cluster, MarkerOptions markerOptions) {
    int bucket = this.getBucket(cluster);
    BitmapDescriptor descriptor = (BitmapDescriptor)this.mIcons.get(bucket);
    if(descriptor == null) {
        this.mColoredCircleBackground.getPaint().setColor(this.getColor(bucket));
        descriptor = BitmapDescriptorFactory.fromBitmap(this.mIconGenerator.makeIcon(this.getClusterText(bucket)));
        this.mIcons.put(bucket, descriptor);
    }

    markerOptions.icon(descriptor);
}

But I can't understand a thing from this.


text:
Q: ProjectReference being converted to a Reference Our team has a solution with two class libraries (A, B).

*

*B has a "Project Reference" to A.

*A is published to an internal NuGet server.

*B also has a dependency on a class library C (internal; but exists in a different repo, solution).

*C is published to the same internal NuGet server.

*C also has a dependency on A.

We are experiencing that at some point during the development process, the B.csproj is modified and the ProjectReference to A is replaced with a Reference to an older version of A that exists in the packages folder (the version of A that C depends on).
I believe we have come across a bug in how Nuget and/or Visual Studio resolve version conflicts, but first wanted to see if anyone had any suggestions before reporting it.


text:
Q: Angular 4 Return http response as interface with JSON as property I had a previously working service that used to only return the JSON response into my component (see second section for previously working code).  However, I am building in additional functionality into all of my components to have loading animations and error messages so I need the response.OK and response.status code as well.  I created this generic response interface to use in a global variable service I have as follows:
export interface GetResponse  {
    status: number,
    ok: boolean,
    json: any
}

I am using it in my service as follows:
   getInfoDeskTopic(topicUrl) {
        this.infoDeskData = [];
        this.http.get(topicUrl, this.options)
            .map(res => this.response = res)
            .map(res => this.response.json = res.json().resultSet.results)
        this.response.json
                .map(data => data
                    .forEach(item => {
                        let infoDesk = <InfoDesk>{};
                        infoDesk.Url = item.json.webUrl;
                        infoDesk.Date = item.date;
                        item.fields.forEach(item => {
                            if (item.id == 'publication') {
                                infoDesk.Publication = item.strings[0];
                            }
                            if (item.id == 'headline') {
                                infoDesk.Title = item.strings[0];
                            }
                        });
                        this.infoDeskData.push(infoDesk);
                    }))
                .map(data => data = this.infoDeskData)
            .map(items => items.slice(0, 5))
            .share();
        return this.response;
    }

And I am attempting to use it in my component as follows:
this.response = this.infodesk.getInfoDeskTopic(this.topicUrl);
this.news = this.response.json;
this.success = this.response.ok;

I have the variable in my component (this.response: any).  I receive the error:
Uncaught Error: Can't resolve all parameters for InfoDeskService: ([object Object], ?).
    at syntaxError (compiler.es5.js:1540)

Can any help me understand why I am getting an error? I feel like I am declaring something incorrectly perhaps, but I cannot figure out what the issue is.  Thanks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following is what I had PREVIOUSLY and it was working fine (just for reference):
In my service:
   getInfoDeskTopic(topicUrl) {
        this.infoDeskData = [];
        return this.http.get(topicUrl, this.options)
            .map(res => res.json().resultSet.results)
                .map(data => data
                    .forEach(item => {
                        let infoDesk = <InfoDesk>{};
                        infoDesk.Url = item.json.webUrl;
                        infoDesk.Date = item.date;
                        item.fields.forEach(item => {
                            if (item.id == 'publication') {
                                infoDesk.Publication = item.strings[0];
                            }
                            if (item.id == 'headline') {
                                infoDesk.Title = item.strings[0];
                            }
                        });
                        this.infoDeskData.push(infoDesk);
                    }))
                .map(data => data = this.infoDeskData)
            .map(items => items.slice(0, 5))
            .share();
    }

And in my component:
this.news = this.infodesk.getInfoDeskTopic(this.topicUrl);

A: First if you use angular 4+, you should to use HTTPCLIENT vs HTTP.
Please, search the difference.. (You don't need to use .map)
Please look at this example:
interface interfaceJSON {
  name: string;
  email: string;
  company: string;
}

this.http.get<interfaceJSON>('apiUrl').subscribe(data => {
  console.log("Name: " + data.name);
  console.log("Email: " + data.email);
  console.log("Company: " + data.company);
});


text:
Q: Date validator in Angular 8 to compare two dates What is the best way to do this in Angular 8
i have two inputs that are dates fromDateMin and fromDateMAx
i need to compare these two against formControlName='fromctrlname' and formControlName='toctrlname'
and display errors
Conditions:
If fromDateMin is non-null, the user can't select a date any earlier than this date. If they do, the date is changed to this date. Display message in error-message-span.
If fromDateMax is non-null, the user can't select a date any later than this date. If they do, the date is changed to this date. Display message in error-message-span.
fromDate must be earlier than, or the same as, toDate. toDate must be later than, or the same as, fromDate. Display message in error-message-span.
Here is what i have tried so far
https://stackblitz.com/edit/angular-2gdadn?file=src%2Fapp%2Fapp.component.ts
Here is my html

    <form [formGroup]='dateFilterForm'>
      {{fromLabel}}
      <input type="date" formControlName='fromctrlname' id="{{componentId}}-fromDate" name="{{componentId}}-fromDate"
        placeholder="{{fromPlaceholder}}" [(ngModel)]="fromDate" (ngModelChange)="errMsg = ''" [value]="fromDate">

      {{toLabel}}
      <input type="date" formControlName='toctrlname' id="{{componentId}}-toDate" name="{{componentId}}-fromDate"
        placeholder="{{toPlaceholder}}" [(ngModel)]="toDate" (ngModelChange)="errMsg = ''" [value]="toDate">

      <button type="submit" (click)="submit()"
        class="btn button-border white icon-rightarrow-white medium mt2 ml2 mr1 mb2 r15 fw7"
        style="display:inline-block;">{{buttonLabel}}</button>

         From date should not be earlier than {{fromDateMin}}.

        To date should not be later than {{fromDateMax}}.

        {{errMsg}}

    </form>

A: The validation part can be easily achieved using reactive forms and custom validators, as mentioned by Robert.
You can create 2 validators based on your requirements, one that validates min and max date on each form control within the group. Another validator for the group to validate that fromDate is earlier than toDate.
This is how the validator for the input controls basically could look like.
function dateRangeValidator(min: Date, max: Date): ValidatorFn {
  return control => {
    if (!control.value) return null;

    const dateValue = new Date(control.value);

    if (min && dateValue < min) {
      return { message: 'error message' };
    }

    if (max && dateValue > max) {
      return { message: 'error message' };
    }

    null;
  }
}

You can compose a ValidatorFn by wrapping it around another function to provide additional parameters besides the control. In your case that would be a min and max date. You then add the validator to the form by calling your function.
fromDate: new FormControl('', [dateRangeValidator(this.minDate, this.maxDate)])

In your group validator you compare the values of both child controls
function groupValidator(group: AbstractControl): ValidationErrors | null {
  const fromCtrl = group.get('fromDate');
  const toCtrl = group.get('toDate');

  return new Date(fromCtrl.value) > new Date(toCtrl.value) ? { message: 'error message' } : null;
}

In this case we don't wrap the validation function around another function, because we don't have to configure anything.
The complete form group configuration will look something like this:
formGroup = new FormGroup({
    fromDate: new FormControl('', [dateRangeValidator(this.minDate, this.maxDate)]),
    toDate: new FormControl('', [dateRangeValidator(this.minDate, this.maxDate)]),
}, [groupValidator]);

Each validator will add the errors to the corresponding control. So they are easy to get to in the template or somewhere else.
These are very rough example implementations, so use them only as a starting point.
As for the updating the value during validation. You could do it in the validator, as you do have the AbstractControl available. Calling setValue or patchValue can do that for you. But that will trigger validation again and can lead to an infinite recursive loop, so watch out for that. Also, you might want to change that a value update is emitted on blur, and not on each keystroke. You can do that on each form control using the updateOn: blur option.
fromDate: new FormControl('', { updateOn: 'blur', validators: [...] })

Here is the stackblitz I used for a quick prototype: https://stackblitz.com/edit/angular-ivy-jfes5n


text:
Q: App opens to specific ViewController inside Navigation Controller I'm trying to have my app open to a specific ViewController that is deeply embedded in a Navigation Controller, but isn't the RootViewController. I have tried in the app delegate didFinishLaunchingWithOptions adding:
  self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
  let storyboard = UIStoryboard(name: "Main", bundle: nil)
  let initialViewController = storyboard.instantiateViewControllerWithIdentifier("NavViewController")
  self.window?.rootViewController = initialViewController
  self.window?.makeKeyAndVisible()

But this goes to the root view controller. I tried changing this line to:
storyboard.instantiateViewControllerWithIdentifier("MainViewController")

and this does open to the correct viewcontroller but then there is no Navigation Bar on the top which is needed to navigate in the app.

A: To access the rootViewController from the AppDelegate then here is the code:
let rootViewController = application.windows[0].rootViewController as! UINavigationController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let notificationVC = mainStoryboard.instantiateViewControllerWithIdentifier("identifier") as! NotificationVC
rootViewController.pushViewController(notificationVC, animated: false)

Now, it will have the navigationBar. Let me know, if you still face the issue. thanks.

A: Here is the Objective-C version to open a specific UIViewController deeply embedded inside a UINavigationController (which is not the rootController).
If we take @bdc example in comments and we want to open UIViewController D:

*

*A : rootViewController

*N : navigationController

*B, C, D : UIViewControllers embedded in N

*A -> N[B C D]

Set storyboardId in InterfaceBuilder for every UIViewController or UINavigationController in the hierarchy through D.
In AppDelegate, the code is straight forward. You just have to instantiate everything, and use your UINavigationController to push every UIViewController in your hierarchy.
// Instanciate from storyboard with identifiers

UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle:nil];
UINavigationController * N = (UINavigationController*) [storyboard instantiateViewControllerWithIdentifier:@"N"];
UIViewController* B = (UIViewController*) [storyboard instantiateViewControllerWithIdentifier:@"B"];
UIViewController* C = (UIViewController*) [storyboard instantiateViewControllerWithIdentifier:@"C"];
UIViewController* D = (UIViewController*) [storyboard instantiateViewControllerWithIdentifier:@"D"];

// Set up the views hierarchy

self.window.rootViewController = N;
[N pushViewController:B animated:NO];
[N pushViewController:C animated:NO];
[N pushViewController:D animated:YES];

[self.window makeKeyAndVisible];

Hope this will help.


text:
Q: Run Python + OpenCV + dlib in Azure Functions I have created an image processing script in Python (with dlib and OpenCV) - I was wondering how I can bring this functionality to Azure Functions, so that the script can be called via an API. As Python is still in preview for Azure Functions I wanted to know if anybody here has experience with bringing modules to Azure Functions and if it's possible to install OpenCV there?

A: You can bring your own modules to your Function by uploading them into the a lib folder residing in the same folder as your Function.
However, in the context of OpenCV, it is not a supported scenario at the moment.  The default Python version being used in the Azure Function environment is Python 2.7.  If you try to execute a Function code using OpenCV for Python 2.7, the error message you will get would be similar to the following,
2016-11-07T20:47:33.151 Function completed (Failure, Id=42fa9d38-05f1-46d4-a8ce-9fbaa24a870d)
2016-11-07T20:47:33.166 Exception while executing function: Functions.ImageProcessor. Microsoft.Azure.WebJobs.Script: ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
  File "D:\home\site\wwwroot\ImageProcessor\run.py", line 17, in <module>
    import cv2
ImportError: numpy.core.multiarray failed to import

The fix for this is to update the numpy version used by Python 2.7, but you will not be able to run the update yourself.
As you have noted, Python language support for Azure Functions is in an experimental stage right now.  These issues will be addressed when Python is fully on-boarded as a first-class language.

A: so I figured a dirty hack, it will install the package on the first run and throw an error, so the function will restart. Follow these steps:

*

*Upload package to the function directory (I just added the package to the git project to which the function is syncronized).

*Do something like (there probably is a better way, but I'm really new to python):
try:
 import pyodbc
except:
 package = 'pyodbc-3.0.10-cp27-none-win32.whl'
 pip.main(['install', '--user', package])
 raise ImportError('Restarting')

So the reason behind --user is that it won't let me install it with admin privileges... Also if you do include the requirements.txt with your git repository the packages are installed to the WebApp, but it appears that the Function got its own python environment, so you have to install packages manually.
So the only real trick it to find the appropriate wheel package (I strongly believe that Function is using Python 2.7, I couldn't get it to work with packages for Python 3.4)


text:
Q: htaccess url as parameter Hi all and thanks in advance, I'm trying to add a url as a parameter but I can not.
My rule is:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^info/([a-zA-Z0-9|]+)/(.*)/(.*)$ info.php?user=$1&text=$2&url=$3

In the browser:
http://localhost/example/info/peter/hi guy/http://www.example.com
Return array $_GET php
[user] => peter
[text] => hi guy / http:
[url] => www.example.com

What would be correct:
[user] => peter
[text] => hi guy
[url] => http://www.example.com

I hope your help thanks

A: It's called greedy matching .. the "dot-asterisk" matches as much as it can & then backtracks. Instead use [^/] which will match up to the next slash.

A: RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^info/([a-zA-Z0-9|]+)/([^/]*)/(.*)$ info.php?user=$1&text=$2&url=$3 [B,QSA]

[^/] means "any character that's not a slash". Naturally this means that "text" cannot contain any slashes, but your URL will be matched correctly.
Also note the [B] which is one of many options you can add to a rewrite rule. [B] means that any &s and some other characters will be escaped. So if the URL that you're as a parameter has a query string, it can be read out in $_GET['url'] where its parameters would otherwise be interepreted as part of the new query string.

A: http://localhost/example/info/peter/hi/guy/http://www.example.com is not a valid URL for what you're trying to do. The URL part should be urlencoded.  See this explanation, for example.
The correct URL would be:
http://localhost/example/info/peter/hi/guy/http%3A%2F%2Fwww.example.com

Nothwithstanding this point, the error with your regex is greedy matching as described in another answer.  However if you encoded the URL correctly, that wouldn't be a problem.

A: Not my area of expertise, but why not use a $_SERVER request for the url?
It may work, may not, and that way if the domain ever changes then there is no need to update anything.
Hope this helps.


text:
Q: How to prove that the metric $d=\sup \lbrace d_i(x_i,y_i) \rbrace$ satisfy the triangle inequality? Let $(X_i
, d_i), i ∈ \Bbb N$, be a collection of metric spaces.  Here $x = (x_1, . . . , x_n)$ and $y = (y_1, . . . , y_n)$ are
elements of $\prod_{i \in \Bbb N} X_i.$
Define the metric $d(x,y)=\sup \lbrace d_i(x_i,y_i) \rbrace$ on the infinite product $\prod_{i \in \Bbb N} X_i.$
My question is how to prove that the metric $d(x,y)=\sup \lbrace d_i(x_i,y_i) \rbrace$ satisfy the triangle inequality? Can I ask for someone's help? Thanks so much.

A: For every $i$ we have $d_i(x_i,x_i)+d_i(y_i,y_i) \ge d_i(x_i+y_i,x_i+y_i)$ because metric space $X_i,d_i$ satisfies triangle inequality.
Suppose that : $\sup \lbrace d_i(x_i,x_i) \rbrace +\sup \lbrace d_i(y_i,y_i)  \rbrace  \lt \sup \lbrace d_i(x_i+y_i,x_i+y_i)  \rbrace $. That would mean that for some $i$ : $  d_i(x_i,x_i)   +  d_i(y_i,y_i)    \lt  d_i(x_i+y_i,x_i+y_i)   $. This contradicts with the fact that the triangle inequality is valid in all spaces $X_i$ individually.


text:
Q: Using django-allauth and Stack Exchange as a provider, how can I change the redirect_uri in my development environment? I am attempting to use the the allauth plugin and Stack Exchange as a provider.
I have the following settings:
INSTALLED_APPS = [
    ...
    # The Django sites framework is required
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.stackexchange',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ...
                # Required by `allauth` template tags
                'django.core.context_processors.request',
            ],
        },
    },
]

SOCIALACCOUNT_PROVIDERS = {
    'stackexchange': {
        'SITE': 'stackoverflow'
    }
}

I have a registered app over on Stack Apps and it doesn't use the "Client Side Flow" and I've configured my client id and secret key in the Django Admin panel.
In my development environment, though, how do I force a log in to redirect back to my localhost? Right now, I receive this error:
error description: Cannot return to provided redirect_uri

The documentation says:

For local development you can simply use "localhost" for the OAuth domain.

What does this mean and how do I accomplish it?

A: Just add the page you want to be redirected to your settings
#settings.py
LOGIN_REDIRECT_URL = '/example'


text:
Q: fitting transition matrix to crosstable in r I am having some trouble fitting a transtion matrix.
While analysing panel data I need to fit a transition matrix (with standard error) to the crosstable shown below or the underlying data. It shows participants transitioning between income states in the first two waves.
By converting it to a markovchain object using the markovchain package, I only get the transtion percentages, but no standard errors. How do I get those?
          1    2    3    4    5    6
      1  2639 156  69   49   21   42
      2  150  300  53   11   1    1
      3  74   20   363  48   8    4
      4  60   7    46   384  65   12
      5  42   2    5    75   275  63
      6  40   0    1    15   52   402

library(markovchain)
mcobject<-as(mytableX, "markovchain")

         1           2           3          4           5           6
1 0.88676075 0.052419355 0.023185484 0.01646505 0.007056452 0.014112903
2 0.29069767 0.581395349 0.102713178 0.02131783 0.001937984 0.001937984
3 0.14313346 0.038684720 0.702127660 0.09284333 0.015473888 0.007736944
4 0.10452962 0.012195122 0.080139373 0.66898955 0.113240418 0.020905923
5 0.09090909 0.004329004 0.010822511 0.16233766 0.595238095 0.136363636
6 0.07843137 0.000000000 0.001960784 0.02941176 0.101960784 0.788235294

A: You can use the multinomialConfidenceIntervals function.
library(markovchain)
#get your data
ciau.matrix<-matrix(c(2639, 156  ,69,   49  , 21,   42,
150,  300  ,53 ,  11  , 1  ,  1,
74,   20  , 363 , 48   ,8   , 4,
60,   7  ,  46   ,384 , 65   ,12,
42,   2 ,   5    ,75 ,  275 , 63,
40,   0,    1    ,15,   52  , 402),nrow = 6,byrow = TRUE)

ciau.table<-as.table(ciau.matrix)

ciau.Markovchain<-as(ciau.table,"markovchain")
#use the multinomialConfidenceInterval to obtain confidence intervals
multinomialConfidenceIntervals(transitionMatrix=ciau.Markovchain@transitionMatrix,
                               countsTransitionMatrix=ciau.matrix, confidencelevel=.95)


text:
Q: Wrap different subclasses with same additional field Let's say I have some abstract class User, and then subclasses Owner and Client. Each of the two subclasses have some specific fields, but they both inherit common fields from the User. This is all OK, but in a specific situation I'd like to be able to wrap any instance of User with another field. Here is the example.
User.java
public abstract class User {

    private String email;

    private String password;

    private String name;

}

Client.java
public class Client extends User {

    private String salary;

    private String profit;

}

Owner.java
public class Owner extends User {

    private int numberOfClients;

    private double averageClientSalary;

}

Now in a specific case, I'd like to be able to wrap such instances with a login token. So no matter if it is a Client or the Owner instance, it should receive another field loginToken on top of all it's fields.
The use-case would be something like this.
Client client = new Client(email, password, name, salary, profit);

String loginToken = "123abc456";

UserLogin clientLogin = new UserLogin(client);
clientLogin.setLoginToken(loginToken);

// now this should be possible
clientLogin.getEmail(); // base class field
clientLogin.getSalary(); // derived class field
clientLogin.getLoginToken(); // field from a wrapper

So this UserLogin should be able to receive any subclass of User as constructor argument, and remain all of it's fields, just add the extra one, ie. loginToken.
Would something like this be possible and how?
Basically, what would the UserLogin class look like?

A: For base class fields and wrapper class fields (or to be precise getters as private fields are not accessible from subclasses) , you can add delegation methods in the wrapper UserLogin class.
But you could not use getters of the subclass as the wrapper manipulates a User declared variable.
public class UserLogin {

    private User user;
    private String token;

    public UserLogin(User user, String token) {
        this.user = user;
        this.token = token;
    }

    public String getEmail() {
        return user.getEmail();
    }

    public String getLoginToken() {
        return token;
    }

    // not possible for derived fields
    public String getSalary() {
        return user.getSalary();
    }

}

As workaround to do such a thing you could make UserLogin a generic class that provides a method that returns an instance of the specific User class.
For example :
public class UserLogin<T extends User> {

    private T user;
    private String token;

    public UserLogin(T user, String token) {
        this.user = user;
        this.token = token;
    }

    public String getEmail() {
        return user.getEmail();
    }

    public T getConcreteUser() {
        return user;
    }

    public String getLoginToken() {
        return token;
    }

}

You can now invoke :
UserLogin<Client> clientLogin = new UserLogin<>(new Client(), "token");

clientLogin.getEmail();
clientLogin.getConcreteUser()
           .getSalary();
clientLogin.getLoginToken();


text:
Q: Ideals in Gaussian integers
Let $R:=\mathbb{Z}[i]$. Prove that every nonzero prime ideal
  $\mathfrak{P}$ of $R$ belongs to one of the following families:

*

*$\mathfrak{P}=(1+i)R$

*$\mathfrak{P}=(a+bi)R$ where $a,b\in\mathbb{Z}$ and $a^2+b^2$ is an odd prime $p$ which is congruent to $1$ modulo $4$

*$\mathfrak{P}=pR$ where $p$ is an odd prime which is congruent to $3$ modulo $4$.
Hint: in case 3), let $\alpha\in R$ be written as $c+id$ with $c,d\in\mathbb{Z}$ and suppose $\alpha\notin\mathfrak{P}$. Consider
  $\alpha\overline{\alpha}=c^2+d^2$; prove that $p$ does not divide
  $c^2+d^2$, so that there exists an integer $e$ such that
  $(c^2+d^2)e=1\bmod p$. Conclude that
  $\alpha\cdot\overline{\alpha}e=1\bmod\mathfrak{P}$.

I can't understand the hints that i'm given. I've proved that $p$ doesn't divide $c^2+d^2$, in fact $p=3\bmod 4$ implies that $p$ is also a Gaussian prime, so if it divides $c^2+d^2=(c+di)(c-di)$ then it should divide one of the two factors, which is impossible.
Hence, being $p$ a rational prime, not dividing $c^2+d^2$, it must be coprime to $c^2+d^2$ so that there exists $e$ such that etc. etc.
And now? I have proven that $\alpha$ is invertible modulo $\mathfrak{P}$. How can i use this?

A: The definition of a prime ideal $P \subset R$ is that for any $x,y \in R$ such that $xy \in P$ either $x \in P$ or $y \in P$ (or both).
In your case, let $x,y \in R$ be such that $xy \in P$. Assume for a contradiction that neither $x\in  P$ nor $y \in P $. Then both $x$ and $y$ are invertible mod $P$(as you've already proved) and therefore so is their product! So their product cannot possible lie in $P$(it would imply $1 \in P$) unless $P=R$ which is clearly impossible.


text:
Q: Find infinite collection of open sets in $\Bbb R$ whose intersection is open and nonempty Can someone please suggest what such a collection may be like?

A: Here is one way to construct such a collection:
Take any open set $S \subset \mathbb{R}$, then take an infinite collection of open supersets of $S$.  Add to this collection $S$ itself.  This will ensure that the intersection is $S$, which as we know is open.

A: In $\Bbb{R}$ Fix some $\epsilon >0$. Consider $$\bigcap_{x> \epsilon}^\infty (-x,x) \cap \left(\frac{-\epsilon}{2},\frac{\epsilon}{2}\right)$$ This will work since I have used $\epsilon$ to prevent the intervals from shrinking to zero.
$\bf{\text{EDIT FOR PROOF REQUESTED BELOW}}$:
Let $\{U_\alpha\}_{\alpha \in \lambda}$ be a collection of distinct open subsets of $\Bbb{R}$ indexed by the infinite set $\lambda.$ Show if there exists $\beta \in \lambda$ such that $U_\beta \subseteq U_\alpha$ for all $\alpha \in \lambda$ then $$\bigcap_{\alpha \in \lambda- \{\beta\}}U_\alpha$$ is open in $\Bbb{R}$.
Pf: By definition of intersection it is obvious that  $$\left(\bigcap_{\alpha \in \lambda}U_\alpha \right)  \subseteq U_\beta$$ Further, since $U_\beta \subseteq U_\alpha$ for all $\alpha$ then $$U_\beta \subseteq \left(\bigcap_{\alpha \in \lambda}U_\alpha \right)$$ By double containment we have $$U_\beta = \left(\bigcap_{\alpha \in \lambda}U_\alpha \right)$$ so we know $\left(\bigcap_{\alpha \in \lambda}U_\alpha \right)$ is an open set. $\Box$

A: I think this could work as well,
$$\bigcap_{n \geq 2} (0, 1 - 1/n)= (0,1/2).$$


text:
Q: Syntax highlighting for shell sessions? Edit: I've opened an issue for this in the code-prettify project on GitHub.

The author of the question Why does bash login shell break here-doc command string argument? noted in the comments that:

As expected, the broken SE syntax colouring now indicates to inexperienced eyes that the '> ' prompts are part of typed strings and the warning messages further destroy any highlighting utility.

I turned off the syntax highlighting by adding the <!-- language: lang-none --> tag, as described in the relevant meta thread:

*

*What is syntax highlighting and how does it work?
However, it got me to wondering: why doesn't Stack Exchange support proper shell session syntax highlighting?
Oddly enough, including the tag <!-- language: shell_session --> does turn on some sort of syntax highlighting, even though I don't see shell_session anywhere in the supported languages list in the above linked Meta thread.
However, the syntax highlighting isn't great—it looks more like shell syntax highlighting than shell session syntax highlighting.  As noted, it doesn't properly identify the default PS2 prompt of > and highlights it as though it is part of the quoted string.
GitLab.com has shell_session syntax highlighting, as mentioned in this mailing list post.  I checked and GitLab's highlighting does properly handle PS2 detection, and even error message detection.
Since the shell_session tag isn't even mentioned in https://github.com/google/code-prettify (and so I'm not sure why it does anything at all here on Stack Exchange), how can I propose improvements to the Stack Exchange functionality of shell_session highlighting so it can improve to be more like GitLab's?

Here is what GitLab's syntax highlighting looks like:

And here is Stack Exchange's highlighting of the same block:


text:
Q: vector has no member "function" I have two classes (Vector3 is an irrelevant class here):
class Room {
  public:
    Room();

  private:
    vector<Button> roombuttons[3];
};

and
class Button {
  public:
    Button();
    Button(Vector3 pos);

    void SetPos(Vector3 pos);

  private:
    Vector3 pos;
}

If I want to define Room() as:
Room::Room() {
  roombuttons[0].SetPos(100,100,0);
}

I get an error saying class "std::vector<Button, std::allocator<Button>>" has no member "SetPos"
Why am I not able to call the SetPos function of the Button class on Button instances in a vector?
I want to have a Room instance with a couple Buttons that are stored in some kind of array so that I can use them like elements of an array.

A: The problem is that you are declaring roombuttons as an array of vector objects, thus roombuttons[0] is accessing the 1st vector, not the 1st Button.  So the error is correct, vector does not have a method named SetPos().  You would need something more like this instead:
roombuttons[0][0].SetPos(100,100,0);

But that is not what you are really asking for.  You want an array of Buttons, so either

*

*change your array to be a single vector instead, and then populate it in the constructor:
class Room {
  public:
    Room();

  private:
    vector<Button> roombuttons;
};

Room::Room() : roombuttons(3) {
  roombuttons[0].SetPos(100,100,0);
  ...
}

*or, just get rid of the vector since you know up front how many Buttons you want:
class Room {
  public:
    Room();

  private:
    Button roombuttons[3];
};

Room::Room() {
  roombuttons[0].SetPos(100,100,0);
  ...
}

A: just do
vector<Button> roombuttons;

instead of
vector<Button> roombuttons[3];


text:
Q: How is a metric space a topological space? I learned about metric spaces and topological spaces but I don't see how they correlate.
How does a metric space follow the properties of a topological space.

A: You call a set open if it contains a ball of positive diameter around each of its points. It can be (easily) shown this follows the usual axioms of a topological space.
It can be partially reversed (not so easy): Every $T_3$ space with a countable basis is metrizable.

A: Let $(X,d)$ be a metric space. Then, define $B_\epsilon(x) = \{y \in X| d(x,y) < \epsilon\}$ to be the ball with radius $\epsilon$ around $x$. You can now define a topology on $X$ as follows:
A subset $U \subset X$ is open, if, for all $x \in U$, there is $\epsilon > 0$ such that $B_\epsilon(x)$ is contained in $U$. One easily checks that the so defined collection of open sets defines a topology.
Note that, if $X = \mathbb{R}^n$ and $d$ is the usual Euclidean distance, this coincides with the usual Euclidean topology on $\mathbb{R}^n$.

A: The classical answer is that given any metric space, using open balls you can define a topology (where a set is open if every point in it brings with it an open ball contained in the set). In fact, metric spaces and topological spaces are much more closely related than that, if one interprets metric spaces in a suitable generalized form. Using Flagg's notion of value quantale (a certain partially ordered sets with just the right structure to define metric spaces valued in it), it is still the case that every such generalized metric space induces a topology, but now in fact any topology is metrizable, i.e., there exists a value quantale tailored for it and a metric structure inducing the given topology. This correspondence can be made to explicit give an equivalence between the category of topological spaces and the category of generalized metric spaces.

A: You can equip any metric space with a valid topology:
Topologies can be defined by designating a generating basis. In the case of a metric space, $X$, with a metric, $d$, we can consider our generating neighborhoods to be any set of the form $\{y\in X|d(y,x)<\epsilon\}$ given some center point $x\in X$. This is usually called the "metric topology".


text:
Q: Efficient implementation of Element product of Ublas Matrix makemake I benchmarked the default function for element by element product of Boost Ublas Matrix and found that element_prod was way slower than if I wrote my own implementation with simple for loops. So, I decided to write my own version.
I am trying to achieve code that will do element by element matrix multiplication with the help of a statement as followed :
matrix m1, m2, m3;
m3 = m1 * m2;

Here, I would like to make use of C++11 move semantics with regards to efficiently returning the output of the multiplication.
This is what I have so far.
#include "boost\numeric\ublas\matrix.hpp"
#include <Windows.h>
typedef boost::numeric::ublas::matrix<float> matrix;
void ElemProd();
const size_t X_SIZE = 400;
const size_t Y_SIZE = 400;
const size_t ITERATIONS = 500;
matrix operator*(const matrix &m1, const matrix &m2)
{
    size_t rows = m1.size1();
    size_t cols = m2.size2();
    matrix temp(rows,cols);
    for (size_t i = 0; i < rows; i++)
    {
        for (size_t j = 0; j < cols; j++)
        {
            temp(i, j) = m1(i, j) * m2(i, j);
        }
    }

    //return std::move(temp);
    return temp;
 }

void ElemProd()
{
     matrix m1(X_SIZE, Y_SIZE);
     matrix m2(X_SIZE, Y_SIZE);
     for (size_t i = 0; i < X_SIZE; i++)
     {
         for (size_t j = 0; j < Y_SIZE; j++)
         {
             m1(i, j) = 2;
             m2(i, j) = 10;
         }
     }

         matrix m3 = m1; // simply to allocate the right amount of memory for m3, to be overwritten.
         m3 = m1 * m2;
   }

Here, in the operator* overload, I had to create a temp matrix to store the result of the calculation. I think this is adding a significant overhead. Any suggestions how to work around this?
Another option is to make the arguments to the overload as not const, and overwrite one of the matrices and return it, but I think this is very risky long term, I would prefer to avoid it.
Consider the case where I want something like this :

matrix m = m1 * m2 * m3 * m4 * m5 * m6;

Here, you can see that I am allocating memory for temp 6 times in my implementation. m should only have to be allocated once. Further allocations are simply overhead.


text:
Q: How to extract a Teradata .TPT file with UTF-8 encoding We are currently extracting several Teradata .TPT files that we will upload to AWS S3, however the files are coming with ANSI encode
I need them to come with encode UTF-8

A: You must specify the character set in your TPT script. At the top add:
USING CHARACTER SET UTF8

The tricky part is that UTF8 here has 3 bytes per character, so in your DEFINE SCHEMA you must triple the size of each field.
For example if your schema looks like:
   DEFINE SCHEMA s_some_export
    (
            status VARCHAR(20),
            userid VARCHAR(20),
            firstname VARCHAR(64),
    );

You'll have to triple the values to accommodate your UTF8 characters:
   DEFINE SCHEMA s_some_export
    (
            status VARCHAR(60),
            userid VARCHAR(60),
            firstname VARCHAR(192),
    );

Sometimes, because I'm lazy, I define my TPT with USING CHARACTER SET UTF16 so that I only need double each field size (the math is easier). BUT it means I have to convert it to UTF8 after extraction. In Linux this would just be iconv  -f UTF-16LE -t UTF-8 myoutputfile.csv > myoutputfile.utf8.csv
Some caveats:

*

*If your table's field is defined as CHAR and CHARACTER SET LATIN then you may run into column size issues with your schema. see here

*Dates and Timestamps can get wierd as they don't need to be doubled so defining them as VARCHAR in your schema can get you into trouble. You may have to fuss around a bit here. My suggestion would be to change the view from which you are selecting the data for you TPT and CAST(yourdate AS VARCHAR(10)) as yourdate and then use VARCHAR(30) in your schema so you don't have to think about the field types while defining your schema. This means extra CPU overhead in your extraction, but unless you are running tight on resources I think it's worth it. I'm also very lazy that way and always happy to just get the damned TPT to extract data without much debugging.


text:
Q: animate jQuery attribute can't use variables? After declaring height() variables for multiple loaded elements which have different variables for each, the animate() function doesn't seem to be loading the variable excHeight.
What would be the best way to use the value of excHeight for the animate() as below?
$(".exPand a").click(function (event) {
    event.preventDefault();

    var post_id = $(this).attr("rel");

    var postHeight = $(this).closest('.boxy')
                            .find('.articleImageThumb')
                            .height();

    var excHeight = $(this).closest('boxy')
                           .find('.articleImageThumb')
                           .find('.initialPostLoad')
                           .height();

    $.ajaxSetup({cache:false});

    $(this).closest('.boxy')
           .animate({height: postHeight+excHeight}, 1000);

    $(this).closest('.boxy')
           .find('.articleImageThumb')
       .animate({top: 0}, 1000);

    $(this).closest('.boxy').find('.articleTitle')
    .animate({bottom: excHeight}, 1000);

    $(this).closest('.boxy').find('.postmetadata')
    .animate({bottom: excHeight}, 1000);
});

A: Seems like it is not working because you forgot "dot" in boxy class name: var excHeight = $(this).closest('boxy') , must be like this: var excHeight = $(this).closest('.boxy')


text:
Q: Connection details for Priority Web API sand box (demo environment) According to the Web API introduction page, I have to connect to the development environment by calling the login(...) function passing it the following configuration object:
{
    username: '<username>',
    password: '<password>',
    url: '<url>',
    tabulaini: '<tabula.ini>',
    language: <language>,
    company: '<companyName>',
    appname: 'Customers'
}

Does the Prioritysoftware provides connection settings details (username, password, url, etc.) for Priority Web API demo environment as it provides for Priority REST API demo environment (using the following postman collection)?

A: Yes it does. Try
var configuration = {
    username: 'apidemo',
    password: '123',
    url: 'https://www.eshbelsaas.com/ui',
    tabulaini: 'tabmob.ini',
    language: 3,
    company: 'usdemo'
};


text:
Q: How to do load test for grpc services, Any sample code will be appreciated I am having trouble load testing gRPC services. Is there any way or tool to do that?
I tired Jmeter but looks like it does not support.
{
  "space_id": "3e9202b2-6d65-4651-96e5-af80ce51df70",
  "external_id": "5678",
  "anonymous": true
}

A: there are few existing load testing tools by community such as ghz.sh.


text:
Q: Scraping Facebook pages with Goutte I'm attempting to scrape facebook pages with Goutte in order to gather the 'created date' of a page.
This is not accessible via the Graph API.
In testing, I am able to retrieve all links from pages like tutsplus and symfony-project however when I attempt to access a page like 'https://www.facebook.com/151116474914629' it returns '2' links which is incorrect.
Code:
use Symfony\Component\DomCrawler\Crawler;
use Goutte\Client as Goutte;

public function goutte()
{
    $url_to_traverse = 'https://www.facebook.com/151116474914629';

    $client = new Goutte();
    $crawler = $client->request('GET', $url_to_traverse);
    $status_code = $client->getResponse()->getStatus();
    if($status_code==200){
        $a_count = $crawler->filter('a')->count();
    }
    return $a_count;
}

Any ideas on retrieving the full pages contents?

A: With Facebook, the vast majority of the content of the page is generated dynamically - multiple Ajax calls and so on.  This makes it very, very difficult to scrape.  And of course for any page that's generated dynamically, the "created date" is really the date you request the page, every time.
In the context of web pages, I don't know of an obvious way to obtain a creation date, but the modification date is included as an optional part of the HTTP 1.1 specification.  So, many (but not all) websites will send the Last-Modified header along with the web page.  This header can be modified programmatically and is fairly meaningless on dynamic web pages, so I wouldn't rely on it.
You're out of luck with Facebook in any case.  There's no Last-Modified header (I've checked, including following this particular page's redirect).  And I'm not sure what else you could look for connected to this page, to find the creation date.
In relation to other Goutte operations on this page, and bearing in mind what I've said about dynamic page creation, you can still retrieve some content.  Just watch out for redirections.  Using cURL at the command line, you can see that the web page redirects from https://www.facebook.com/151116474914629 to https://www.facebook.com/PhilzCoffeeCastro:
me@here:~$ curl --head https://www.facebook.com/151116474914629
HTTP/1.1 301 Moved Permanently
Location: https://www.facebook.com/PhilzCoffeeCastro
[snip]
Date: Tue, 16 Sep 2014 12:54:01 GMT
Connection: keep-alive
Content-Length: 0

Note "Moved Permananently".
So you need to test for the redirection and make sure you're scraping the correct page.
In summary:

*

*Don't use Goutte to find the last modified time.  You need to parse HTTP headers, so cURL is a better choice.

*Dynamic pages have no meaningful "created date" and are very difficult to scrape anyway

*Always check for page redirects

If you want to find the date when a page first appeared on the Internet, I would suggest trying a different strategy completely: http://www.labnol.org/internet/search/find-publishing-date-of-web-pages/8410/
Disclaimer: I do not know what "the Graph API" is, so I admit I may not fully understand the context of your question.  I hope some of the above is helpful though.


text:
Q: The deadline for OAuth re-review is March 31st 2019 and may take some weeks We have an app which uses OAuth to connect to mailboxes via IMAP to Gmail.
We have been advised that we need to re-verify our OAuth screen by March 31st and this may take some weeks. We have submitted the re-review but I wanted to know if the integration will break after March 31st if it is still pending review.
I've already tried to find support topics on this question but advised to come here.

A: You have until May 15th to complete the verification process. If you are in the process of completing requirements, refer to this section of the FAQ: https://support.google.com/cloud/answer/9110914?hl=en#how-long


text:
Q: How to convert an editbox to a number assembly? In TASM for Win32, I have this code:
;------- Edit1 Create ----------------
push    L 0
push    [hInstEdit1]
push    idEdit1
push    [newhwnd]
push    L 20
push    L 200
push    L 50
push    L 130
push    L WS_CHILD+WS_VISIBLE+WS_BORDER+ES_LEFT+ES_NOHIDESEL+ES_AUTOHSCROLL
push    L 0
push    offset EClassName
push    L 0
call    CreateWindowEx
mov [hEdit1],EAX

push    L SW_SHOW
push    [hEdit1]
call    ShowWindow
push    [hEdit1]
call    UpdateWindow

I need to get the number entered by the user in this editbox.
The number must be placed in the register.
Who knows how to do this?
PS I think you need to use the function GetDlgItemInt

A: Here is the way found on the Internet
                            ; Input:
    mov esi, offset szMsg1  ; esi - str
    dec msgLength
    mov ecx, msgLength      ; ecx - length str
                            ; Output:
                            ; EAX = integer value
string_to_int:
    xor ebx,ebx             ; clear ebx
next_digit:
    movzx eax, byte ptr [esi]
    inc esi
    sub al,'0'              ; convert from ASCII to number
    imul ebx,10
    add ebx,eax             ; ebx = ebx*10 + eax
    loop next_digit         ; while (--ecx)
    mov eax,ebx


text:
Q: Excel Macro to run automatically for change in cells at different times independent of each other I have a spreadsheet which will be used as a form by a number of users, and based on a few pull down boxes selection, a number of cells will change value (Independently of each other).
I have several macros which I want to run when the cells change (again independently, not collectively)
I already have one which runs using worksheet change by target value within the worksheet, but can't get anymore to work with this code.
A bit of a novice when it comes to this sort of stuff and need some help - using latest version of excel.


text:
Q: What functions are cached in Haskell? I have the following code:
memoize f = (map f [0 ..] !!)

fib' 0 = 1
fib' 1 = 1
fib' n = fib' (n - 1) + fib' (n - 2)

fibMemo n = memoize fib' n
fibMemo'  = memoize fib'

(I am aware of that fibonacci implementation has exponential time complexity and does not use the cache)
The first time I execute fibmemo' 30 it takes 3 seconds, and the second time it takes ~0 seconds, because the result is cached. But the first version, fibmemo, does not get the result cached, it always takes 3 seconds to execute. The only difference is the definition (which as far as I know are equivalent).
So my question is, what functions are cached in Haskell?
I have already read https://wiki.haskell.org/Memoization and does not resolve my question.

A: Essentially, the functions you defined behave as the following ones:
fibMemo n = let m = map fib' [0..] in m !! n
fibMemo'  = let m = map fib' [0..] in (m !!)

Why is fibMmemo' more efficient? Well, we can rewrite it as
fibMemo'  = let m = map fib' [0..] in \n -> m !! n

which makes it more clear that the single list m gets created before n is taken as input. This means that all the calls to fibMemo' will use the same m. The first call evaluates a part of m slowly, and the successive calls will reuse that cached result (assuming the call hits the cache, of course, otherwise another part of m is evaluated and cached).
Instead, fibMemo is equivalent to
fibMemo = \n -> let m = map fib' [0..] in m !! n

which takes the input n before the list m gets created. So, each call gets a new cache, which is pointless, since the whole purpose of a cache is that it is reused later.
The order of the lambda \n -> vs the let m = .. matters a lot in terms of the performance. Since m = .. does not use n, technically the let m = .. can be floated outwards, essentially turning fibMemo into fibMemo', without affecting the semantics. However, as you discovered, this does not preserve performance, in general!
This is indeed an optimization that GHC could perform, but does not, because it can easily make the performance significantly worse.


text:
Q: Spark NullPointerException with saveAsTextFile I'm getting a NPE when trying to coalesce and save out an RDD.
Code works locally, and works on the cluster in the scala shell, but throws the error when submitting it as a job to the cluster.
I've tried printing out using a take() to see if the rdd contains some null data, but this throws the same error - pain because it works ok in the shell.
I'm saving out to HDFS and have the full url path in the variable - model saves with this method fine during MLLib training phase.
Any ideas much appreciated!
Scala Code (Whole Prediction Func):
//Load the Random Forest
val rfModel = RandomForestModel.load(sc, modelPath)

//Make the predictions - Here the label is the unique ID of the point
val rfPreds = labDistVect.map(p => (p.label, rfModel.predict(p.features)))

//Collect and save
println("Done Modelling, now saving preds")
val outP = rfPreds.coalesce(1,true).saveAsTextFile(outPreds)
println("Done Modelling, now saving coords")
val outC = coords.coalesce(1,true).saveAsTextFile(outCoords)

Stack Trace:
    Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 6.0 failed 4 times, most recent failure: Lost task 0.3 in stage 6.0 (TID 40, XX.XX.XX.XX): java.lang.NullPointerException
    at GeoDistPredict1$$anonfun$38.apply(GeoDist1.scala:340)
    at GeoDistPredict1$$anonfun$38.apply(GeoDist1.scala:340)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
    at scala.collection.Iterator$$anon$10.next(Iterator.scala:312)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)

A: Spark operations are divided into lazy transformations and actions.
A lazy transformation on a RDD is performed when an action is called on the RDD.
So when you execute a transformation it is just stored as an operation to be performed.
The saveAsTextFile method is an action meanwhile the map operation is transformation.
If there is any issue on a transformation step, it will show as an issue at the action level step in which the transformation was called.
So you might have an issue during the map operation in which there is a null value in some of the field which is most probably causing your NPE issue.


text:
Q: Image overlay on profile Picture FB or adding Frame to Picture Want to make a tool to add any Image overlay on profile Picture FB. I am looking in to few post regarding this. I am new to it. Is there any FB api for the same. Or it needs to be designed separately. Please if any one can help me out.
Actually I want to add a frame to the profile picture of the user logged in on single link or button clicked.

A: Have you looked at the Facebook's Profile Expression Kit at all? There is a section on uploading profile pictures and videos.
EDIT:
Graph API has User Picture to get a profile picture. Make your own edits to the picture (add the frame) and then use upload API.


text:
Q: Any tools to beautify the nested NSDictionary result Is there any tools, including online service and macOs app, to beautify the nested NSDictionary result like this?
   {
        id = 1;
        testName = my name;
        createDate = 20021023;
        likeNumber = 0;
        statusList = ({
                appleId = 1;
                orangeName = 81;
                itsStatus = YES;
        });
        text = test;
        type = Text;
   },

I mean collapse(close and open) the tree nodes easily.
Currently ,there are many online tools for this purpose when it comes to JSON like jsonformatter.

A: As Fonix mentioned, the best way to convert NSDictionary to JSON and then use JSON tools for this purpose:
+(NSString *)dictionaryToJson:(NSDictionary *)dictionary {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];

    NSString *jsonString;
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
        jsonString = [error localizedDescription];
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}


text:
Q: How to implement multitenancy for redis in spring boot I am working on making my whole application multi-tenanted but stuck on redis. So far I created a map of JedisConnectionFactory and tried to pass it to RedisTemplate but it throwing java.lang.IllegalArgumentException: template not initialized; call afterPropertiesSet() before using it.
Below are code snippets:
@Component
public class RedisConfiguration {

    @Autowired
    private DSConfig dsConfig;

    private Map<String,JedisConnectionFactory> jedisConnectionFactoryMap = new HashMap<>();

    private static Logger LOGGER = LoggerFactory.getLogger(RedisConfiguration.class);

    @PostConstruct
    public void initializeJedisConnectionFactories() {

        for(DatasourceDetail datasourceDetail : dsConfig.getDatasources()) {
            RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
            redisConfig.setHostName(datasourceDetail.getRedisHost());
            redisConfig.setPassword(RedisPassword.of(datasourceDetail.getRedisPassword()));
            redisConfig.setPort(Integer.parseInt(datasourceDetail.getRedisPort()));
            JedisClientConfiguration configuration = JedisClientConfiguration.builder().usePooling().
                    poolConfig(new JedisPoolConfig()).build();
            jedisConnectionFactoryMap.put(datasourceDetail.getTenantId()
                    ,new JedisConnectionFactory(redisConfig,configuration));
        }
        LOGGER.info("Connection factory count " + jedisConnectionFactoryMap.size());
    }

    public RedisTemplate< String, Object > redisTemplate() throws Exception {
        final RedisTemplate< String, Object > template =  new RedisTemplate< String, Object >();
        template.setConnectionFactory( jedisConnectionFactory() );
        template.setKeySerializer( new StringRedisSerializer() );
        template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        return template;
    }

    JedisConnectionFactory jedisConnectionFactory() throws Exception {
        if(TenantContext.getCurrentTenant()==null) {
            throw new Exception("No tenant context found");
        }
        LOGGER.info("Returning redis connection for tenant" + TenantContext.getCurrentTenant());
        return jedisConnectionFactoryMap.get(TenantContext.getCurrentTenant());
    }
}

And I am using redis template as below:
@CrossOrigin("*")
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisConfiguration redisConfiguration;

    @GetMapping("/set")
    @ResponseBody
    public Object set(@RequestParam(value = "key", required = true) String key,
                      @RequestParam(value = "value", required = true) String value) throws Exception {
        redisConfiguration.redisTemplate().opsForValue().set( key,value );
        return true;
    }

    @GetMapping("/get")
    @ResponseBody
    public Object get(@RequestParam(value = "key", required = true) String key) throws Exception {
        redisConfiguration.redisTemplate().opsForValue().get(key);
        return true;
    }
}

Is there anyway I can implement this in a better way or is there any other way which spring redis provides?

A: Finally I was able to resolve by calling afterPropertiesSet() explicitly.


text:
Q: Separate Config Files for Separate Users Here we have a winforms desktop application used by various users. Each user runs the application locally. That said the build folders are separate for each user. They also have different set of config keys under their local application config files to run the app (different connection strings and key options). You may guess how painful updating versions is.
My purpose is to put this winforms desktop application in a shared folder and share it to each user. The challenge here is their configurations being separate.
I tried merging the separate keys with different names and using conditions under the code but the job seems massive.
Is there any way to collect all these separate config files under the bin folder and switch between them depending on the username? What's the easiest way approaching this problem?
Thank you.

A: My proposition is to use a modified .NET settings mechanism. In general you can have application specific and user specific settings. In this case we would like to use the user settings.
The problem with this approach is that user settings are not stored in the bin folder but somewhere else i.e. %userprofile%\appdata\local... (here are details). However, you can override this behaviour by writing a custom settings provider. Luckily someone has already did it. CustomSettingsProvider from this answer works like a charm.
To sum here is a solution:

*

*In order to add a settings file to you project right click the
project and then select Add -> New item... Finnally, find
Settings File template. If you double click the added file a designer will pop up. Let's assume that this file is called MySettings.

*Define some user specific settings.

*Add CustomSettingsProvider to your project.

*Find MySettings class in the project and add the following attribute to it:
[System.Configuration.SettingsProvider(typeof(CustomSettingsProvider))].

*

*Before using settings you have to specify a path to a file with them. I suggest to do it as the one of the first things in your application. In the following example settings files be created in a current folder and their names will contain a user name:

MySettings.Default.SettingsKey = $@".\user_{Environment.UserName}.config";

*

*If a file with settings does not exist CustomSettingsProvider will create an empty one.

*When closing the application call MySettings.Default.Save(); to save user settings to a file.

*Run your application once on your own just to create a template file. Then make a copy of this template for other users changing their names accordingly.

*The disadvantage of my approach is that you will have no connection strings section in settings file. So reference to ConfigurationManager.ConnectionStrings you will have to replace with references to MySettings.PropertyWithConnectionString.


text:
Q: CoreBluetooth Event Backgrounding - no events in iOS 6.0.1 and higher I work with my ble device in event background mode. So i do not specify any special in info.plist for this.
I have a two troubles here:
1) In iOS 5.1.1 events appear without accessory name.
So when events from ble come when application is in the background i see The "" accessory would like to open "MyAppName"
But in
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

i see the name in the peripheral.name property and advertisementData also contains key kCBAdvDataLocalName @"MyDeviceName"
2) In iOS 6.0.1 and higher the events do not come from background never...
I use ti cc2540 stack, and this is my structs for advertise:
// GAP - SCAN RSP data (max size = 31 bytes)
static const uint8 scanRspData[] =
{
  // complete name
  0x05,   // length of this data
  GAP_ADTYPE_LOCAL_NAME_COMPLETE,
  'O',
  'b',
  'd',
  '2',
  // connection interval range
  0x05,   // length of this data
  GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE,
  LO_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),   // 100ms
  HI_UINT16( DEFAULT_DESIRED_MIN_CONN_INTERVAL ),
  LO_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),   // 1s
  HI_UINT16( DEFAULT_DESIRED_MAX_CONN_INTERVAL ),

  // Tx power level
  0x02,   // length of this data
  GAP_ADTYPE_POWER_LEVEL,
  0       // 0dBm
};

static const uint8 advertData[] =
{
  0x02,   // length of this data
  GAP_ADTYPE_FLAGS,
  DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED,

  // service UUID, to notify central devices what services are included
  // in this peripheral
  0x03,   // length of this data
  GAP_ADTYPE_16BIT_MORE,      // some of the UUID's, but not all
  LO_UINT16( RPC_SERVICE_UUID ),
  HI_UINT16( RPC_SERVICE_UUID ),
  0x05,   // length of this data
  GAP_ADTYPE_LOCAL_NAME_COMPLETE,
  'O',   // 'O'
  'b',   // 'b'
  'd',   // 'd'
  '2' //2
};

What's wrong? Help please

A: Dude you DO need to specify the background mode in your info.plist.....
Under Required Background Modes, put in "App shares data using CoreBluetooth" or "App communicates using CoreBluetooth"... (or both, depending on what your app functionality requires).
Then you'll be able to receive background events.


text:
Q: How to use QCOMPARE with two custom classes within custom namespace? I have a class MyClass within a namespace MyNameSpace, and I define a == operator in test unit, so, classes could be copmared.
The unit test doesn' compile 'cause theres no operator == match for const MyNameSpace Myclass, MyNamespace MyClass, even if I have it in unit test.
Without using a namespace works as expected.
Lets say we have:
namespace MyNamespace {
class MyClass {
public :
    QString a;
};
}

and in test unit:
....
#include "myclass.h"
using namespace MyNamespace;
....

test_case1 {
    MyClass myClass;
    myClass.a = "test";

    MyClass myClass2;
    myClass2.a = "test";

    QCOMPARE(myClass, myClass2); //Fails to compile
}

operator==(const MyNamespace::MyClass &class1, const MyNamespace::MyClass &class2) {
    return (class1.a == class2.a);
}

A: I solved by wrapping the definition of operator == into std namespace
namespace std {
    bool operator==(const MyNamespace::MyClass class1, const MyNamespace::MyClass class2)
    {
        return (class1.a == class2.a);
    }
}


text:
Q: HQL(hibernate) timestamp range match I need to write a query to get an object between a range of time, currently the query looks like this:
Timestamp from = ...
Timestamp to = ...

getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString());

However, this doesnot work for obvious reasons. How can I format the timestamp to be acceptable by the query.

org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: 16 near line 1, column 123 [from Person ml where ml.lastModifiedOn>=2010-02-12 16:00:21.292 and m1.lastModifiedOn

A: You're missing single quotes in your current query. The following should work:
from Person ml where ml.lastModifiedOn
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292'

Note that I don't know why you're not passing Date instances to the following query:
from Person ml where ml.lastModifiedOn between :from and :to

Are you using java.sql.Timestamp here? If yes, you shouldn't.

A: You can simply pass a long (from.getTime()) in the comparison, if it is represented as long in the DB.
Otherwise you can use these functiomns: second(...), minute(...), hour(...), day(...), month(...), and year(...)

A: How about something like this?
    String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?";
    Date from = ...;
    Date to = ...;

    getHibernateTemplate().find(sql, new Object[] {from,to});

A: If you want to query for something between you can do the following:
 public List findPerson() {
   Date from = ...;
   Date to = ...;
   return entityManager.createQuery(
     "SELECT p from Person p WHERE p.lastModifiedOn BETWEEN ?1 AND ?2")
     .setParameter(1,from, TemporalType.DATE)
     .setParameter(2,to, TemporalType.DATE).getResultList();
}

You might need to change TemporalType.DATE to whatever you are using


text:
Q: Creating related records in visual force page matching by record Id I am started learning standard controller in visualforce. I have two custom object: Timesheet__c & Timeentries__c.I want to display the timeentries__c details in timesheet__c matching with Id.Can anyone help me to solve it.
Code
<apex:page standardController="Time_Entry__c">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="Time Entry Details">
                <apex:inputField value="{! Time_Entry__c.User_Name__c}"/>
                <apex:inputField value="{! Time_Entry__c.Start_Date_Time__c}"/>
                <apex:inputField value="{! Time_Entry__c.End_Date_Time__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Save}" value="Save"/>
                <apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>

A: Displaying Related Lists for Custom Objects
Displaying custom objects and their related lists with Visualforce is very simple.
Suppose you have three custom objects: MyChildObject, MyMasterObject, and MyLookupObject. MyChildObject has a master-detail relationship with MyMasterObject (which is the master). MyLookupObject also has a Lookup relationship with MyChildObject.
If you want to create a Visualforce page that displays the related list for MyMasterObject, use the following markup:
<apex:page standardController="MyMasterObject__c">
    <apex:relatedList list="MyChildObjects__r" />
</apex:page>

Reference:- Displaying Related Lists for Custom Objects in vf page