text:
Q: Java Synchronization issue - Main thread locked by the Coroutine implementation I am working on a game, and I have a problem with thread synchronizations. I have failed miserably to write this properly so main thread does not hang because of this. Short story its creating a locks in my main game thread (game loop). Ill do my best to provide the details, as much as I can. Issue is not related to the game framework, since this is my generic code which is locking everything.
Background:
Actions which are occurring in game are executed as Coroutines. Since there is no Coroutine feature in java, they have been implemented as a Coroutines with use of threads. Idea is to have interruptible actions, so when new action is started, execution of the current is paused until new one is finished. This behavior can have more depth as well.
Question:
How to properly do synchronization in this case, or how to properly protect my main thread loop ( the update method given in the example) so it does not hangs?
Here is the simplified use case. Each action performed ie move units, upgrade whatever completed was executed as a Coroutines or set of Coroutines.
Game init:
Player turn: move units around, upgrade stuff and so on
Ai turn:
    Calculate stuff
    Calculate more stuff
    Evaluate player strength
    Evaluate choke points
    More calculations
    Plan attack actions
    Move units>
        Create action (Coroutines) for every single move >
            Coroutine executing for move
                We have to fight in battle between two units
Create action (Coroutines) for every Combat
                        Coroutines executing for Combat
                       Coroutine for combat finished
            Coroutine for move finished
            repeat few times, sometime with and without battle
        Move Coroutine finished
    Move loop finished
Do more stuff
End ai turn;

I have been looking at the thread dumps to figure out whats causing this, and its the resume method.
Thread dumps where you can see the locks:
MAIN  Thread Locked :

"LWJGL Application" #18 prio=5 os_prio=0 tid=0x0000000020062800 nid=0x3b20 in Object.wait() [0x0000000022a7f000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        at java.lang.Object.wait(Object.java:502)
        at package_name.Coroutine$CoroutineExecutor.resume(Coroutine.java:319)
        - locked <0x00000006c3aeddd8> (a java.lang.Thread)
        at package_name.Coroutine.resume(Coroutine.java:409)
        at package_name.screens.GameScreen.render(GameScreen.java:430)
        at com.badlogic.gdx.Game.render(Game.java:46)
        at package_name.Game.render(Game.java:273)
        at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
        at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

   Locked ownable synchronizers:
        - None

OTHER Thread  Locked the MAIN Thread:
"Thread-6" #32 prio=5 os_prio=0 tid=0x0000000020a9e000 nid=0xc94 runnable [0x000000014d64e000]
   java.lang.Thread.State: RUNNABLE
        //Doing something here which might take a second or two
        at package_name.Coroutine$CoroutineExecutor$1.run(Coroutine.java:242)
        - locked <0x00000006c3aeddd8> (a java.lang.Thread)
        at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
        - None

Complete Coroutine Code:
package com.game.coroutine;

import com.game.coroutine.CoroutineDeath;
import com.game.coroutine.DeadCoroutineException;
import com.game.coroutine.InternalCoroutineException;
import com.game.coroutine.ResumeSelfCoroutineException;
import com.game.coroutine.YieldOutsideOfCoroutineException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An implementation of Lua-like coroutines.
 * Supports returning values with yield, nesting and it might be thread safe.
 */
public class Coroutine {
    private static final Logger log = LoggerFactory.getLogger(Coroutine.class);
    private static List<CoroutineExecutor> executorPool = new ArrayList<>();

    private final Runnable runnable;
    private Object returnValue;
    private boolean finished;

    /** I think CoroutineExecutor is used to map Lua coroutines (not present in Java) to Java Threads.
     *
     * */
    private static class CoroutineExecutor {

        private boolean running = true;
        private final Thread thread;
        private Coroutine coroutine;

        CoroutineExecutor() {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (thread) {
                        while (running) {
                            try {
                                if (!coroutine.finished) {
                                    coroutine.runnable.run();
                                }
                            } catch (CoroutineDeath | Exception e) {
                                log.error("Error while running coroutine runnable", e);
                            }
                            finally {
                                coroutine.finished = true;
                                coroutine.returnValue = null;
                                thread.notifyAll();
                                try {
                                    thread.wait();
                                } catch (InterruptedException e) {
                                    log.error("Error while waiting for coroutine runnable", e);
                                    Thread.currentThread().interrupt();
                                }
                            }
                        }
                    }
                }
            });
            thread.setDaemon(true);
            coroutine = new Coroutine(new Runnable() {
                @Override
                public void run() { }
            });
            coroutine.finished = true;
        }

        Object resume() {
            synchronized (thread) {
                if (thread.getState() == Thread.State.NEW) {
                    thread.start();
                }
                thread.notifyAll();
                try {
                    thread.wait();
                } catch (InterruptedException e) {
                    throw new InternalCoroutineException("Thread was interrupted while waiting for coroutine to yield.");
                }
                return coroutine.returnValue;
            }
        }

        void yield(Object o) {
            synchronized (thread) {
                coroutine.returnValue = o;
                thread.notifyAll();
                try {
                    thread.wait();
                } catch (InterruptedException interrupted) {
                    throw new CoroutineDeath();
                }
            }
        }

        void setCoroutine(Coroutine coroutine) {
            synchronized (thread) {
                if (busy()) {
                    throw new InternalCoroutineException("Coroutine assigned to a busy executor.");
                }
                this.coroutine = coroutine;
            }
        }

        boolean busy() {
            synchronized (Coroutine.class) {
                return !coroutine.finished;
            }
        }

        void reset() {
            synchronized (thread) {
                coroutine.finished = true;
                if (thread.getState() != Thread.State.NEW) {
                    thread.interrupt();
                    try {
                        thread.wait();
                    } catch (InterruptedException e) {
                        log.error("Error while waiting for coroutine runnable", e);
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        void kill() {
            synchronized (thread) {
                running = false;
                thread.interrupt();
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    log.error("Error while waiting for coroutine runnable", e);
                    Thread.currentThread().interrupt();
                }
            }
        }

        @Override
        public String toString() {
            return "Executor " + thread.getName();
        }
    }

    private Coroutine(Runnable runnable) {
        this.runnable = runnable;
        this.finished = false;
    }

    /**
     * Resumes/starts a coroutine. Return value is the object that the coroutine passed to yield
     */
    public static <T> T resume(Coroutine coroutine) {

        if (coroutine.finished) {
            throw new DeadCoroutineException("An attempt was made to resume a dead coroutine.");
        }

        CoroutineExecutor executor = getExecutorForCoroutine(coroutine);

        if(executor != null) {
            if (executor.equals(getCurrentExecutor())) {
                throw new ResumeSelfCoroutineException("A coroutine cannot resume itself.");
            }
            return (T) executor.resume();
        }
        else {
            log.error("CoroutineExcutor is null");
            return null;
        }
    }

    /**
     * A coroutine can use this to return a value to whatever called resume
     */
    public static void yield(Object o) {

        CoroutineExecutor coroutineExecutor = getCurrentExecutor();
        if (coroutineExecutor != null) {
            Coroutine coroutine = coroutineExecutor.coroutine;

            if (coroutine == null) {
                throw new YieldOutsideOfCoroutineException("Yield cannot be used outside of a coroutine.");
            }

            coroutineExecutor.yield(o);
        } else {
            log.error("CoroutineExcutor is null");
        }

    }

    /**
     * Creates a new coroutine that with the "body" of runnable, doesn't start until resume is used
     */
    public static synchronized  Coroutine create(Runnable runnable) {
        Coroutine coroutine = new Coroutine(runnable);
        CoroutineExecutor coroutineExecutor = getFreeExecutor();
        coroutineExecutor.setCoroutine(coroutine);

        return coroutine;
    }

    /**
     * Stops and cleans up the coroutine
     */
    public static synchronized void destroy(Coroutine coroutine) {
        CoroutineExecutor executor = getExecutorForCoroutine(coroutine);
        if (executor != null) {
            executor.reset();
        }
    }

    /**
     * Returns true if resuming this coroutine is possible
     */
    public static synchronized boolean alive(Coroutine coroutine) {
        return coroutine != null && !coroutine.finished;
    }

    /**
     * Shrinks the thread pool
     */
    public static synchronized void cleanup() {
        Iterator<CoroutineExecutor> it = executorPool.iterator();
        while (it.hasNext()) {
            CoroutineExecutor executor = it.next();
            if (!executor.busy()) {
                executor.kill();
                it.remove();
            }

        }
    }

    /**
     * Returns the current number of executors in the pool
     */
    public static synchronized int poolSize() {
        return executorPool.size();
    }

    private static synchronized CoroutineExecutor getCurrentExecutor() {
        for (CoroutineExecutor e : executorPool) {
            if (Thread.currentThread().equals(e.thread)) {
                return e;
            }
        }
        return null;
    }

    private static synchronized CoroutineExecutor getFreeExecutor() {
        for (CoroutineExecutor executor : executorPool) {
            if (!executor.busy()) {
                return executor;
            }
        }
        CoroutineExecutor newExecutor = new CoroutineExecutor();
        executorPool.add(newExecutor);
        return newExecutor;
    }

    private static synchronized CoroutineExecutor getExecutorForCoroutine(Coroutine coroutine) {
        for (CoroutineExecutor executor : executorPool) {
            if (coroutine.equals(executor.coroutine)) {
                return executor;
            }
        }
        return null;
    }
}

Finally the game loop in the main thread which get stuck because of resume which locked the coroutine thread object:
public boolean update() {
    Coroutine coroutine = coroutineQueue.peek();
    if (coroutine != null) {
        if (Coroutine.alive(coroutine)) {
            Event event = Coroutine.resume(coroutine);
            if (event != null) {
                broadcast(event);
            }
        } else {
            coroutineQueue.poll();
        }
    }
    return !coroutineQueue.isEmpty();
}

Please Advise on how to correct the synchronisation so at the end of the day, main loop does not get locked and all other Coroutines execute properly, in sequence and pause/continue if required.
Thank you all for taking the time to read this question.
Kind regards

A: If you do not provide a lock for the synchronized keyword, it defaults to using the object. But, in your case, these are all static methods, so it uses the class as the lock. So, all of your coroutines methods are locking on the same thing - the Coroutine class.


text:
Q: SSO for Laravel and moodle applications from WordPress I am in a need to have single sign-on (SSO) on my applications.
Basically, I have three applications in different directories. I have a WordPress(ecommerce) site running in the main folder of my domain and a Laravel application in a directory and a moodle(lms) application in a directory.
The idea is if I log into my WordPress site, I don't need to sign in on the other two applications and able to access the Laravel and moodle applications.
I will give access to moodle pages from laravel app. What is the best approach to achieve this?

A: Moodle has OAuth2, I'm guessing Wordpress has it too?
https://docs.moodle.org/311/en/OAuth_2_authentication
So maybe use an oauth2 server, eg Okta or OneLogin

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swagger UI Not adding Header to Requests I am using Swagger 2.0 and Swagger UI 3.0.3.
In my api_definition.yaml I have the following before my paths:
swagger: '2.0'

################################################################################
#                  Host, Base Path, Schemes and Content Types                  #
################################################################################
# Metadata
info:
  version: v1
  title: Microservice
  description: Microservice API!

host: sandbox

basePath: '/apps/fiji/v1'
schemes:
  - http

securityDefinitions:
  apikey:
    type: apiKey
    name: X-Access-Token
    in: header

security:
  - apikey: []

produces:
  - application/json
consumes:
  - application/json

This adds an Authorize button the the Swagger UI where the user can paste in their API key. I would like this API key to be sent in the request header of every request.  This does not happen though and I'm not sure why.  Am I missing something?
EDIT:
The request seems to send and I get back 401 Unauthorized.
Chrome Dev Tools shows the following Request Headers:
GET /apps/fiji/v1/getCPICountries HTTP/1.1
Host: sandbox
Connection: keep-alive
accept: application/json
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
content-type: application/json
Referer: http://sandbox/apps/fiji/vendor/swagger-ui/dist/index.html?url=http://sandbox/apps/fiji/swagger/api_definition.yaml
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

I have the paths set up as:
# API Paths
paths:
  # getCPICountries endpoint
  /getCPICountries:
    # HTTP operations
    get:
      # Describe this verb here. Note: you can use markdown
      description: |
        Returns a list of countries and country codes
      produces:
      - application/json
      security:
        - auth:
          - role_admin
      # Expected responses for this operation:
      responses:
        # Response code
        200:
          description: Successful response
          # A schema describing your response object.
          # Use JSON Schema format
          schema:
            properties:
              data:
                type: array
                items:
                  $ref: '#/definitions/CPIResponse'

And definitions as follows:
definitions:
  CPIResponse:
    type: object
  UserObject:
    type: object
    properties:
      email:
        type: string
      id:
        type: number
      orgId:
        type: number
      firstName:
        type: string
      lastName:
        type: string

A: The problem was that I override security in my paths.  I need to remove the following:
security:
    - auth:
    - role_admin


text:
Q: Inhomogeneous wave equation with bounded term, solution becomes zero Let $u(x,y)$ be e a solution of the equation $$u_{tt}-u_{xx}=q(t,x)u$$ with initial conditions that are all zero. If $q$ is bounded, then $u\equiv 0$.
My attempt: the solution of the homogeneous is zero, so, using Duhamel, the solution is $$u(t,x)= \frac{1}{2}\int
 \int_{\Delta(t,x)} q(r,s)u(r,s)\text{d}r \text{d}s$$
where $\Delta(t,x)$ is the triangle limited by the characteristic lines containing the point $(t,x)$. If $M = \sup |q|$, then $$|u(t,x)|\leq \frac{M}{2}\int \int_{\Delta(t,x)} |u(r,s)|\text{d}r \text{d}s. $$ If $S(t,x) = \sup_{\Delta(t,x)}|u|$, then $$|u(t,x)|\leq  \frac{M \cdot S(t,x)}{2}\int \int_{\Delta(t,x)} \text{d}r \text{d}s =  \frac{M \cdot S(t,x) \cdot t^2}{2}.$$ Is it correct? If it is, how can I go from here?


text:
Q: delete part of string with different format I have 2 strings in 2 tables with the same text but with different formats. Moreover, in table 2 the data is concatenated as the user enters new info. Is there a way to delete from the concatenated text the data coming from table 1? So the delete is performed on table 2 based on info from table 1. I'm using SQL Server 2014.
Table 1
12/01 aaa
bbb
ccc

Table 2
10/01 Sfdfdg 12/01 aaa bbb ccc  14/02 sdgdfgfh


text:
Q: Java List of List of List, better solution? I created a class name objectA that has lets say 4 variable:
Date time; String text; int var1, int var2
I need to create a list of ObjectA(). And then group them first by Time, second by var1, and then by var2.
This is because i want to be able to compare lists that has different var2 but the same var1; or lists that has the same var2 but different var1.
I end up using "List< List< List< objectA>>>" which works fine i guess, but it doesnt looks great. And i dont think this is a good practice. Does anyone know any Datastructure or Tree or other ideas with which i could implement instead of List within List within List.

Almost similar question has actually been ask here:
List of Lists of Lists
.But the answer are just not what i was looking for. Please pardon me if this is still consider against the rule.

A: This is an example of a simple tree structure for your problem.
public class Tree {

private Node root;

public Tree(List<YourObject> rootData) {
    root = new Node();
    root.data = rootData;
    root.children = new ArrayList<Node>();
}

public static class Node {
    private List<YourObject> data;
    private Node parent;
    private List<Node> children;
}
}

Your can build a simple tree and run all tree and graph-algorithms on this simple structure.

A: The ideal structure to group objects by some attribute is a Map of Lists, where each key of the map corresponds to each different value of the attribute along the list of objects, and each value of the map is a sublist of all the objects whose attribute matches the key.
Let's start grouping by a single attribute. Using streams is quite easy to accomplish what you want:
Map<Date, List<ObjectA>> groupsByDate =
    yourList.stream()
        .collect(Collectors.groupingBy(ObjectA::getTime));

This assumes ObjectA has a getTime method.
Now, Collectors.groupingBy has an overloaded version that accepts what is called a downstream collector, meaning that you can collect the objects that match a value into another structure different than a List.
For example, you can collect to a second Map that groups objects by a second criteria, in your case this would be by var1:
Map<Date, Map<String, List<ObjectA>>> groupsByDateAndVar1 =
    yourList.stream()
        .collect(Collectors.groupingBy(
            ObjectA::getTime,
            Collectors.groupingBy(ObjectA::getVar1)));

This assumes ObjectA has also a getVar1 method.
Finally, if you need to group by a third nested criteria, you could do it in a similar way:
Map<Date, Map<String, Map<String, List<ObjectA>>>> groupsByDateAndVar1AndVar2 =
    yourList.stream()
        .collect(Collectors.groupingBy(
            ObjectA::getTime,
            Collectors.groupingBy(
                ObjectA::getVar1,
                Collectors.groupingBy(ObjectA::getVar2))));

This assumes ObjectA has also a getVar2 method.

A: a List<List<Object>> is probably what you want if you want to group by the first variable and then subgroup by the second
You could also do a Tree, up to you

A: If that's always the way you want to sort; by time, then val1, then val2, implement Comparable in your ObjectA class.  Something like
public int compareTo(Object that) {
    //check for null
    // check for instanceOf ObjectA
    // cast from Object to ObjectA
    int result = this.time.compareTo(that.time);
    if (result == 0) {
       // time comparison was the same
       result = this.var1.compareTo(that.var1);
       if (result == 0) {
           // time and var1 comparisons were the same
           result = this.var2.compareTo(that.var2)
       }
    }
    return result;
}

and then just sort() one list.


text:
Q: vim hit "enter" on a specific letter I want to hit enter on the arrow symbol in a file. Basically after hitting enter the arrow key collapses to show more text. I have so many such arrow keys.
▾ $wp_filter = (array [365])
  \
   ▸ $wp_filter['pre_term_name'] = (array [2])

After completely collapse
▾ $wp_filter = (array [365])
  \
   ▾ $wp_filter['pre_term_name'] = (array [2])
    \
     ▾ $wp_filter['pre_term_name'][10] = (array [2])
      \
       ▾ $wp_filter['pre_term_name'][10]['sanitize_text_field'] = (array [2])
        \
         ⬦ $wp_filter['pre_term_name'][10]['sanitize_text_field']['function'] = (string [19]) `sanitize_text_field`

I am trying
:%s/▸/\r/g

It does not collapse the text and the text after arrow breaks to next line.
▾ $wp_filter = (array [365])
  \

 $wp_filter['pre_term_name'] = (array [2])

I also tries
:%s/▸/▸\r/g

It breaks the line after the arrow mark.
▾ $wp_filter = (array [365])
  \
   ▸
 $wp_filter['pre_term_name'] = (array [2])

A: see http://vim.wikia.com/wiki/Folding or http://vimdoc.sourceforge.net/htmldoc/fold.html
particularly: za toggles one level of folding, zA toggles all levels. You need to be on the node for this to work.
To open all folds in the file: zR  (and zM will close all of them) (of course here, no need to be on a node, as it acts on all of them)


text:
Q: How to include GeoLite2 database in a java application I'm new in Java programming so don't hold it against me. I'm trying to include a Maxmind database in my application. I've been using a relative path when working on the project, similar to:
File dbfile = new File("C:\Development\Maxmind GeoIP2 DB\GeoLite2-Country.mmdb");
DatabaseReader dbReader = new DatabaseReader.Builder(dbfile).build();

That works well for local development, however I've been struggling to figure out how to add the database file when I compile the project.
Any ideas on how to do this?


text:
Q: How can I make the 'X' button in a modal popup window redirect to another site $(document).ready(function() {
    $("#dialog-message").css("display", "none");
    $("#uniqueCode").click(function() {
        $("#dialog-message").dialog({
            modal: true,
            width: 400,
            height: 250,
            position: {
                my: "center",
                at: "center",
                of: window
            },
            buttons: {
                Ok: {
                    text: "Ok",
                    id: "subBtn",
                    click: function() {
                        window.location.href = "google.com";
                        $(this).dialog("close");
                    }
                }
            }
        });
    });
});

The code above for the modal popup window shows a message to the user, and there's an Ok button at the bottom right hand corner of the popup window. There is also an 'X' button at the top right. When the user clicks the Ok button, they get redirected to another page. Everything works until I found an issue. The issue is when the user clicks the 'X' button on the top right, they don't get redirected. I have tried everything that I thought I could to make it work, but I am still stuck! How can I redirect the user to another site when they click either the 'X' button on the top right or the 'Ok' button on the bottom right? Can somebody help me?
EDIT:
<input type="submit" id="uniqueCode" name="submit" value="Submit" />

<div id="dialog-message" title="Reference Return Code">

The input button triggers the modal. And the div is for the window.

A: $('div#dialog-message').on('dialogclose', function(event) {
     window.location.href = "--your URL goes here--";
 }):

or
$("#dialog").dialog({
    autoOpen: false,
    resizable: false,
    width: 400,
    height: 140,
    modal: true,
    buttons: {
        "SUBMIT": function() {
        $("form").submit();
    },
    },
    close: function() {
      window.location.href = "--your URL goes here--";
    }
});

A: Keep that X button inside an anchor tag and give it a id or a class, Select that X anchor tag in DOM. Then you can add an event listener to that button.
Like:
Lets give your X button an Id of close,
Then,
var x = document.getElementById("close");

x.addEventListener('click', function() {
    var anch = document.getElementById("yourAchorTagId");
    anch.href = "yourDesiredUrl";
});

A: $('your close button id or class').click(function(){
  window.location.href = "google.com"
})

A: .ui-dialog-titlebar-close
{
    display: none !important;
}

Thanks for the help, guys. But I have solved the issue.
EDIT: I had to "inspect" the page and saw the class id for the button. It's from the framework that I am using and I forgot to check it earlier


text:
Q: CUSTOMER and purchased CATEGORY count details in Oracle SQL I am having the below require. if anyone provide the solution it would be thankful
Requirements:-
Transaction of the customer who purchased in the below category
Customers and purchased Category
Total Number of customer from category level
category and customer count
I want to display the output life below
output
Thanks
R Sanjay

A: You can use cte, self join it and join it again with your table as following:
With cte as
(Select category, count(1) as cnt
From your_table
Group by category)
Select t1.category,
T1.cnt,
T2.category,
T2.cnt,
Count(distinct t.customer) as both_cat
From cte t1
Join cte t2
On (t1.category <> t2.category)
Join your_table t
On (t.category in (t1.category, t2.category)
Group by t1.category, t2.category,
         T1.cnt, t2.cnt
Order by t1.category, t2.category

Cheers!!


text:
Q: What is the point of the Remember Me option on website logins? What is stopping developers from ALWAYS remembering the user? Is it simply an artifact of the old fear (still around in some places) of cookies?
I also would like to know if it is bad practice to simply pass in user names from an outbound email.

A: Nothing is stopping the web app from always remembering the user for as long as they want on particular computer without asking explicit permission from the user. However, doing so has security and privacy implications on shared computers.
Imagine you go to a cyber-cafe or a library, sit on a shared computer and login to your bank website (which you shouldn't do from such places anyway :-)). The bank website tries to be "smart" and persists a cookie with a ticket based on your credentials. When you're done, you close the browser without logging off. Next person sits down, opens the browser, looks at the history and goes to the bank site. And now they have magically access to all your money.
That would probably be the last time you use that bank for anything.
Update: To answer the second part of the question (and the comment below)
If you are afraid of URL injection, you should probably not specify the username in the email URL itself. Instead, generate a one-time token (you could use a one-way hash of the user name and a website secret for example), which wouldn't mean anything to an external site, but would allow you to extract the user identity and prepopulate the field on the page.
Keep in mind that you should not include in the URL in the email enough information, so that clicking on that link would authenticate the user to your site. You still want the user to prove their identity.


text:
Q: How do I export an HTML table to excel I am trying to export an HTML table into an excel file.
Because I am already using sheetjs for importing excel files, I have been trying to use it as well for exporting.
Searching the internet, it seems to be only possible together with filesaver.js.
Below is what I have been trying but without success.

var tbl = document.getElementById('tbl');
var wb = XLSX.utils.table_to_book(tbl);
console.log(wb)

var blob = new Blob([tbl], {
    type: "application/vnd.ms-excel;charset=charset=utf-8"
});
saveAs(blob, "Report.xls");
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 500px;
    margin: 50px 0 0 50px;
}

td,
th {
    border: 1px solid #cacaca;
    text-align: left;
    padding: 8px;
    background-color: #f5f5f5;
}

th {
    background-color: #dce0e3;
}

        Company
        Contact
        Country

            Alfreds Futterkiste
            Maria Anders
            Germany

            Centro comercial
            Francisco Chang
            Mexico

            Ernst Handel
            Roland Mendel
            Austria

            Island Trading
            Helen Bennett
            UK

            Laughing Bacchus
            Yoshi Tannamuri
            Canada

            Magazzini Alimentari
            Giovanni Rovelli
            Italy

A: It sounds like you might be after a scraper, there's one I found here, which might start you in the right direction:
http://analystcave.com/excel-scraping-html-regular-expression-continued/


text:
Q: Why won't my diff.exe run from cmd line? I've got a number of utilities installed in C:\program files (x86)\git\bin, many of which shadow built-in command line functions. So as not to run afoul of that, I would rather NOT add that folder to the PATH, however I do want to be able to type diff a.txt b.txt anywhere and run diff on the two.
Things I have tried:

*

*Added a diff.exe subkey to [HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths]

*Created a diff.lnk in C:\dev (which is on my PATH) and added .LNK to my PATHEXT

*Created a diff.bat with the following code:
@"C:\Program Files (x86)\git\bin\diff.exe" *$
The only method that worked was the last one, which (although it runs diff) fails to find any files I specify through the command line.
Similarly, the second method allowed diff to run if I was currently in C:\dev but not elsewhere.
I have a doskey script that works as an alias machine (notably: npp=notepad++ on cmd start) but I would rather not resort to that for this. I will if I have to.
Any suggestions? Any idea why the above didn't work?

A:
Any idea why the above didn't work?

A few.

*

*HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths has no effect on cmd, because cmd doesn't use ShellExecuteEx to run programs.

*Creating a .lnk file should have worked.  From your description, it seems the most probable that the statement C:\dev is on my PATH. is not in fact true.

*diff.bat didn't work as you wanted because the syntax that you were using for substituting all positional parameters was gibberish.  *$ isn't even an accidental bashism.  As noted, %* is the correct syntax for doing that in scripts interpreted by cmd.  (It is also the correct syntax for Take Command, which supports %# as a bonus.)


text:
Q: Saving multiple scores in seperate executions score=(uName, '=', uCoins)
try:
    with open('saveScore.txt', 'rb') as file:
        score=pickle.load(file)
except:
    score==0
with open('saveScore.txt', 'wb') as file:
    pickle.dump(score, file)

This is my code, I need help saving the score for each particular execution of the program without overwitting any previous saved scores. I cannot seem to get it to work.

A: To write to a file without overwriting it, you open the file in 'append' mode with the 'a' flag to open. In the below code snippet, I'm using random simply for example purposes:
#!/usr/bin/python

import random

score = random.randint(1, 500)

wfh = open('score.txt', 'a')

print(str(score))

wfh.write("{}\n".format(score))

wfh.close

Here I run it multiple times, then after that I print out the contents of the file which have retained all my 'scores':
$ ./score.py
159
$ ./score.py
156
$ ./score.py
224
$ ./score.py
235

$ cat score.txt
159
156
224
235


text:
Q: Docker - port forwarding I'm need help, can not connect to the container all day. I used this address: 127.0.0.1:80 and see: http://joxi.ru/Vm6oegWtxoQVK2. When enter this command 'docker ps' I see it:
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
42941a9e0dda        docker_web          "python manage.py ru…"   45 seconds ago      Up 4 seconds        127.0.0.1:8000->80/tcp   docker_web_1

Docker-compose:
version: '3'

services:
  web:
    build:
    context: .
    dockerfile: /django.testsite/Dockerfile
  ports:
    - "127.0.0.1:8000:80"

Docerfile
FROM python:3

RUN easy_install pip
RUN pip install django==1.9.12
RUN pip install requests

ADD . /.
WORKDIR /django.testsite

CMD ["python", "manage.py", "runserver", "127.0.0.1:80"]

How solve?

A: In your docker-compose.yml file, you specify "127.0.0.1:8000:80" as the port mapping. This means that you are mapping port 8000 on your local ip, 127.0.0.1, to port 80 on the internal container.
Docker also reinforces this in the docker ps call, where it tells you that the container has a port mapping with 127.0.0.1:8000->80/tcp.
If you visit 127.0.0.1:80, there is nothing hosted on that port. You need to visit 127.0.0.1:8000 instead.


text:
Q: Use of "to be having" I am confused with the usage of "to be having".
He is assumed to be having the diamonds.
or
He is assumed to have the diamonds.
Which one is correct?

A: Both can be correct: they mean different things.

He is assumed to be having the diamonds.

Although the sentence could be re-phrased slightly, in essence, this means that it is assumed he will be receiving the diamonds; that they should be being sent to him; that they are meant to be given to him; etc..
In other words, this implies an assumption that something will be - or is meant to be - happening, probably in the near future.

He is assumed to have the diamonds.

This means that it is assumed that they are already in his possession - now; present tense.


text:
Q: Android Webview keeps Executing JavaScript even after app closes I have a JS script running on loop in a webview and that loops should ideally die when the webview is out of focus or the parent application is closed.
Is there anyway to do this. So far the desired result works on my Google Nexus 7 (4.0) but not on my Kindle (2.2.3)


text:
Q: Backbone.js unable to access the router functions? I have a simple implementation of Backbone.js which goes like this -
$(document).ready(function(){
    Workspace = Backbone.Router.extend({
    routes: {
    "/getAcademics": "academics"
        },

    academics: function(){
            alert("ok");
    $("#content").append("
Academics
");
    }
    });
var myWorkspace = new Workspace;
});

The link in the body is given as -
     Academics

Though the router routes to the link #/getAcademics but it does not execute the function academics. Any clues as how to rectify this. Am I missing something else.
Thanks

A: After you instantiate your router, and before you attempt to use any of its routes, you need to call Backbone.history.start(). This will setup a listener for hash changes and call the correct route functions when needed.
You can find more information here: http://documentcloud.github.com/backbone/#History


text:
Q: Is there any tool to measure speed of laptop and test laptop hanging before and after adding 8GB RAM? My hp laptop having core i3 plus 4GB of RAM hangs on running one chrome browser with some tabs plus visual studio 2015. I just upgrade my laptop from 4GB of RAM to 4+8 GB of RAM. Now I want to measure/judge how much difference in processing speed and how many heavy applications I can run in parallel. Can anyone please tell me a way to measure how much efficiency I have gotten in terms of speed and capacity of parallel processing? Is there tool for laptop hang testing?

A: AIDA64 has a memory stress test, but since I don't think you've changes the RAM clock speed, the change you'll see will probably be linear with the size increase.

A: I use Hiren Tools, they have a collection of a lot of very useful tools.  You can get GoldMemory 5.07, Memtest86+ 4.20, MemTest 1.0 and S&M Stress Test 1.9.1 (just to name a few) from their website, to do testing.  Hope this helps!


text:
Q: Ajax MySQL POST responses with Object without data I am using that code to send a POST request to add data to a mysql table.
var todoItem = $(this).serialize();

  $.ajax({
    type: "POST",
    url: "/test",
    data: todoItem,
    dataType: "json",
    success: function(data, textStatus, jqXHR) {
      console.log(data);
      if(data.success){
        $('#todo-list').append(
          '
' +
            '' +
              data.todo +
            '' +
            '
' +
              'Edit' +
              '<form style="display: inline" method="POST" action="/test/${data.id}">' +
                '<button type="submit" class="btn btn-sm btn-danger">Delete</button>' +
              '</form>' +
            '
' +
            '

' +
          '
'
        );
      } else {
        $("#todo-list").append(
          '
' +
            '' +
              'Fail' +
            '' +
            '

' +
          '
'
        );
      }
    }

Then i want to use data from the response to append to my list.
But if(data.success) isnt passing. why is that?
Also my data in console.log looks like object Object and doesnt contain the inserted row data.
Do i need to send a get request now to retrieve the last data row?


text:
Q: How to implement Factory Pattern for components in a React App? Im currently using React in my company for building our main Software product... The development of the app was started a year ago, and we don't expected that our app growed so much like it does. Now we are dealing with some kind of problems that could have been avoided if we had done a good architecture design from the beginning .
For summarize, one of the most central problems that we have is the code duplication... and the large amount of "import" statements with relative routes in the top of each new component that we make...
I would like to know if is recommended for solve this kind of problems use the Factory Pattern for reusing the React components and how to successfuly implement it?
Thanks in advance

A: You could implement a factory pattern in this way,
function ReactComponentFactory(contentsJSX){
  // do factory stuff here...
  return <div>{contentsJSX}</div>
}

But in my opinion this makes the code harder to grok so I'd avoid using a factory for react components.


text:
Q: How to insert an array into a SQLite database? I'm trying to insert an array into a SQLite database and I'm having difficulties getting the array variables to insert.
How can I get variables from the array (username & fullName) to insert in the db?
Here are the error messages:
Property 'username' not found on object of type 'NSString *'
Property 'fullName' not found on object of type 'NSString *'

Here's my code...
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

    NSMutableArray *items = result;

    sqlite3_stmt *insert_statement;

    // prepare the insert statement
    const char*sql = "INSERT INTO people (username, fullName) VALUES(?,?)";
    sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL);

    // iterate over an array of dictionaries
    for (NSString *str in items) {

        // NSLog(@"%@",str);

        // bind variables
        sqlite3_bind_text(insert_statement, 1, [str.username UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(insert_statement, 2, [str.fullName UTF8String], -1, SQLITE_TRANSIENT);

        // insert fails
        if (sqlite3_step(insert_statement) != SQLITE_DONE) {
            NSLog(@"Insert failed: %s", sqlite3_errmsg(database));
        }

        // reset the statement
        sqlite3_reset(insert_statement);
    }

    // release the statement
    sqlite3_finalize(insert_statement);
}`

A: This code works well ok combined with starting a transaction and committing it:
// start transaction
sqlite3_stmt *begin_transaction_stmt;
const char *beginTrans = "BEGIN EXCLUSIVE TRANSACTION";

if (sqlite3_prepare_v2(database, beginTrans, -1, &begin_transaction_stmt, NULL) != SQLITE_OK) {
    sqlite3_close(database);
    return NO;
}

sqlite3_step(begin_transaction_stmt);
sqlite3_finalize(begin_transaction_stmt);

========== [your code from the post above comes here] =============
// commit transaction
sqlite3_stmt *end_transaction_stmt;
const char *endTrans = "COMMIT";
if (sqlite3_prepare_v2(database, endTrans, -1, &end_transaction_stmt, NULL) != SQLITE_OK) {
    sqlite3_close(database);
    return NO;
}

sqlite3_step(end_transaction_stmt);
sqlite3_finalize(end_transaction_stmt);


text:
Q: Specifying a minimum cluster size with Open Layers Clustering With OpenLayers 3, how can I specify a minimum cluster size so that clusters with 5 map markers or less will not get clustered, but will instead display the individual map markers? Is there a way to do this within the cluster layer's ol.layer.Vector object?
let clusterSource = new ol.source.Cluster({
   distance: CLUSTER_DISTANCE,
   source: features
});
let clusterLayer = new ol.layer.Vector({
   source: source,
   style: function(feature, resolution) { }
});

A: You can check in the code how many features are there. If you have too many, you can create a cluster source based on the vector source you already have to add it a to a new vector layer. If not, a vector layer can be created with your existing vector source.
Since there is no method to set the source dynamically to a layer, your vector layer should be created with the desired source. If you want to see how it works with more than 5 features, just uncomment the commented lines.

var features = [
    new ol.Feature({
     geometry: new ol.geom.Point([0,0])
    }),
    new ol.Feature({
     geometry: new ol.geom.Point([100000,500000])
    }),
    new ol.Feature({
     geometry: new ol.geom.Point([500000,100000])
    }),
    new ol.Feature({
     geometry: new ol.geom.Point([5000000,1000000])
    }),
    new ol.Feature({
     geometry: new ol.geom.Point([1000000,500000])
    })
    /*,new ol.Feature({
     geometry: new ol.geom.Point([1800000,800000])
    })*/
 ],
  source = new ol.source.Vector({
   features: features
  });

var layer;
if (features.length > 5) {
  var clusterSource = new ol.source.Cluster({
    distance: parseInt(40, 10),
    source: source
  });

  var styleCache = {};
  layer = new ol.layer.Vector({
    source: clusterSource,
    style: function(feature) {
      var size = feature.get('features').length;
      var style = styleCache[size];
      if (!style) {
        style = new ol.style.Style({
          image: new ol.style.Circle({
            radius: 10,
            stroke: new ol.style.Stroke({
              color: '#AAA'
            }),
            fill: new ol.style.Fill({
              color: '#DDD'
            })
          }),
          text: new ol.style.Text({
            text: size.toString(),
            fill: new ol.style.Fill({
              color: '#B144FF'
            })
          })
        });
        styleCache[size] = style;
      }
      return style;
    }
  });
} else {
  layer = new ol.layer.Vector({
    source: source
  });
}

var map = new ol.Map({
  layers: [
   new ol.layer.Tile({
    source: new ol.source.OSM()
  }),
    layer
  ],
  target: 'clusterMap',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});
<link href="https://openlayers.org/en/v3.20.1/css/ol.css" rel="stylesheet"/>


text:
Q: How to add a triangle symbol on the top of the vertical line in Matplotlib How can I add a triangle symbol on top of the red line axvline?
input
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00',
                    1: '2020-01-01 18:00:00',
                    2: '2020-01-02 06:00:00',
                    3: '2020-01-02 18:00:00',
                    4: '2020-01-03 06:00:00',
                    5: '2020-01-03 18:00:00',
                    6: '2020-01-04 06:00:00',
                    7: '2020-01-04 18:00:00'},
              'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1}})

Code
fig, ax = plt.subplots(1)
ax.bar(df['A'], df['B'], linestyle='-',color='midnightblue' ,lw=6, width=0.01)
plt.xticks(rotation=90)
ax.axvline('2020-01-02 18:00:00', color='red', zorder=1, linestyle='--')

A: How about using a dedicated arrow function? ax.arrow()
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)
ax.bar(df['A'], df['B'], linestyle='-',color='midnightblue' ,lw=6, width=0.01)
plt.xticks(rotation=90)

# ax.axvline('2020-01-02 18:00:00', color='red', zorder=1, linestyle='--')
ax.arrow(3,0,0,df['B'].max(), head_width=0.1, head_length=0.3, fc='r', ec='r', linestyle=':')
ax.set_ylim(0,df['B'].max()+0.2)


text:
Q: Errors when compiling with GLUT program It is impossible to compile an error.
Please help, who faced a similar problem?
OS: Ubuntu
IDE: Clion
CMakeFiles/a4_waves_OpenGL.dir/main.cpp.o: In function display()':
/home/alex/ClionProjects/test/a4-waves_OpenGL/main.cpp:7: undefined reference toglClear'
..............................
/home/alex/ClionProjects/test/a4-waves_OpenGL/main.cpp:9: undefined reference to glColor3f'
/home/alex/ClionProjects/test/a4-waves_OpenGL/main.cpp:42: undefined reference toglutMainLoop'
collect2: error: ld returned 1 exit status
make[3]: *** [a4_waves_OpenGL] Error 1
code
#include <iostream>
#include <math.h>
#include <GL/freeglut.h>
using namespace std;

void display() {
    glClear(GL_COLOR_BUFFER_BIT);   ///очистим буфер

    glColor3f(0.0,1.0,0.0); ///зададим цвет которым будем "рисовать". Я выбрал зелёный.
    glBegin(GL_LINES);   ///начнём рисовать первую координатную ось - OX. Будем это делать при помощи линий
    glVertex2f(-550,0);   ///первая точка оси
    glVertex2f(550,0);   ///вторая точка оси
    glEnd();

    glBegin(GL_LINES);  ////теперь проделаем тоже для оси OY
    glVertex2f(0,150);
    glVertex2f(0,-150);
    glEnd();

    glBegin(GL_LINE_STRIP);   ///начнём рисовать синусоиду при помощи ломаной линии
    glColor3f(1.0,0.0,0.0); ///выберем для неё красный цвет

    for (int i = -500; i <= 500; i++) {
        float y = 100 * sin(i*M_PI/180);    ///вычислим текущую координату Y. Функция Sin() принимает значение в радианах, поэтому i следует умножить на число Пи и разделить на 180. Весь результат умножим на 100, указав тем самым максимальную высоту нашей синусоиды.
        glVertex2d(i,y);
    }
    glEnd();
    glFlush();
}

int main(int argc, char **argv) {
    glutInit(&argc,argv); ///инициализируем glut
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); ///использовать 1 буфер, и цвет типа RGB (3 составляющие)
    glutInitWindowSize(240,240); ///зададим размер окна 240x240
    glutInitWindowPosition(0,0);  ///позиция открытия окна
    glutCreateWindow("Sin"); ///создать окно с именем "Sin"
    glClearColor(1.0 , 1.0 , 1.0 , 1.0); ///цвет фона окна
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-600.0,600.0,-200.0,200.0,-1.0,1.0); ///зададим размеры координатной сетки
    glutDisplayFunc(display); ///зададим функцию отображающую необходимые объекты
    glutMainLoop();  ///передает управление в glut
    return 0;
}

A: An undefined reference means, that the linker cannot find one or more of the function definitions (details here).
In your case, you are most probably not linking agains opengl32 (-lGL). If you haven't done this yet, you will also need to link agains glut (-lglut). Have a look at this answer to see how this has to be done.


text:
Q: Expandable listview childset not fully visible I have multilevel expandable listview.But the grand childs are not fully visible in my case.Also I know this happens in the case of listview.But in the expandable listview I don't know what its.Please help me to show the full grandchild.
my main activity
public class MainActivity extends Activity
{
    ExpandableListView explvlist;
    TextView ui_hot = null;
    int hot_number = 0;
   // private ExpandListAdapter ExpAdapter;
    private ArrayList<Group> ExpListItems;
    private ExpandableListView ExpandList;
   // private SliderLayout mDemoSlider;
    Intent intent = null;
    RequestQueue requestQueue1, requestQueue2;
    int[] firstcatid = null,secondcatid = null;
    String firsttitle[] = null,secondtitle[] = null;
    int j = 0;
    ArrayList<Group> list,list2,list3;
    CustExpListview SecondLevelexplv;
    ExpandableListView elv;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestQueue1 = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://www.ezyret.com/cntrldata/ezproductfristcategory.php",
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            list = new ArrayList<Group>();
                            JSONArray ja = response.getJSONArray("hi");
                            JSONArray ja2 = response.getJSONArray("hi2");
                            JSONArray ja3 = response.getJSONArray("hi3");
                            firsttitle = new String[ja.length()];
                            firstcatid = new int[ja.length()];
                            JSONObject jsonObject2=null,jsonObject3=null,jsonObject;
                            for (int i = 0; i < ja.length(); i++) {

                                jsonObject = ja.getJSONObject(i);

                                // Log.e("hie",jsonObject2.getInt("second_category_id")+"");
                                //jsonObject3 = ja3.getJSONObject(i);
                                firstcatid[i] = jsonObject.getInt("first_category_id");
                                firsttitle[i] = jsonObject.getString("first_category_name");
                            }
                            secondcatid=new int[ja2.length()];
                            for(int i =0;i<ja2.length();i++){
                                jsonObject2 = ja2.getJSONObject(i);
                                secondcatid[i]=jsonObject2.getInt("second_category_id");
                            }
                            for(int i = 0;i<ja.length();i++){
                                Group gru = new Group();
                                gru.setName(firsttitle[i]);
                                list2 = new ArrayList<Group>();
                                for(int j=0;j<ja2.length();j++){
                                    Group gru2 = new Group();
                                    jsonObject2 = ja2.getJSONObject(j);

                                    //Toast.makeText(getApplicationContext(),jsonObject2.getInt("second_category_id"),Toast.LENGTH_SHORT).show();
                                    if(firstcatid[i]==jsonObject2.getInt("first_category_id")){
                                        gru2.setName(jsonObject2.getString("second_category_name"));
                                        list3= new ArrayList<Group>();
                                        for(int k=0;k<ja3.length();k++){
                                            Group gru3= new Group();
                                            jsonObject3 = ja3.getJSONObject(k);
                                            if(secondcatid[j]==jsonObject3.getInt("second_category_id")){
                                                Log.e("hie", jsonObject2.getInt("second_category_id") + "");
                                                gru3.setName(jsonObject3.getString("third_category_name"));
                                                list3.add(gru3);
                                            }
                                            gru2.setItems(list3);

                                        }

                                        list2.add(gru2);
                                    }

                                }
                                gru.setItems(list2);
                                list.add(gru);
                            }

                            // Toast.makeText(getApplicationContext(),url[2],Toast.LENGTH_SHORT).show();
                            //output.setText(data);
                            ExpListItems =  list;
                            explvlist = (ExpandableListView)findViewById(R.id.ParentLevel);
                            explvlist.setAdapter(new ParentLevel(getApplicationContext(),ExpListItems,ExpListItems,list3));
                            //ExpAdapter = new ExpandListAdapter(getApplicationContext(), ExpListItems);
                           // ExpandList.setAdapter(ExpAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", error.toString());

                    }
                }
        );
        requestQueue1.add(jsonObjectRequest);

    }

    public class ParentLevel extends BaseExpandableListAdapter {
        private Context context;
        private ArrayList<Group> groups,childgroup,childgroup2,a1;

        @Override
        public ArrayList<Group> getChild(int groupPosition, int childPosition) {
            ArrayList<Group> chList = groups.get(groupPosition).getItemz();
            return chList;
        }

        public ParentLevel(Context context, ArrayList<Group> groups,ArrayList<Group> groups2,ArrayList<Group> groups3) {
            this.context = context;
            this.groups = groups;
            this.childgroup=groups2;
            this.childgroup2=groups3;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
         //Group child = (Group) getChild(groupPosition, childPosition);
           ArrayList<Group> ch=(ArrayList<Group>)getChild(groupPosition, childPosition);
            SecondLevelexplv = (CustExpListview)convertView;
            if (convertView == null) {
               SecondLevelexplv=new CustExpListview(MainActivity.this);
            }
            //child.setItems(childgroup);
            //requestQueue1 = Volley.newRequestQueue(getApplicationContext());

            SecondLevelAdapter adapter=new SecondLevelAdapter(context, ch);

            SecondLevelexplv.setAdapter(adapter);
            SecondLevelexplv.setGroupIndicator(null);
            return SecondLevelexplv;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            ArrayList<Group> chList = groups.get(groupPosition).getItemz();
            if(!(chList==null))
                return 1;
            else return 0;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groups.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return groups.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent){

        Group group = (Group) getGroup(groupPosition);
        if(convertView==null)

        {
            LayoutInflater inf = (LayoutInflater) context
                    .getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = inf.inflate(R.layout.group_item, null);
        }

        TextView tv = (TextView) convertView.findViewById(R.id.group_name);
        tv.setPadding(10, 7, 7, 7);

            tv.setText(group.getName());
        ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
        if(!(group.getItems()==null))

        {
            if (!group.getItems().isEmpty()) {
                if (isExpanded) {
                    tv.setTypeface(null, Typeface.BOLD);
                    imageView.setBackgroundResource(R.drawable.ic_action_minus);
                } else {
                    imageView.setBackgroundResource(R.drawable.ic_action_add);
                    tv.setTypeface(null, Typeface.NORMAL);
                }
            } else imageView.setVisibility(View.INVISIBLE);
        }

        return convertView;

    }

        @Override
        public boolean hasStableIds()
        {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition)
        {
            return true;
        }
    }

    public class CustExpListview extends ExpandableListView
    {

        int intGroupPosition, intChildPosition, intGroupid;

        public CustExpListview(Context context)
        {
            super(context);
        }

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public class SecondLevelAdapter extends BaseExpandableListAdapter {
        int i = 0;
        private Context context;
        private ArrayList<Group> groups;
        private int gr;

        public SecondLevelAdapter(Context context, ArrayList<Group> groups) {
            this.context = context;
            this.groups = groups;

        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            ArrayList<Group> chList = groups.get(groupPosition).getItems();
            return chList.get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            Group child = (Group) getChild(groupPosition, childPosition);

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) context
                        .getSystemService(context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.group_item, null);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.group_name);

            tv.setText(child.getName().toString());

            //Toast.makeText(context,child.getName().toString()+"hi",Toast.LENGTH_SHORT).show();
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            ArrayList<Group> chList = groups.get(groupPosition).getItems();
            if (!(chList == null))
                return chList.size();
            else return 0;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groups.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return groups.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            Group group = (Group) getGroup(groupPosition);
            if (convertView == null) {
                LayoutInflater inf = (LayoutInflater) context
                        .getSystemService(context.LAYOUT_INFLATER_SERVICE);
                convertView = inf.inflate(R.layout.group_item, null);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.group_name);

            tv.setText(group.getName());
            ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
            if (!(group.getItems() == null)) {
                if (!group.getItems().isEmpty()) {
                    if (isExpanded) {
                        tv.setTypeface(null, Typeface.BOLD);
                        imageView.setBackgroundResource(R.drawable.ic_action_minus);
                    } else {
                        imageView.setBackgroundResource(R.drawable.ic_action_add);
                        tv.setTypeface(null, Typeface.NORMAL);
                    }
                } else imageView.setVisibility(View.INVISIBLE);
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

MY activity xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ExpandableListView
        android:layout_width="fill_parent"
        android:id="@+id/ParentLevel"
        android:groupIndicator="@null"
        android:layout_height="fill_parent">

    </ExpandableListView>

</LinearLayout>

my group item xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    android:weightSum="1">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_gravity="right"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/group_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:textColor="#010101"
        android:text="e" />

</RelativeLayout>

the pic

A: Better You can use ScrollView-->LinearLayout--> ExpandableListView

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_expandable_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent">

                  <ExpandableListView android:layout_width="fill_parent"
                                      android:id="@+id/ParentLevel"
                                      android:groupIndicator="@null"
                                      android:layout_height="fill_parent">
                   </ExpandableListView>
    </LinearLayout>
</ScrollView>


text:
Q: DIV's vs. Tables or CSS vs. Being Stupid I know that tables are for tabular data, but it's so tempting to use them for layout. I can handle DIV's to get a three column layout, but when you got 4 nested DIV's, it get tricky.
Is there a tutorial/reference out there to persuade me to use DIV's for layout?
I want to use DIV's, but I refuse to spend an hour to position my DIV/SPAN where I want it.
@GaryF: Blueprint CSS has to be the CSS's best kept secret.
Great tool - Blueprint Grid CSS Generator.

A: Why tables for layout is stupid: problems defined, solutions offered.

A: In my opinion, the bias should be in favour of CSS over IE6 - i.e. unless there's an insanely good reason (e.g. your site is only targetted at people using IE6, which would be weird), it's better to 'alienate' people using IE6 rather than people with poor vision and/or automated user agents. Usage of IE6 is decreasing; the latter group is increasing in number. Even if your site doesn't look perfect in IE6, it will probably be easy for those users to read it than a table-based layout will for those who can't see it.
This is a very general question, so it's difficult to answer with specifics. The two books that are excellent resources are:

*

*Bulletproof Web Design, Dan Cederholm

*CSS Mastery, Andy Budd

If you only have to spend an hour designing your overall site layout, that's not bad going.

A: CSS may not be a religion, but it is how browsers interpret HTML for layout. Like it or not, all modern browsers use (some version) of the W3C box model. To continue to rely on tables is continue to rely on a methodology that is just plain wrong in the eyes of the people who design web rendering technology.
I know CSS can seem awfully complicated at times, but I believe it is a necessity in this day and age (trust me, your clients are going to want it).
If you don't feel comfortable taking the time really learn CSS (so it takes you seconds or minutes to position elements...not an hour), then you need to pass the layout work on to someone who knows really knows the front-end.
Yes, there are a lot of problems with the current browser implementations of CSS, but nothing so drastic that you should ever feel the need to return to table based layout. Just sit down and take the time to learn it, like you would any other language or framework.
The best online reference resource I've found is this one:
http://reference.sitepoint.com/css
But it might not hurt to look at a book like Designing With Web Standards which goes a long way in helping you to understand why this stuff is important.

A: I was also thinking Blueprint was great until I saw YAML (Yet Another Multicolumn Layout). There is an online builder tool which is fantastic. I can get a cool looking multicolumn layout within 5 mins.

A: There's the Yahoo Grid CSS which can do all sorts of things.
But remember: CSS IS NOT A RELIGION. If you save hours by using tables instead of css, do so.
One of the corner cases I could never make my mind up about is forms. I'd love to do it in css, but it's just so much more complicated than tables.
You could even argue that forms are tables, in that they have headers (labels) and data (input fields).

A: After a while you don't even think about it. Using divs with CSS seems like the easier option imo. Plus, you have more freedom when using frameworks such as jQuery. I couldn't imagine doing some of the cool jQuery stuff without using css or divs. If you use tables for style and layout I feel like you miss out on a lot of new technologies and stay stuck in the 90's.

A: In the UK and in US there is a legal requirement for favouring CSS layouts over Tables.  Both Section 508 (US) and the Disability Discrimination Act (UK) cover accessibility standards for users with limited vision.
In the UK the legislation extends so far as to actually make it illegal to commercially produce a site that impedes the ability of a partially sighted user in the same way that it is now illegal to have a shop with a step to enter it and no way for a wheelchair user to get in - admittedly there have been no prosecutions over website accessibility yet.  However I would always go with CSS as it means that your site design is so much easier to maintain in the longer term.
Investing time in learning CSS (I used W3C schools and .Net Magazine http://www.netmag.co.uk) will pay off.

A: This may be unhelpful but I somehow don't understand all these problems related to CSS. If a newspaper designer would try to embed a movie in the ad page, everybody would agree that he's a bit crazy. But still those same people pine after three-column layouts in HTML. HTML is just not apt to handle this kind of layout well at the moment. Furthermore, multi-column layouts are generally not really well-suited for reading on computer monitors. Aren't there enough viable alternatives?
And by the way, even tables don't offer a good way of implementing a fluent column layout so this is no reason at all to resort to such hacks. Assuming a halfway modern browser (i.e. > MSIE 6), tables don't offer any advantages over clean HTML + CSS that I know of.

A: I would just use the table.
In my experience, using a table for layout will work the same in all browsers and the CSS will not (especially if you're trying to support IE6).  It's just not worth the hours and hours of coding to get a layout to work in CSS when it can be done in 10 minutes using a table.
The other advantage to using tables is that your layout can very easily dynamically size itself to content.  Trying to get that done with CSS is a huge nightmare.

A: I find there are lots of limitations to CSS that just seem to hint the specification designers don't make websites for a living.
Use HTML tables if you can't do it easy in CSS.
Having said that, some of the frameworks do help and it always nicer to do in CSS if you can manage it.

A: You might be able to find some inspiration here: http://blog.html.it/layoutgala/

A: A List Apart is a great reference for using semantic HTML, the Holy Grail article is probably one of the best examples.  Also, check out CSS Zen Garden for some inspiration on the topic or read Dave Shea's excellent book "The Zen of CSS Design."

A: You use CSS for layout because not only is it semantically correct but because tables have multiple drawbacks.
Tables are horrible for accessibility because they break almost all screen readers, which in turn gives the visually impaired worthless information because of the way the tables are read.
They also render much slower than their CSS counterparts.  Tables have to be drawn twice, once for the layout, and again for the content.  This can mean that if you have a remote image or two on a server with a slow connection that your ENTIRE LAYOUT will not render.
Would you use an array to store a dictionary when you have a hashmap?  No.  And you shouldn't use a table when there's something out there which works better.


text:
Q: proto3 can't support isStringEmpty() This is my .proto file
syntax = "proto3";

package testing;

option java_multiple_files = true;
option java_package = "com.api.commons.proto";
option java_outer_classname = "SampleProto";

message Person {
  string name = 1;
  int32 id = 2;
  string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    string number = 1;
    PhoneType type = 2;
  }

  repeated PhoneNumber phones = 4;
  map<string, string> map = 5;
}

When I try to compile the proto file, the proto related java files create successfully. but open that file I see the error method. I am given below to attach that error case.
Now I am changing all fields to optional this error case not reproduced... My doubt is in proto3 all fields by default optional then why this issue fixed, when I change all fields to optional. Thanks


text:
Q: Excel - basic copy-paste between sheets macro I need to do a basic merge of data from 2 sheets where the first part (username) changes, but the second part is say, a preset list of 120 items.  ie, combine:
sheet1:USERLIST
albert
benny
cedric
dorothy
....

with
sheet2:ITEMLIST
item1
item2
item3
....
item120

so the final output on another sheet (in separate cells) is
sheet3
albert item1
albert item2
....
albert item120
benny item1
benny item2
....
benny item120
cedric item1
cedric item2
....
cedric item120

and so on.  I know this is a pretty basic question but I havent found the answer thus far.  thanks!

A: This can be simply done in a two level For...Next.
Suppose you have:

*

*[Sheet1]:

    USER_LIST
    A
    B
    C

*

*[Sheet2]:

    ITEM_LIST
    1
    2
    3
    4
    5

*

*[Sheet3]:

    RESULT_LIST

With this sub:
Private Sub Whatever_name_you_like()
    Dim i As Integer
    Dim j As Integer
    For i = 2 To Worksheets(1).Range("A65535").End(xlUp).Row
        For j = 2 To Worksheets(2).Range("A65535").End(xlUp).Row
            Worksheets(3).Cells(Range("A65535").End(xlUp).Row + 1, 1).Value = Worksheets(1).Cells(i, 1).Value & Worksheets(2).Cells(j, 1).Value
        Next
    Next
End Sub

When run, [Sheet3] will results in:
RESULT_LIST
A1
A2
A3
A4
A5
B1
B2
B3
B4
B5
C1
C2
C3
C4
C5

A: can you not just do this with a formula in the target range:
=Sheet1!A:A&Sheet2!A:A

just copy that formula in all your target cells.
This avoids using VBA and a loop, and takes advantage of Excels built-in functionality so no need to kick off VBA code


text:
Q: Sending a request to microservice I am taking out a part of a service from a monolith application and creating a microservice. So I have a monolith application and a microservice(MS).
Problem Statement-
I need to communicate with microservice via REST APIs. So my monolith will divert some specific API calls to microservice.
Now while communication, do I need to map the params of microservice in my monolith?
Creating a jar seems to be a bad idea as it violates the fundamental principles of microservice being independently deployable.
Suppose a create user API is sent to MS, with
- name and
- address
as params
Now in MS side the param names are
- nm
- prms
Ques1. Do I need to map MS params in monolith?
Ques2. or should I create a new service in between which will take care of this
Ques3. or should I send the params without mapped and let MS parse and filter out params from the request

A: Lets discuss each approach
Ques1. Do I need to map MS params in monolith?
When you break your monolithic application , you should be doing in parts . As you mentioned you have taken out one part and converted into microservice. Your monolithic and microservices are running side by side. You can map the parameters in monolithic application as long as your microservice is independent. At one point your monolithic application will be completed migrated so your each microservice will be accepting parameters on its own with out monolithic application. Considering this if your microservice can do this then it should be ok. This approach is good if you are still doing A/B testing and want to send say 25% requests to new service and rest are still being covered by your monolithic application. If there is any problem you simple turn all traffic back to monolithic.
Ques2. or should I create a new service in between which will take care of this
This service will play as your gateway. If you will be adding more services later then this service will be more useful than passing the parameters from monotlithic to microservices. I would prefer this approach , since after your microservices are completed you will be needing gateway service anyway and in this case you have it done already and this service knows about all the microservices and removing monolithic from picture won't break anything.
Ques3. should I send the params without mapped and let MS parse and filter out params from the request
I dont understand this part but make your microservice in a way that input parameters given to it are enough to complete the operation without microservice doing something additional

A: Design your MS independent of the Monolith.  That is to say your MS's API signatures should follow good standard REST practices, including naming conventions for URL paths and param names.
Your Monolith will gave to call the MS using the MS's API signature.  If the monolith calls a param "name" and your MS calls it "username", then so be it... your Monolith will just be calling the MS as if it was any other external API and it will have to user the appropriate param names and security of that API.


text:
Q: R-squared and fit of the model This post is new version of my last question. It was deleted due to my error in data. Currently data updated and verified. I have 2 models. Model 1 gives me:
Call:
lm(formula = A ~ B + C + D)

Residuals:
     Min       1Q   Median       3Q      Max
-0.62281 -0.01037 -0.00011  0.01022  0.79359

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.0002081  0.0001249  -1.667 0.095569 .
B            -0.0136995  0.0040880  -3.351 0.000806 ***
C            -0.0115854  0.0044354  -2.612 0.009004 **
D             1.6885884  0.1038811  16.255  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.02495 on 39996 degrees of freedom
Multiple R-squared:  0.006786,  Adjusted R-squared:  0.006712
F-statistic: 91.09 on 3 and 39996 DF,  p-value: < 2.2e-16

Model 2 gives me:
Call:
lm(formula = A ~ B)

Residuals:
     Min       1Q   Median       3Q      Max
-0.62188 -0.01030 -0.00007  0.01019  0.79685

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.0002189  0.0001252  -1.748  0.08047 .
B            -0.0114271  0.0040951  -2.790  0.00527 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.02504 on 39998 degrees of freedom
Multiple R-squared:  0.0001946, Adjusted R-squared:  0.0001696
F-statistic: 7.786 on 1 and 39998 DF,  p-value: 0.005266

Can someone explain me why Model 1 can be worse, then Model 2? I have only idea about miserable R-squared, which indicates that both models explain variation of dependent variable poorly. But nevertheless, I cant get, why model with more significant predictors and better R-squared can be worse.
Explanation of "worse". Both models predict some variable. Then this variable is checked against test sample (all other things - constant). Using MAE metrics I get better result for Model 2, than Model 1. I don't have access to test sample, only result of testing. I'm confused about it and looking for help, as, to my mind, there might be no situation where model 2 might be better.
Scatter plot matrix ABCD, as asked below:

I believe that ascending plot of A might be helpful too:

A: Here is an example of a fake data set which has the same sort of performance as your example:
set.seed(250116)
x3 <- rnorm(10000)
x1 <- rnorm(10000)
x2 <- rnorm(10000)
dat <- data.frame(x1, x2, x3, y = exp(5*x3) + rnorm(10000, 0, 0.1) + exp(4*(x1 + x2)))

model1 <- lm(y ~., data=dat[1:5000,])
model2 <- lm(y ~ x3, data=dat[1:5000,])

# dat[1:5000,] is the training data. The rest is test data.

mae1 <- sum(abs(predict(model1, dat[5001:10000, ]) - dat$y[5001:10000]))
    mae2 <- sum(abs(predict(model2, dat[5001:10000, ]) - dat$y[5001:10000]))

summary(model1)
summary(model2)
mae1
mae2

with the output:
> summary(model1)

Call:
lm(formula = y ~ ., data = dat[1:5000, ])

Residuals:
      Min        1Q    Median        3Q       Max
 -1809596   -646466   -225528    216168 204514069

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   237539      76163   3.119  0.00183 **
x1            460482      76847   5.992 2.21e-09 ***
x2            390556      75730   5.157 2.60e-07 ***
x3            233292      77625   3.005  0.00267 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5385000 on 4996 degrees of freedom
Multiple R-squared: 0.01416,    Adjusted R-squared: 0.01357
F-statistic: 23.92 on 3 and 4996 DF,  p-value: 2.309e-15

> summary(model2)

Call:
lm(formula = y ~ x3, data = dat[1:5000, ])

Residuals:
      Min        1Q    Median        3Q       Max
  -686743   -379900   -223291    -66778 206613240

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   231025      76619   3.015  0.00258 **
x3            233657      78094   2.992  0.00279 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5417000 on 4998 degrees of freedom
Multiple R-squared: 0.001788,   Adjusted R-squared: 0.001588
F-statistic: 8.952 on 1 and 4998 DF,  p-value: 0.002785

> mae1
[1] 4188685207
> mae2
[1] 2938392349

Here, model1 has more significant variables and a higher $R^2$, but model2 has lower mean absolute error on the test set.

A: The scatter plot matrix (and the quantile plot for A) indicate a family resemblance of all the variables, with

*

*Both negative and positive values.

*A strong concentration around a level of zero.

*Some moderate outliers with absolute values around 0.5 to 1 or so.
This implies

*

*a possibility that the outliers might have undue influence on any regressions.

*an obligation to look inside the very dense cluster of points near zero, just in case there is some hidden structure. From the graphs, I am not hopeful, but we should look.
The idea of a transformation thus arises and it seems clear that an acceptable transformation must respect the sign of values and treat positive and negative tails similarly. That certainly rules out common fudges such as $\log(x + \text{fudge})$.
I suggested
cube root $x^{1/3}$
and @Flounderer suggested
$\text{sign}(x) \ln(1 + |x|)$, which has been dubbed the "neglog" transformation.
The data are not public, so only the OP can revisit the regressions using transformed scales to see if new ideas emerge. But the main point of this answer is to underline that for values like those in this dataset

*

*the neglog transformation is so close to linear that nothing much will change.

*the cube root is going to change distributions much more (and possibly relationships too).
Many readers will have a well-grounded intuition that logarithm-like transformations are much stronger than cube-root-like transformations, which is certainly correct for moderate or large values, but not in this case when we are so near the origin.
The graph here says it all:

As always, I stress that a transformation that seems a good idea as far as producing better behaved marginal distributions is concerned is not necessarily one that will produce clearer relationships between variables.
More on cube roots:
How to transform leptokurtic distribution to normality?
Regarding how to transform leptokurtic distribution to normality
More on neglog:
John, J.A. and N.R. Draper. 1980.  An alternative family of
        transformations.  Applied Statistics 29: 190-197.
Johnson, N.L. 1949.  Systems of frequency curves generated by methods of
        translation.  Biometrika 36: 149-176.
Whittaker, J., J. Whitehead and M. Somers. 2005.  The neglog
        transformation and quantile regression for the analysis of a large
        credit scoring database.  Applied Statistics 54: 863-878.


text:
Q: how can i get RouteValueDictionary values from Page.RouteData.DataTokens how can i get RouteValueDictionary values  from Page.RouteData.DataTokens
My Code:
routes.MapPageRoute("NewsDetails", "NewsDetails/{id}/{title}",
                    "~/NewsDetails.aspx", false,
                     new RouteValueDictionary { { "id", 0 },
                     { "title", string.Empty } });

i want get id and title  because Page.RouteData.Values does not working

thanks

A: I had this problem too; Page.RouteData.Values was not returning any values but I could see the passed value under DataTokens.
It turns out that routes.EnableFriendlyUrls was messing with my route mapping, So after I read this article by Hanselman -->  and used Request.GetFriendlyUrlSegments() to get the values.
It worked but I didn't want to have to iterate through all the values to assign them (as suggested in the article). So, instead of using Request.GetFriendlyUrlSegments(), I changed the order of my route mappings (under RouteConfig.cs) so that routes.EnableFriendlyUrls(settings); is registered after all the other routes have been registered.
It was only after I changed the ordering of the routes that I got my values from Page.RouteData.Values

A: Try to use Page.RouteData.Values instead.

A: I had to use the following to access specific keys:
((System.Web.Mvc.RedirectToRouteResult)response).RouteValues["KeyName"]


text:
Q: How to list the assigned/leased IP adresses by DHCP server in Rapberry PI? I am using a raspberry pi -3 and installed dnsmasq and dhcpd server for auto IP assignment.
how to know the devices connected and their IPs.

A: In Pi we have the path of lease file is
/var/lib/misc/dnsmasq.leases
In Ubuntu it is
/var/lib/NetworkManager/*.lease
in some cases (specially with dhcpd) it is
/var/lib/dhcp/dhcpd.leases
For pi we can display the IP address of named device by
cat /var/lib/misc/dnsmasq.leases | grep "ClienDevName"|cut -d " " -f 3| awk '{print $1}'
in this command -d is for "delimiter" which is space by " " and -f 3 is to print the 3rd value after cutting with  delimiter space i.e " ".

A: DNSMASQ leases file is located at /var/lib/dnsmasq/dnsmasq.leases
DHCPD leases file is located at /var/lib/dhcp/dhcpd.leases


text:
Q: Fortran 90 to Python array How can I translate the following Fortran declarations to Python (numpy array)?
INTEGER, ALLOCATABLE::          I(:)
DOUBLE PRECISION, ALLOCATABLE:: A(:)
DOUBLE PRECISION, ALLOCATABLE:: B(:,:)
DIMENSION Z(*)
DIMENSION X(N)

A: To declare an integer, just assign like so:
i=1

To declare a float, assign like so :
a=1.0

For numpy arrays better to know the size ahead of time :
b=np.zeros((100,100)) # a 100x100 array, initialized with zeros
x=np.ones(1000)   # a 100 array , initialized with ones

If you don't know the size of the array ahead of time, assign an empty list  like so:
xlist=[]

then fill the list (say inside a loop) like so:
xlist.append(5.34)

Why this is the preferred method see this SO question.
You can make lists of lists, with a 2nd loop, as in this example of a multiplication table:
aa=[]
for i in range(10):
     a=[]
     for j in range(10):
         a.append(i*j)
     aa.append(a)

When you are done creating the list (arbitrary dimensionality) and want to be fast, convert them to numpy arrays like so
my2darray=np.array(aa)


text:
Q: MongoDB How to get specific duplicate after aggregation? I need help with creating function to get this duplicates ID's something like $unwind but in other function where I can access them separately and display them on Frontend to edit or merge them.
So when I will click "Edit" I will get these two objects shown

I need help only with  how to code it on backend, I wrote a bit more for a better view of my Problem.
This is my aggregation controller:
const Customer = require('../models/Customer');

const getDataDuplicates = (req, res) => {
  Customer.aggregate([
    {
      $group: {
        _id: {
          title: "$title",
          salutation: "$salutation",
          firstName: "$firstName",
          lastName: "$lastName",
          companyName: "$companyName",
          business: "$business",
          street: "$street",
          city: "$city",
          postcode: "$postcode",
          email: "$email",
          phone: "$phone",
        },
        uniqueIds: {$addToSet: "$_id"},
        count: {$sum: 1}
      }
    },
    {
      $match: {
        count: {$gt: 1}
      }
    },
    {
      $project: {
        "_id": "$uniqueIds",
        "title": "$_id.title",
        "salutation": "$_id.salutation",
        "firstName": "$_id.firstName",
        "lastName": "$_id.lastName",
        "companyName": "$_id.companyName",
        "business": "$_id.business",
        "street": "$_id.street",
        "city": "$_id.city",
        "postcode": "$_id.postcode",
        "email": "$_id.email",
        "phone": "$_id.phone"
      },
    },
  ]).then((data) => {
    res.send(data);
  }).catch((e) => {
    res.send(e)
  })
}

module.exports = {getDataDuplicates};

This is my example JSON response :
[
    {
        "_id": [
            "62582be393a35f4346186678",
            "62582baf93a35f4346186636"
        ],
        "title": "Jr",
        "salutation": "Mrs",
        "firstName": "Korey",
        "lastName": "Signoret",
        "companyName": "Oyoloo",
        "business": true,
        "street": "51 Annamark Parkway",
        "city": "Bryansk",
        "postcode": "241904",
        "email": "ksignoret19@youku.com",
        "phone": "571-657-2625"
    },
    {
        "_id": [
            "62582be393a35f4346186679",
            "62582baf93a35f4346186637"
        ],
        "title": "Jr",
        "salutation": "Honorable",
        "firstName": "Jocelin",
        "lastName": "Gooly",
        "companyName": "Oyoyo",
        "business": false,
        "street": "878 Myrtle Parkway",
        "city": "Casal",
        "postcode": "4600-757",
        "email": "jgooly1a@stanford.edu",
        "phone": "864-794-2909"
    }
]


text:
Q: query to a SQLite DB in android I have a table in DB called TABLE_3 which has several columns....and I wanna do a query to that table using conditions for two of its columns
KEY_SPEED>prefix
and
KEY_USER_ID_=user_id
but I don't know how to write it...can someone help me with that...here is how my query looks with only one of the conditions....How should this look with 2 conditions?
public Cursor getViteze(int prefix,int user_id)
{

    Cursor mCursor=db.query(TABLE_3, new String[]{KEY_ROWID_3,KEY_LONGITUDE,KEY_LATITUDE,
            KEY_SPEED,KEY_TIME,KEY_USER_ID_},
    KEY_SPEED + ">" + prefix,null,null,null,null);
    return mCursor;
}

Thx!
UPDATE:
public Cursor getViteze(int prefix)
{

    Cursor mCursor=db.query(TABLE_3, new String[]

{KEY_ROWID_3,KEY_LONGITUDE,KEY_LATITUDE,
                KEY_SPEED,KEY_TIME,KEY_USER_ID_},
    KEY_SPEED + ">" + prefix +" AND "+ KEY_USER_ID_ + "=" +

3,null,null,null,KEY_SPEED + " DESC");
    return mCursor;

}

A: The condition argument is like WHERE clause in SQL, so you can concatenate your conditions with AND and OR, something like the following,
KEY_SPEED + " > " + prefix + " AND KEY_USER_ID_=user_id"


text:
Q: Designing FSM using Verilog The following is the state transition table for a Moore state machine with one input, one output, and four states. Implement this state machine. Include an asynchronous reset that resets the FSM to state A.

My Code
module top_module(
input clk,
input in,
input areset,
output out); //
reg state,next_state;
parameter A=2'b00,B=2'b01,C=2'b10,D=2'b11;

 always @(*)
    begin
         case(state)
                2'b00: next_state= in ? B : A;
                2'b01: next_state= in ? B : C;
                2'b10: next_state= in ? D : A;
                2'b11: next_state= in ? B : C;
            endcase
    end
always @(posedge clk ,posedge areset)
    begin
        if(areset)
            state<= A;
        else
            state<= next_state;
    end

assign out= (state==D);
endmodule

It is showing 29 mismatches. Please tell me where did i go wrong.
The images of output is as  shown

A: You really need to include an actual link to the website in question — I finally found it here.
Did you read any of the warning messages that the site spits out about your code? They make the problem rather obvious. For example:

Warning (10199): Verilog HDL Case Statement warning at top_module.v(15): case item expression never matches the case expression File: /var/www/verilog/work/vlgNC2KRa_dir/top_module.v Line: 15
This case can never occur. One common bug is that you declared the wrong size for a signal (Also look for warnings about truncating values). For example, case(a[0]) 2'b11: something; endcase never matches because a one-bit signal can never be 2'b11.

Fixing that one problem allows your code to pass all tests.


text:
Q: How to fix English language to specific textbox in Arabic Input language mode? I need to fix the English language as input language even if the user selects Arabic keyboard for particular textbox.
Is it possible?
Once I set the input languae as English, it's changing to all textboxes and labels. But I am looking to fix it to English language for a particular textbox only.

A: Yes, it's possible using the following in the Windows application.
    private void textBox2_Enter(object sender, EventArgs e)
    {
        System.Globalization.CultureInfo TypeOfLanguage = new System.Globalization.CultureInfo("en-us");
        InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(TypeOfLanguage);
    }

A:   this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);

You can add KeyEventHandler for your textbox, if you are using the WinForms, and analize the KeyDown event, something like that

A: It defaults to English language I believe, and I don't think there is any "language" property present for textbox ... provided it's a web form. Take a look at Stack Overflow post Change input language for selected Controls - ASP.NET.

A: If this is WebForms you may well be able to use the solution in this question: Arabic text box
Something like (using jQuery):
$("#textBox").attr("lang", "en");


text:
Q: how to write makefile for c++ vs proje I need to write a makefile for a c++ visual-studio project running on windows.
I have only 5 files that I need to compile:
main,  Board.cpp, Board.h, Node.cpp, Node.h

I want to use the "make" command in cmd and compile it all.
I don't know how to write proper makefile for that, while searching I've found this Write makefile for .cpp and .hpp c++ but it is not my case..
HELP??

A: The simplest would be
all:
    g++ main.cpp Board.cpp Node.cpp


text:
Q: Cannot resize image and upload it to DB using GD with CakePHP2 I have successfully uploaded images to my database but now I need thumbnails for each of the image I am adding. I cannot seem to resize and store the image as a separate file in my webroot/img/thumbnail folder.
I need to upload a file and in the back end it should crop/resize the image and store that image as well as the original image in the database.
Below is my controller function for when I press submit on the form.
if(!empty($this->request->data['Student']['imagePath']))
                {
                        $file = $this->request->data['Student']['imagePath']; //put the data into a var for easy

                        move_uploaded_file($file['tmp_name'], 'img/thumbnail/' . $file['name']);
                        $this->request->data['Student']['imagePath'] = $file['name'];

                        move_uploaded_file($file['tmp_name'], 'img/' . $file['name']);
                        $this->request->data['Student']['resizeImage'] = $file['name'];

                }

No errors. It just doesn't save to the DB

A: Here's the solution to the problem. To create a separate folder for thumbnails, I had to take images from the 'img' folder and resize them, AND THEN move it to the thumbnail folder. :))
public function add() {
    $data = $this->Department->find('list', array(
        'fields' => array('departmentname'),
        'contain' => array(
            'Department'
        )
            )
    );

    $this->set('depdata', $data);

    if ($this->request->is('post')) {
        if (!empty($this->request->data['Student']['cvsFile'])) {

            $cvs = $this->request->data['Student']['cvsFile'];
            $ext = substr(strtolower(strrchr($cvs['name'], '.')), 1);

            if ($this->Student->validate) {

                move_uploaded_file($cvs['tmp_name'], 'files/' . $cvs['name']);
                $this->request->data['Student']['cvsFile'] = $cvs['name'];
            }
        }

        if (!empty($this->request->data['Student']['imagePath'])) {
            $file = $this->request->data['Student']['imagePath'];
            move_uploaded_file($file['tmp_name'], 'img/' . $file['name']);
            if ($file['name'] == "") {

            }
            else {

                list($old_width, $old_height) = getimagesize(WWW_ROOT . "img/" . $file['name']);

                $new_width = 50;
                $new_height = 50;

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1);

                if ($ext == 'png') {

                    $new_image = imagecreatetruecolor($new_width, $new_height);
                    $old_image = imagecreatefrompng(WWW_ROOT . "img/" . $file['name']);
                    imagecopyresampled($new_image, $old_image, 0, 0, 0, 1, $new_width, $new_height, $old_width, $old_height);
                    imagepng($new_image, WWW_ROOT . "img/thumbnail/" . $file['name'], 3);
                }
                elseif ($ext == 'jpg') {
                    $new_image = imagecreatetruecolor($new_width, $new_height);
                    $old_image = imagecreatefromjpeg(WWW_ROOT . "img/" . $file['name']);
                    imagecopyresampled($new_image, $old_image, 0, 0, 1, 1, $new_width, $new_height, $old_width, $old_height);
                    imagejpeg($new_image, WWW_ROOT . "img/thumbnail/" . $file['name'], 30);
                }

                $this->request->data['Student']['imagePath'] = 'thumbnail/' . $file['name'];
            }

            if ($this->Student->save($this->request->data)) {
                $this->Flash->set("Student has been added.");
                $this->redirect(array('action' => 'add'));
            }
        }
    }
}