text:
Q: Create a simple ToDo application which would be able to add, delete and update ToDo with spring boot starter web.But update scenario is not working Below is the todo controller which i am using to add,delete and update todo.This is simple spring boot application for which i am using sprint boot starter web.
TodoController
    package com.Mayur.Controller;

    import com.Mayur.Model.Todo;
    import com.Mayur.Service.ToDoService;
    import com.Mayur.Service.ValidationCheck;
    import org.apache.log4j.Logger;
    import org.json.simple.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.*;

    import javax.servlet.http.HttpServletRequest;
    import javax.validation.Valid;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.stream.Collectors;

    @Controller
    @SessionAttributes("name")
    public class ToDoController {
        private final static Logger log = Logger.getLogger(ToDoController.class);

        @Autowired
        ToDoService todd;

        @InitBinder
        public void init(WebDataBinder web)
        {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            web.registerCustomEditor(Date.class,new CustomDateEditor(sdf,false));
        }
        @RequestMapping(value = "/listtodos")
        public String listTodos(ModelMap m) {
            List<Todo> todos = todd.retrieveToDo();
            String kk =(String)m.get("name");
            m.put("l",kk);
            m.put("td",todos);
            return "listtodos";
        }

        @RequestMapping(value ="/addTodo")
        public String addTodo(ModelMap map){
            map.put("todo",new Todo(0,(String)map.get("name"),"",new Date(),false));
            return "addTodo";
        }
        @RequestMapping(value ="/addTodo",method = RequestMethod.POST)
        public String addTodoNew(ModelMap map, @Valid Todo tod, BindingResult bindingResult){
            System.out.println("server restarted");
            if(bindingResult.hasErrors())
            {
                return "/addTodo";
            }
            System.out.println("Tod is :"+tod);
            List<Todo> tdlist= todd.addTodo(tod);
            map.put("addList",tdlist);
            return "redirect:/listtodos";
        }

       @RequestMapping(value="/delete")
       public String delete(@RequestParam int id,ModelMap m)
       {
           List<Todo> tdlist = todd.retrieveToDo();
           log.info(tdlist);
           tdlist.removeIf(i->i.getId()==id);
           m.put("td",tdlist);
           m.put("message","Deleted Sucessfully");
           log.info(tdlist);
           return "listtodos";
       }

       @RequestMapping(value="/update")
        public String updateTodo(@RequestParam int id,Model m)
       {
           m.addAttribute("registerId",id);
           return "updateTodo";
       }

        @RequestMapping(value="/updateTodos")
        public String updateTodos(@RequestParam String name,Model m)
        {

            m.addAttribute("paramcheck",name);
            log.info("parameter is : "+name);
            return "updateTodos";
        }

        @RequestMapping(value="/updateTodos",method = RequestMethod.POST)
        public String finalUpdate(@RequestParam int id,@RequestParam String name,@RequestParam Object updateField, ModelMap mp)
        {
            List<Todo> to = todd.retrieveToDo();
            List<Todo> newTodo=to.stream().filter(i->i.getId()==id).map(v->{
                if(name.equalsIgnoreCase("Desc"))
                {
                    v.setDesc((String)updateField);
                }
                else if(name.equalsIgnoreCase("user"))
                {
                    v.setUser((String)updateField);
                }
                else if(name.equalsIgnoreCase("status"))
                {
                    v.setDone(updateField.equals("active")?true:false);
                }
                return v;
            }).collect(Collectors.toList());
            log.debug("list :"+newTodo);
            System.out.println("list "+newTodo);
            System.out.println("coming to update todo controller");
            mp.put("td",newTodo);
            return "redirect:/listtodos";
        }
    }

Below is the jsp page where i am displaying all the list of todos .
listtodos.jsp
<%@ include file="common/header.jspf"%>
<%@ include file="common/navigation.jspf"%>

${message}

    User Id
    User Name
    Description
    Date
     Status
     Delete
     Update

<c:forEach items = "${td}" var="s">
${s.getId()}
${s.getUser()}
${s.getDesc()}
<d:formatDate value ="${s.getDate()}" pattern="dd/MM/yyyy"/>
${s.isDone()}
Delete
Update

</c:forEach>

Add new todo

<%--
Delete Todo
--%>
<%@ include file="common/footer.jspf"%>

Update todo where i am giving choice to the user what he wants to update and todo id i am passing from list todo.jsp
UpdateTodo.jsp

<title>
Login Application
</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

What do you want to update :
User
Description
Date
Status

update todos jsp where i am actually updating something in the todo

updateTodos.jsp

<title>
Login Application
</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

<fieldset class="form-group">
Enter the ${paramcheck}:
<input type="text" name="updateField"/>

<input type="submit" value="update"/>
</fieldset>

</form>

Below is pom.xml i am using for this project

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.Mayur</groupId>
    <artifactId>SpringLoginApplication</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>default</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.26.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>

But when i am clicking on update.It is not hitting my update request in todo controller.


text:
Q: Parse JS file via Python have a question, how can I properly get the value for field 'data' from the following JS file via Python? Tried do it like parsing a json, but for json.load it's in incorrect format. So will be thankful for a help.
return [
{
    'id'         : 1,
    'category'   : 'html5',
    'name'       : {
        'en' : 'XSS via formaction - requiring user interaction (1)',
        'ja' : 'formaction\u7d4c\u7531\u3067\u306eXSS - \u30e6\u30fc\u30b6\u306e\u4ecb\u5728\u304c\u5fc5\u8981',
        'ru' : 'ПаÑÑивный Ñкриптинг через formaction (1)',
        'cs' : 'XSS pomocí formaction - vyžaduje uživatelskou interakci (1)',
        'de' : '',
        'tr' : 'formaction ile XSS - kullanıcı etkileşimi gerektiren (1)',
        'zh' : '通过formaction属性进行XSS - 需è¦ç"¨æˆ·è¿›è¡Œäº¤äº' (1)'
    },
    'data'       : '<form id="test"></form><button form="test" formaction="%js_uri_alert%">X</button>',
    'trigger'    : 'document.getElementsByTagName("button")
    'urls'    : ['http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#attr-fs-formaction'],
    'howtofix'   : {
        'en' : 'Don\'t allow users to submit markup containing "form" and "formaction" attributes or transform them to bogus attributes. Avoid "id" attributes for forms as well as submit buttons.',
    'ja' : '\u0022form\u0022\u3068\u0022formaction\u0022\u5c5e\u6027\u3092\u542b\u3080\u8981\u7d20\u3092\u30e6\u30fc\u30b6\u306b\u5165\u529b\u3055\u305b\u306a\u3044\u3001\u3042\u308b\u3044\u306f\u305d\u308c\u3089\u306e\u5c5e\u6027\u3092\u7121\u52b9\u306a\u5024\u306b\u5909\u63db\u3059\u308b\u3053\u3068\u3002\u0022id\u0022\u5c5e\u6027\u306fform\u3060\u3051\u3067\u306a\u304fsubmit\u30dc\u30bf\u30f3\u306b\u3064\u3044\u3066\u3082\u5bfe\u5fdc\u3059\u308b\u3053\u3068\u3002',
        'ru' : 'Ðе разрешайте пользовательÑкую разметку, Ñодержащую атрибуты form и formaction или неправильные Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñтих атрибутов. Избегайте атрибут id в формах, как и Ñлементы ввода submit типа.',
        'cs' : 'Nedovolte uživatelům vložit kód obsahující atributy "form" a "formaction" Äi jejich "zkomolené" tvary. VyhnÄ›te se atributu "id" u formulářů i u odesílacích tlaÄítek.',
        'de' : '',
        'tr' : 'Kullanıcıların "form" ve "formaction" markup\'larını yollamaları engellenmeli veya bu özellikler kullanışsız hale getirilmelidir. Submit butonlarında olduğu gibi formlarda "id" özelliklerinden kaçının.',
        'zh' : 'ä¸è¦è®©ç"¨æˆ·æäº¤åŒ…å« "form" å'Œ "formaction"属性çš"æ ‡ç¾.é¿å…在form中出现id属性åŠæ交按钮.'
    },
    'browsers'   : {
        'firefox' : ['4.0', 'latest'],
        'opera': ['10.5', 'latest'],
        'chrome': ['10.0', 'latest'],
        'safari' : ['4.0.4', 'latest'],
        'internet explorer' : ['10', 'latest (inside form element)']
    },
    'tags'       : ['xss', 'html5', 'opera', 'chrome', 'firefox', 'formaction', 'javascript', 'button'],
    'reporter'   : '.mario'
}
]

Thanks a lot.

A: You may look into JavaScript parsers, like slimit (working example here). Or, you can also extract the data key value with a regular expression:
import re

match = re.search(r"'data'\s+:\s+'(.*?)',", script, re.MULTILINE | re.DOTALL)
if match:
    print(match.group(1))

A: It has a syntax error; 'trigger': 'document.getElementsByTagName("button") should end with ',.
If that is fixed, and you remove return from the start, the data can be gotten like
import ast

struct = ast.literal_eval(your_string)
data = struct[0]['data']

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to share cookie between two different domain i just do not know that is it at all feasible to share cookie between two different domain but when i need to share cookie between two sub domain then i do it below way
HttpCookie cookie = new HttpCookie("cookiename", "value");
cookie.Domain = "domain.com";

For forms authentication set this in web.config

<forms name=".ASPXAUTH"
       loginUrl="login.aspx"
       protection="All"
       timeout="30"
       path="/"
       requireSSL="false"
       domain="domain.com">
</forms>

A: I think that you can use jQuery for that and only specify the domain
$.cookie('the_cookie', 'the_value', { path: '/', domain: 'www.example.com' });


text:
Q: Internet Explorer gives error: ')' is expected, while firefox isn't? Internet Explorer gives an error ')' is expected while Firefox is running this code fine. According to the Internet Explorer console the error is situated in the first line:
function HTMLtableRows (titles=[] , values=[]) {
How can I fix this problem?

function HTMLtableRows (titles=[] , values=[]) {

            var i, j;
            var str, strT, strM;
            str = '
';

            str = str + '
';
            for (j = 0; j < titles.length; j++) {
                str = str + '' + titles[j] + '	';
            }
            str = str + '
' + '
';
            for (j = 0; j < titles.length; j++) {
                str = str + 'Tijdstip	' + 'Looptijd	';
            }
            str = str + '
' + '
';
            for (j = 0; j < titles.length; j++) {
                var a = values[j].split('\r');
                strT = ''
                strM = ''
                for (i = 0; i < a.length; i++) {
                    var b = a[i].split('=');
                    if (b[1] != undefined) {
                        strT = strT + b[0];
                        strM = strM + b[1] + 'min';
                    }
                    if (i < a.length - 1) {
                        strT = strT + '
';
                        strM = strM + '
';
                    }
                }
                str = str + '' + strT + '	';
                str = str + '' + strM + '	';
            }
            str = str + '
';

            str = str + '
';

            return str;

        }

A: IE does not support default parameters.
Just do it like this if you want

function HTMLtableRows (titles , values) {
  if (!titles) titles = [];
  if (!values) values = [];

  console.log(titles);
  console.log(values);
}

a1 = [1,2,3];

HTMLtableRows(a1, null);
HTMLtableRows({foo: "bar"}, undefined);
HTMLtableRows(2, NaN);
HTMLtableRows("not empty string", "");
HTMLtableRows(1, 0);
HTMLtableRows(true, false);

All of the following values

*

*null

*undefined

*NaN

*""

*0

*false
will become an empty array. If you don't want some of those values to be overwritten with an empty array adjust if conditions as you see fit.
Example where you allow values to remain unchanged as "", 0 and NaN:

function HTMLtableRows (titles , values) {

  if (!titles) titles = [];
  if(values != "" &&
     values != 0  &&
     !isNaN(parseInt(values))
    )
    values = [];

  console.log(titles);
  console.log(values);
}

HTMLtableRows("string", "");
HTMLtableRows(1, 0);
HTMLtableRows(7, NaN);

A: Thanks to alex i've solved this with the adjustments below:

function HTMLtableRows (tmpTitles , tmpValues) {
  titles=[];
  values=[];
  titles = tmpTitles;
  values = tmpValues;
  //...
}


text:
Q: Git - master branch 26 ahead 22 behind Please help to bring the master branch to match with the remote master branch which has all the recent changes.
Please find below the git status:
$ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 26 and 22 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

A: The message showed by git status means that when you make local changes there already has new changes on remote which you were not pull first.
There are below options you can refer:

*

*git pull directly and then solve the merge conflicts as git message hint you, then push your local master to remote repo.

*Pull the remote changes firstly, and then rebase your local changes on the top of latest master branch by git pull origin master --rebase. But you should also solve the conflicts may occur.

*If your don't want the local changes you made on master branch, then reset local master as origin/master by git fetch origin master and git reset --hard origin/master.


text:
Q: Where can I find math plans for US primary / secondary education? I'd really like to have an overview of how math is being studied in US. I would love to see how it compares to primary / secondary education in Europe (ex Yugoslav countries).
TIA

A: In the U.S., precollege education is not nearly as centeralized as it is in many other countries, so something like the following google search is probably more helpful than trying to look for some type of U.S. national standard:
http://www.google.com/search?q=math+%22state+standards%22+grade

A: Someone from University of Puget Sound wrote a paper check http://www2.ups.edu/faculty/woodward/Mathematics%20Education%20in%20the%20United%20States.pdf
Also check this paper http://www.nctm.org/uploadedFiles/About_NCTM/Corresponding_Societies/MathEdUS2008-Dossey.pdf
And one final link http://www.csun.edu/~vcmth00m/AHistory.html
These are all copyright materials.  You should contact Prof. David Klein from California State University if you are working on such topic.

A: Unless someone else gives a better answer, I'll select this one:
Among answers to this question What should the high school math curriculum consist of?, I found a great link with correct answer to my questions: http://www.corestandards.org/the-standards
This basically does it. Sweet.


text:
Q: Wait for key before reading from a JTextField I have a program that will make a JFrame with a JTextField. How do I get it to wait for text to be in the JTextField / the enter key is pressed?
public static void main(String[] args) {
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   int width = (int) screenSize.getWidth();
   int height = (int) screenSize.getHeight();
JFrame frame = new JFrame();
frame.getContentPane().add(new Text());
JTextField field = new JTextField(10);
frame.add(field, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width,height-55);
frame.setVisible(true);
   // There is a keylistener here called listener. It was 100 lines. Did not want to copy
frame.addKeyListener(listener);
double x = 0;

x = Double.parseDouble(field.getText());

System.out.println(x);

I want
x = Double.parseDouble(field.getText());

to run only when someone types something in the JTextField in the JFrame.

A: *

*Don't use a KeyListener

*Add a DocumentListener to your JTextField's Document.

*Inside of this listener check to see if the Document is empty or not.

*If not empty, change the state of your program to allow the calculation, perhaps by enabling or disabling a JButton or Action.

For example:
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

public class DisbleButton extends JPanel {
   private JTextField field = new JTextField(10);
   private ButtonAction buttonAction = new ButtonAction();
   private JButton button = new JButton(buttonAction);

   public DisbleButton() {
      add(field);
      add(button);
      buttonAction.setEnabled(false);

      field.getDocument().addDocumentListener(new FieldDocListener());
   }

   private class FieldDocListener implements DocumentListener {

      @Override
      public void changedUpdate(DocumentEvent dEvt) {
         testDoc(dEvt);
      }

      @Override
      public void insertUpdate(DocumentEvent dEvt) {
         testDoc(dEvt);
      }

      @Override
      public void removeUpdate(DocumentEvent dEvt) {
         testDoc(dEvt);
      }

      private void testDoc(DocumentEvent dEvt) {
         Document doc = dEvt.getDocument();
         buttonAction.setEnabled(doc.getLength() > 0);
      }

   }

   private class ButtonAction extends AbstractAction {
      public ButtonAction() {
         super("Press Me");
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // TODO do calculation here!

      }
   }

   private static void createAndShowGui() {
      DisbleButton mainPanel = new DisbleButton();

      JFrame frame = new JFrame("DisbleButton");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}


text:
Q: How to replace ddply with Dplyr or Data.Table I am currently using ddply to apply a function I have written to a data frame. The function evaluates each row based on the values in the columns and then applies a number of other functions to the data in that row. The result is a data frame with the same structure as the input data frame and an additional column with the result of the applied function for each row.
My problem is the data set is reasonably large and therefore using ddply takes a long time - too long for the purpose!
I have read a number of other SO questions and blog posts on replacements to ddply when time is of the importance. Most posts either recommend using data.table or some combination of functions in the dplyr package with do. While speed is of the most importance, I have never used data.table so ease of use / intuitiveness is also important.
Similarly, while this question was very useful in explaining how to use different dplyr functions in combination your own function, I also need to pass in other objects to my function, which I am unsure how to do using the answer in the question.
I have created a simplified example below. My question then is how to replicate the below ddply function call with either dplyr or data table given my above points.
First, I set up some data to mimic the structure of the actual data
noObs <- 1e5
dataIn <- data.frame(One = rep(c("J", "K"), noObs/2), Two = rep(c("ID", "BR", "LB", "OZ"), noObs/4),
                     Three = runif(noObs))

secondaryData <- data.frame(Two = c("ID", "BR", "LB", "OZ"), Size = c(300, 500, 250, 400))

A simplified example of my function is below (in practice, the function parameters are greater than 2 and it calls other functions in itself)
MyFunction <- function(dataIn, secondaryData){

  groupNames <- c("BR", "LB")

  if(dataIn$One == "J"){
    if(!(dataIn$Two%in%groupNames)){
      if(dataIn$Two == "ID"){
        idx <- match(dataIn$Two, secondaryData$Two)
        value <- secondaryData[idx, "Size"]
        dataIn$newCalc <- dataIn$Three*value
      }else{
        dataIn$newCalc <- dataIn$Three*1000
      }
    }else{
      idx <- match(dataIn$Two, secondaryData$Two)
      value <- secondaryData[idx, "Size"]
      dataIn$newCalc <- dataIn$Three*value+1
    }
  }else{
    idx <- match(dataIn$Two, secondaryData$Two)
    value <- secondaryData[idx, "Size"]
    dataIn$newCalc <- dataIn$Three*value
  }

  return(dataIn)

}

The ddply call looked like
dataOut <- ddply(dataIn, names(dataIn), MyFunction, secondaryData)

Finally, some examples of things I have tried (I am yet to try data.table)
dataIn %>% group_by(names(dataIn)) %>% do(MyFunction(dataIn, secondaryData))
dataIn %>% group_by(names(dataIn)) %>% MyFunction(dataIn, secondaryData)
dataIn %>% group_by(.dots = names(dataIn)) %>% MyFunction(secondaryData)

EDIT
I have been able to find a way with dplyr that works except it is even slower than with ddply and I can't figure out how to use group_by with names. This doesn't seem right to me as dplyr is meant to be faster.
In addition, I have been experimenting with data.table, but haven't been able to get it to work. Again, I am looking for something that runs faster than ddply
#Plyr
start <- proc.time()
dataOut <- ddply(dataIn, names(dataIn), MyFunction, secondaryData)
plyrTime <- proc.time() - start

#Dplyr
#Works
start <- proc.time()
res <- dataIn %>% group_by(One, Two, Three) %>% do(MyFunction(.,secondaryData))
dplyrTime <- proc.time() - start
#Doesn't work
res <- dataIn %>% group_by(.,names(dataIn)) %>% do(MyFunction(.,secondaryData))

#Data.table
dataInDT <- data.table(dataIn)
dataInDT[,.(MyFunction(.,secondaryData)), by=.(One, Two, Three)]

A: I found a solution using data.table. Notably, it performs the correct calculations for each row but at a remarkably faster speed. The format of function is different to adapt to the different style of data.table. I'm sure there is an even better or more correct way to solve it using data.table, but the below solution works well.
dataInDT <- data.table(dataIn)

groupNames <- c("BR", "LB")
start <- proc.time()
dataInDT[, NewCalc := {
  if(One == "J"){
    if(!(Two%in%groupNames)){
      if(Two == "ID"){
        Three*secondaryData[match(Two, secondaryData$Two), "Size"]
      }else{
        Three*1000
      }
    }else{
      Three*secondaryData[match(Two, secondaryData$Two), "Size"]+1
    }
  }else{
    Three*secondaryData[match(Two, secondaryData$Two), "Size"]
  }}, by=.(One, Two, Three)]
datTableTime <- proc.time() - start

Comparing this to the old solution and you can see the speed is greatly improved
start <- proc.time()
dataOut <- ddply(dataIn, names(dataIn), MyFunction, secondaryData)
plyrTime <- proc.time() - start

Of course, in practice the data.table function I used was even more intricate, in particular the by section was much longer.
I was unable to find a solution using dplyr and am still curious to know how it would work.


text:
Q: How to program regex to include space in C# I have a regex, which is suppose to validate strings like R1 AND R2 or R1 AND R3 OR R2 AND R4.
This is my regex:
^[R\d+ (\bAND\b|\bOR\b)]+ R\d+$

Today, I found out that it also accepts strings like "R1AND R2" or "R1 ANDR R2". How can I make sure that my regex must detect spaces between the R\d, AND and OR?
Thanks!

A: You're using a character class, it's wrong, use a non capture group instead:
^(?:R\d+\s(?:AND|OR)\s+)*R\d+$

A: ^R\d+(?:\s+(?:AND|OR)\s+R\d+)*$

Try this.See demo.
https://regex101.com/r/rU8yP6/4
The reaosn yours is not working is because you have included evrything inside [] character class which does not maintian sequence and is just a pool of characters to chose from.
This will match R1 AND R3 OR R2 AND R4 and R1 AND R3 but not R1AND R3


text:
Q: What is the best way to look under Juliet's skirt? When I played Lollipop Chainsaw, I figured out the there were many upskirt moments. There is also an achievement for looking under Juliet's skirt by "accident".
What is the best way to do that? Will there be a punishment of some sort if I look under this cheerleader's skirt?

A: If you stand idle for a couple of seconds, Juliet should stick her chainsaw into the ground. Just manipulate your camera to achieve your evil purpose. She will cover herself, simply push forward and she will eventually give up.
The achievement name is "I Swear ! I Did It By Mistake !".
source : XBox Achievements


text:
Q: Cardinals below the critical point of a generic embedding This may be an easy question.  Are the cardinals below the critical point of a precipitous ideal embedding always absolute between the generic ultrapower and the generic extension?
To focus on the simplest case, suppose $I$ is a precipitous normal ideal on $\omega_2$.  Let $G$ be generic for $\mathcal{P}(\omega_2)/I$.  Let $j : V \to M$ be the generic ultrapower.  Then $\omega_1^V$ is not moved by $j$, but could it be the case that $\omega_1^V$ is countable in $V[G]$?  Of course the answer is no if $I$ has enough presaturation.
Edit: As a subproblem towards a consistent negative answer, can we find (from some large cardinal assumption) a measurable $\kappa$ with measure $U$, and a $\kappa$-c.c. forcing $\mathbb{P}$ such that $\mathbb{P}$ preserves $\omega_1$, but $j_U(\mathbb{P})$ collapses $\omega_1$?  (Not in $Ult(V,U)$ of course, but in $V$.)

A: Mohammad's answer here can be applied to give many negative examples.  Here's one of optimal consistency strength.  By Goldring's improvement on a result of Foreman-Magidor-Shelah, if we use the Levy collapse to turn a Woodin cardinal $\delta$ into $\aleph_{\omega+2}$, then $NS_{\aleph_{\omega+1}}$ is precipitous in the extension.  Forcing with $NS_{\aleph_{\omega+1}} \restriction cof(\omega_n)$ for $n \geq 1$ collapses $\aleph_{\omega+1}$ and $\delta$, and so must change $\delta$'s cofinality to some $\mu < \aleph_\omega$.  By Mohammad's argument, all cardinals in $(\mu,\delta]$ are collapsed.


text:
Q: Integrating and plotting Green's function using Maxima I am trying to integrate product of two Green's functions and plot the results using Maxima.  The problem is that Green's functions have singularities.
$ I=\int_{-\infty}^{+\infty}dxG1(x)G2(x)(F1(x)-F2(x))$
and
$ G1(x) =  \frac{1}{ (x-0.1)+0.5+0.00001i} $
$ G2(x) =  \frac{1}{ (x-0.1)+0.5-0.00001i} $
$ F1(x) = \frac{1}{ 1+e^{\frac{x}{0.2}}}$
$ F2(x) = \frac{1}{ 1+e^{\frac{x+0.4}{0.2}}}$
When I use wxMaxima (CAS), it fails to integrate and it fails to plot the solution y.  I know that the solution plot should look like a smoothed step function where rising edge should be at x=0.1.
Any suggestions how to code wxMaxima/mathematica is appreciated. Thanks.


text:
Q: paramiko operating network firewall meet some question,Any suggestions? I use python paramiko operate a network firewall.
when I login to the firewall with terminal,It look like this:
when I login to the firewall with terminal
But when I use python's paramiko code below,It returns is not my expected. when I hit configure command, it should in "config" mode, but it is not worked. Any suggestions for me. TKS
use python paramiko
def send_cmd(cmd, ch):
    cmd += '\r'
    result = ''
    while True:
        time.sleep(0.2)
        ret = ch.recv(65535)
        ret = ret.decode('utf-8')
        result += ret
        break
    return result

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("11.1.1.122", "22", "root", "xxxx", timeout=15)
ch = ssh.invoke_shell()
a = send_cmd('configure', ch)
a = send_cmd('address 1.1.0.1-123123', ch)
print(a)
ssh.close()


text:
Q: Editorpart positioning at the bottom I created my own custom editor part for my web part.
But when I add it to the web part, it displays by default at the top, what i would like to have is to position it at the bottom.
Anyona has any idea, how to achieve that?
Here is the screenshot:


text:
Q: Pandas HDFStore: changing dtype of indexes Does there exist a way of controlling the data type that is used for storing indexes of data frames when using HDFStore.append?
It seems pandas indexes are always stored with 64bits in the hdf5 file. I would like to increase storage efficiency and reduce the size of the index columns.
I have a unique 3 column multi index and saving them as uint64 indexes is an enormous waste of space in my application:
Given the following data frame
In [15]: df.dtypes
Out[15]: indA              int32
indB              int16
indC              int8
data              float32
dtype: object

simply setting df.set_index(['indA', 'indB', 'indC']) before HDFStore.append results in indA, indB and indC being stored as Int64Col in the hdf5 file.
Not setting a pandas index and specifying pytables data columns instead:
store.append('mytable', df, data_columns=['indA', 'indB', 'indB'])

indA, indB and indC are stored with their original dtypes, however an additional Int64Col is stored in the hdf5 file.
This does not really help: by storing in the original dtypes I am saving/conserving 56 bits for the three ind columns. The additional (superfluous) index column however costs 64 bits...
Any ideas?

A: Your approach is the correct one. Data columns provide the searching capability and provide dtype preservation. Index storage is pretty fixed at the moment.
Providing an option to store the index is an open issue, see here. I have done a bit of work on it, but its not high priority ATM. Welcome to have you take a look.
The usual answer to wanting to shrink storage space is to use compression. You seem to be jumping thru a lot of hoops to save a relatively small amount of storage, but that's my2c.


text:
Q: Trigonometric Series Proof I am posed with the following question:
Prove that for even powers of $\sin$:
$$ \int_0^{\pi/2} \sin^{2n}(x) dx = \dfrac{1 \cdot 3 \cdot 5\cdots (2n-1)}{2 \cdot 4 \cdot 6 \cdots 2n} \times \dfrac{\pi}{2} $$
Here is my work so far:

*

*Proof by induction

$P(1) \Rightarrow n = 2 \Rightarrow $
$$\int_0^{\pi/2} \sin^4(x) dx = \dfrac{1 \cdot 3}{2 \cdot 4} \times \dfrac{\pi}{2} $$
$$ \frac{3\pi}{16} = \frac{3 \pi}{16} $$
Base Case Succeeds. (The left hand side evaluated by MAPLE)
$P(n+1) \Rightarrow n = n + 1 \Rightarrow$
$$ \int_0^{\pi/2} \sin^{2n + 1}(x) dx = \int_0^{\pi/2} \sin^{2n} x  \sin x dx$$
$$ = \int_0^{\pi/2} (1 - \cos^2x)^n \sin x dx$$
Let $u = \cos x, du = - \sin x dx \Rightarrow$
$$ -\int_0^{\pi/2} (1-u^2)^n du$$
Now I am stuck and unsure what to do with this proof ... Any help would be greatly appreciated
(I also tried using the reduction formulas to no avail)
EDIT
I have completed the proof.
I am posting this here for any other people who may have the same question...
We will prove by induction that $\forall n \in 2 \mathbb{N}_{>0}$
\begin{align*}
   \int_0^{\pi/2} \sin^{2n} x dx & = \frac{1 \times 3 \times 5 \times \cdots \times (2n - 1)}{2 \times 4 \times 6
   \times \cdots \times 2n} \times \frac{\pi}{2} \tag{1}
\end{align*}
With $k = 1$ as our base case, we have
\begin{align*}
   \frac{1}{2}x - \frac{1}{4} \sin{2x} \bigg|_{0}^{\pi / 2} & = \frac{\pi}{4} \tag{67}
   \\ \frac{1}{2} \times \frac{\pi}{2} & = \frac{\pi}{4}
\end{align*}
Let $n \in 2\mathbb{N}_{>0}$ be given and suppose (1) is true for $k = n$. Then
\begin{align*}
  \int_0^{\pi/2} \sin^{2n+2} x dx & = - \frac{1}{2n+2} \cos^{2n-1}x \sin x \bigg|_{0}^{\pi / 2} + \frac{2n+1}{2n+2} \int_0^{\pi/2} \sin^{2n} x dx \tag{67} \\
 & = \frac{2n+1}{2n+2} \int_0^{\pi/2} \sin^{2n} x dx \\
 & = \frac{1 \times 3 \times 5 \times \cdots \times (2n + 1)}{2 \times 4 \times 6
   \times \cdots \times {(2n+2)}} \times \frac{2n+2}{2n+1} \times \frac{\pi}{2} \\
 & = \frac{1 \times 3 \times 5 \times \cdots \times (2n - 1)}{2 \times 4 \times 6
   \times \cdots \times 2n} \times \frac{\pi}{2} \\
 & = \int_0^{\pi/2} \sin^{2n} x dx
\end{align*}
Thus, (1) holds for $k = n + 1$, and by the principle of induction, it follows that that (1) holds for all even numbers. $\square$

A: This proof  makes use of the gamma and beta functions. We have the basic identity $$B(x, y) = \frac{\Gamma(x)\Gamma(y)}{\Gamma(x + y)} $$
Note that $$B(x, y) = \int_0^1 t^x(1 - t)^y \,dt $$
by definition. Put $x = \sin^2\theta$. Thus we have $$\int_{0}^{\pi/2}\sin^{2m + 1}\theta\cos^{2n + 1}\theta \,\,d\theta = \frac{\Gamma(m)\Gamma(n)}{2\Gamma(m + n)}$$
Note that since we were originally dealing with two independent variables, we need to maintain those after making this substitution, hence the $m$ and $n$.
Now put $2k = 2m + 1$ and $2n + 1 = 0$. This gives the following result:
$$\int_{0}^{\pi/2}\sin^{2k}\theta \,d\theta = \frac{\Gamma[\frac{1}{2}(2k + 1)]\Gamma(1/2)}{2\Gamma(k + 1)} $$
The denominator is simply $2\cdot k!$ and the numerator is $\pi\cdot k!\cdot \binom{k - 1/2}{k}$
Expanding the binomial coefficient gives the required result.

A: For $k=1$, it's straightforward to verify$$\int_0^{\pi/2}\sin^2x~dx=\int_0^{\pi/2}\frac{1-\cos 2x}2dx=\frac\pi4$$
Assume $k=n$ we have
$$I_n=\int_0^{\pi/2}\sin^{2n}x~dx=\frac{(2n-1)!!}{(2n)!!}\frac\pi2$$
Then for $k=n+1$,
$$\begin{align}I_{n+1}&=\int_0^{\pi/2}\sin^{2n}x(1-\cos^2x)dx\\
&=I_n-\int_0^{\pi/2}\sin^{2n}x\cos^2x~dx\\
&=I_n-\left.\frac1{2n+1}\sin^{2n+1}x\cos x\right|_0^{\pi/2}-\frac1{2n+1}\int_0^{\pi/2}\sin^{2n+1}x\sin x~dx\\
&=I_n-\frac1{2n+1}I_{n+1}\end{align}$$
Solve the recurrent relation and obtain
$$I_{n+1}=\frac{2n+1}{2n+2}I_n=\frac{(2n+1)!!}{(2n+2)!!}\frac\pi2$$


text:
Q: How to change the filename before saving in carrierwave in Rails? In the controller I have:
ext = File.extname(params[:file].original_filename)
 basename = File.basename(params[:file].original_filename, ext)
 time = Time.now.to_i

 for_hash = Digest::MD5.hexdigest([basename, time].join(''))[0..5]
 new_file_name = [for_hash, ext].join('')

And it save to database the new file name. But how can with this code art change the file name in the folder before the save?

A: In your uploader file, you can change the filename,
class ImageUploader < CarrierWave::Uploader::Base
   def filename
     "#{model.id}.jpg" # to name file with their id
   end
 ....
end

I did it a long time ago, I think that was this.


text:
Q: Is TabbedArea deprecated in React-Bootstrap? I've upgraded to react-bootstrap 0.28.1 and React 0.14.3
Since this change ReactBootstrap TabbedArea and TabPane no longer works. When we build our project (using web pack) TabbedArea is undefined.
It seems that replacing it with Tabs and Tab works.
Is TabbedArea known to be no longer supported?

A: yes. Use Tabs instead. With thanks to the react-bootstrap team:
https://github.com/react-bootstrap/react-bootstrap/issues/1565


text:
Q: Spring - No WebApplicationContext found: no ContextLoaderListener registered? I am getting the following error while trying to run a Spring project
HTTP Status 500 - java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

Inspite of adding the listner on to my web.xml. I am still getting this error. Below is the listener I have added to my web.xml :
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/HelloWebRedirect-servlet.xml</param-value>
 </context-param>

 <listener>
 <listener-class>
  org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>

Can someone help me out in this regard?

A: Try like this
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

A: If you using Annotation:
public class SpringWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(ApplicationContextConfig.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
                new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        ContextLoaderListener contextLoaderListener = new ContextLoaderListener(appContext);

        servletContext.addListener(contextLoaderListener);

        // Filter.
        FilterRegistration.Dynamic fr = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);

        fr.setInitParameter("encoding", "UTF-8");
        fr.setInitParameter("forceEncoding", "true");
        fr.addMappingForUrlPatterns(null, true, "/*");
    }

}

A: Hi @user2681868 I was also facing the same problem here are the steps you should follow.
1) in web.xml define this
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2) create a applicationContext.xml in web-inf with this content
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    </beans>

A: Please remove the first "/" in the
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      WEB-INF/HelloWebRedirect-servlet.xml
    </param-value>
</context-param>

A: Instead of specifiying contextConfigLocation try to specify dispatcher servlet
<servlet>
     <servlet-name>HelloWebRedirect</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
</servlet>

choose your servlet name according this template: /WEB-INF/${servlet-name}-servlet.xml


text:
Q: Implementing a Time-Out function in VBA in case code gets stuck I'm currently using VBA to automate pulling of large data-sets. However, it often happens that either

*

*the sub simply gets stuck and does not update any more/connection breaks (application is still responsive) or

*the application becomes totally unresponsive.

Is there a way to implement a time-out function which automatically closes the application after say 15 minutes elapse?
In other programming languages, I would have solved this using multi-threading. But not sure if something similar is feasible in VBA given that it is entirely single-threaded.
The basic algorithm I employed to automate the data looks like this:
Sub automateFetchData()
Dim requestTable As Workbook

Set requestTable = Workbooks.Open(requestTablePath)
Run ("'" & requestTable.Name & "'" & "!fetchData")
' This is where the application starts fetching data and occasionally gets stuck
debug.print "Data retrieval complete"

End Sub

For those familiar with Thomson Reuters Datastream, I am using request tables and the pre-programmed macro within the request table file to connect and fetch data from the datastream server.
Therefore, I unfortunately do not know/understand in detail what is happening when I run:
Run ("'" & requestTable.Name & "'" & "!fetchData")

I just know that once I call it, a progress bar appears looking like this:

Which then transitions to:

If the data retrieval is successful, the progress bar disappears, output is pasted to a worksheet and the code above reaches the
debug.print "Data retrieval complete"

Statement.
If it is not successful, it just freezes with the progress bar from the second screenshot still open and running. At this point, I would want the time-out to kick-in and exit the function which called
Run ("'" & requestTable.Name & "'" & "!fetchData")

Please excuse me for being so vague in the description of the issue. I'd be glad if someone could nonetheless help me out! Always happy to share more info where I can. Cheers!


text:
Q: Launching browser on Ice Cream Sandwich I have a program that I have made for Android 1.6 and up and I have been doing tests to ensure that the program works fine with the new Ice Cream Sandwich (Android 4).
Everything on the app works fine except that when a certain task has been performed by the user it is supposed to automatically launch the android browser. However for some reason it seems to load it up in the background and keeps my app shown which is not what I want it to do.
On every other version of android when I execute the code to launch the browser the browser comes to the top of the screen therefore causing my app to be in the background which is how I wanted it to work.
Below is the code that I have to launch the browser
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(companyURL));
startActivity(intent);

The companyURL is a variable that I am using to parse the url to the browser.
Thanks for any help you can provide.
UPDATE
I have just discovered that if the browser is not currently running (i.e. not been loaded previously) when my app starts the browser it brings it to the front. However, once the browser has been previously loaded, when my app loads it up again, it loads it in the background.

A: Please try this it is working on ICS for me.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(companyURL));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

A: Typically you don't need the CATEGORY_BROWSABLE category. Try the following instead:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(companyURL));
startActivity(intent);

In fact, the documentation seems to suggest CATEGORY_BROWSABLE is intended to be used in the opposite direction (browser to your app):

Activities that can be safely invoked from a browser must support this category. For example, if the user is viewing a web page or an e-mail and clicks on a link in the text, the Intent generated execute that link will require the BROWSABLE category, so that only activities supporting this category will be considered as possible actions.

http://developer.android.com/reference/android/content/Intent.html#CATEGORY_BROWSABLE

A: Try adding FLAG_ACTIVITY_BROUGHT_TO_FRONT flag to the intent.

A: I'm using following code and its working fine with me even when browser is already running in the background.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(intent);


text:
Q: Exaggerating the peaks in a graph to a standard value I will try to explain what I need, and I hope you can provide me some info about what this "procedure" is called so I can search further on the internet.
I have a plot with "peaks" that happen on "different" levels, something like this:

And I would like to know if there exists any function that can strengthen these peaks to the same level like the peaks on the right, so it would look something like this (made in paint sorry):

I am not sure it is it called normalisation or something like this, but please can you help me find the exact definitions or functions I should search for? I am using mathplotlib.
I want to strengthen the low "y" to the level of max "y", even though my plot will change completely.
The hardest thing is that I don't know what to search for, or if this even exists, I will appreciate any help, thanks!


text:
Q: Android Swipe on List Does anyone have a simple example of a ListActivity displaying Textviews in a column and when you swipe left to right you see that row in a new view?  This would be to say edit the data for that row or show more detailed info on that row.  Please do not reference code shogun or other sites as I have googled and have not seen this answered.

A: I had the same problem and I didn't find my answer here.
I wanted to detect a swipe action in ListView item and mark it as swiped, while continue to support OnItemClick and OnItemLongClick.
Here is me solution:
1st The SwipeDetector class:
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class SwipeDetector implements View.OnTouchListener {

    public static enum Action {
        LR, // Left to Right
        RL, // Right to Left
        TB, // Top to bottom
        BT, // Bottom to Top
        None // when no action was detected
    }

    private static final String logTag = "SwipeDetector";
    private static final int MIN_DISTANCE = 100;
    private float downX, downY, upX, upY;
    private Action mSwipeDetected = Action.None;

    public boolean swipeDetected() {
        return mSwipeDetected != Action.None;
    }

    public Action getAction() {
        return mSwipeDetected;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downX = event.getX();
            downY = event.getY();
            mSwipeDetected = Action.None;
            return false; // allow other events like Click to be processed
        case MotionEvent.ACTION_UP:
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            // horizontal swipe detection
            if (Math.abs(deltaX) > MIN_DISTANCE) {
                // left or right
                if (deltaX < 0) {
                    Log.i(logTag, "Swipe Left to Right");
                    mSwipeDetected = Action.LR;
                    return false;
                }
                if (deltaX > 0) {
                    Log.i(logTag, "Swipe Right to Left");
                    mSwipeDetected = Action.RL;
                    return false;
                }
            } else if (Math.abs(deltaY) > MIN_DISTANCE) { // vertical swipe
                                                            // detection
                // top or down
                if (deltaY < 0) {
                    Log.i(logTag, "Swipe Top to Bottom");
                    mSwipeDetected = Action.TB;
                    return false;
                }
                if (deltaY > 0) {
                    Log.i(logTag, "Swipe Bottom to Top");
                    mSwipeDetected = Action.BT;
                    return false;
                }
            }
            return false;
        }
        return false;
    }
}

2nd I use the swipe detector class in the list view:
    final ListView lv = getListView();
    final SwipeDetector swipeDetector = new SwipeDetector();
    lv.setOnTouchListener(swipeDetector);
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (swipeDetector.swipeDetected()){
                    // do the onSwipe action
                } else {
                    // do the onItemClick action
                }
            }
    });
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
            if (swipeDetector.swipeDetected()){
                // do the onSwipe action
            } else {
                // do the onItemLongClick action
            }
        }
    });

This way I can support 3 actions - swipe, click, long click and I can use the ListView item info.
ADDED LATER:
Since ListView catches a scrolling action, it is sometimes hard to swipe. To fix it, I made the following change to SwipeDetector.onTouch:
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            downX = event.getX();
            downY = event.getY();
            mSwipeDetected = Action.None;
            return false; // allow other events like Click to be processed
        }
        case MotionEvent.ACTION_MOVE: {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            // horizontal swipe detection
            if (Math.abs(deltaX) > HORIZONTAL_MIN_DISTANCE) {
                // left or right
                if (deltaX < 0) {
                    Log.i(logTag, "Swipe Left to Right");
                    mSwipeDetected = Action.LR;
                    return true;
                }
                if (deltaX > 0) {
                    Log.i(logTag, "Swipe Right to Left");
                    mSwipeDetected = Action.RL;
                    return true;
                }
            } else

            // vertical swipe detection
            if (Math.abs(deltaY) > VERTICAL_MIN_DISTANCE) {
                // top or down
                if (deltaY < 0) {
                    Log.i(logTag, "Swipe Top to Bottom");
                    mSwipeDetected = Action.TB;
                    return false;
                }
                if (deltaY > 0) {
                    Log.i(logTag, "Swipe Bottom to Top");
                    mSwipeDetected = Action.BT;
                    return false;
                }
            }
            return true;
        }
    }
    return false;
}

A: here's a snippet I use for detecting swipes. You could then use a viewflipper to change the view.
  @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }
        }

        private static final int SWIPE_MIN_DISTANCE = 30;
        private static final int SWIPE_MAX_OFF_PATH = 250;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
        class MyGestureDetector extends SimpleOnGestureListener {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                    float velocityY) {
                try {
                    if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                        return false;
                    // right to left swipe
                    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                        leftFling();
                    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                            && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                        rightFling();
                    }
                } catch (Exception e) {
                    // nothing
                }
                return false;
            }

        }

A: Here is a very simplified version using the two listeners (onTouch for swipe detection, and onClickIem for item click detection)
using the isSwipe flag to stop the onClickItemListener until its confirmed that is was not a swipe
Detecting the click
taking into consideration that it is not a swipe first
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                if(!isSwipe)
                {
                    adapter.increase(arg2);
                    adapter.notifyDataSetChanged();
                }
            }
        });

Detecting the swipe
        listView.setOnTouchListener(new OnTouchListener() {
        private int action_down_x = 0;
            private int action_up_x = 0;
            private int difference = 0;
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        action_down_x = (int) event.getX();
                        isSwipe=false;  //until now
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if(!isSwipe)
                        {
                            action_up_x = (int) event.getX();
                            difference = action_down_x - action_up_x;
                            if(Math.abs(difference)>50)
                            {
                                Log.d("action","action down x: "+action_down_x);
                                Log.d("action","action up x: "+action_up_x);
                                Log.d("action","difference: "+difference);
                                //swipe left or right
                                if(difference>0){
                                    //swipe left
                                    Log.d("action","swipe left");
                                    adapter.decrease(selectedItem);
                                    adapter.notifyDataSetChanged();
                                }
                                else{
                                    //swipe right
                                    Log.d("action","swipe right");
                                }
                                isSwipe=true;
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.d("action", "ACTION_UP - ");
                        action_down_x = 0;
                        action_up_x = 0;
                        difference = 0;
                        break;
                }
                return false;   //to allow the clicklistener to work after
            }
        })

A: If you want to display some buttons with actions when an list item is swipe are a lot of libraries on the internet that have this behavior.
I implemented the library that I found on the internet and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.
Here is the github link


text: Q: data sorting effeciency Mysql Order by vs php sorting I have been loving to use php sorting except using mysql sort order by due to the performance issue. i found this time taking while php sorting is faster than the mysql order by . But is this right approach?


text:
Q: Very simple file appender logging not working Here's my web.config information:
  <configSections>

      </configSections>
      <log4net>
        <root>
                <level value="ALL" />
        </root>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
              <file value="c:\temp\log-file.txt" />
              <appendToFile value="true" />
              <rollingStyle value="Size" />
              <maxSizeRollBackups value="10" />
              <maximumFileSize value="1MB" />
              <staticLogFileName value="true" />
              <layout type="log4net.Layout.SimpleLayout" />
        </appender>
      </log4net>
...

Here's the code that initializes the logger:
protected void SendMessage()
    {
        log4net.Config.XmlConfigurator.Configure();
        ILog log = LogManager.GetLogger(typeof(Contact));
        ...
        log.Info("here we go!");
        log.Debug("debug afasf");
        ...
     }

It doesn't work, no matter what I seem to do.  I am referencing the 'log4net.dll' correctly, and by debugging the application I can see that the log object is getting initiated properly.  This is an asp.net 3.5 framework web project.  Any ideas/suggestions?
I thought originally this error may be due to a file write permission constraint, but that doesn't seem to be the case (or so I think).

A: As far as I can see you are missing an appender for root:
<root>
  <level value="ALL" />
  <appender-ref ref="RollingFileAppender" />
</root>

A: I found the answer: I needed the requirePermission="false" tag in my web.config's configuration seciton.
<configSections>

</configSections>

A: I had to call fileAppender.ActivateOptions() to get it logging

A: Is it possible to run Debug View on the webserver?
If so, you may be able to see if log4net is reporting any errors (such as an access error or a error reading the configuration file)


text:
Q: PHP cURL to Facebook insights report I am using the Facebook Marketing API with php sdk to generate my insight report.
When my report is created successfully I can download it from browser in this URL:

www.facebook.com/ads/ads_insights/export_report?report_run_id=RUN_ID&format=csv&access_token=TOKEN

$fileName = "campaign_insights.csv";
$graph_url = 'https://www.facebook.com/ads/ads_insights/export_report?report_run_id='.$report_run.'&format=csv&access_token='.$access_token;

$path = "campaign_insights.csv";

set_time_limit(0);
$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec( $ch );
var_dump($result);
curl_close($ch);
fclose($fp);

But when I try to download with php to my server with cURL or file_get_contents I can't. In cURL the response is empty.
What can I do to save the csv in my server?
Please excuse my English, I speak Spanish.
Thanks.

A: You're missing the return transfer option for curl.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Note: The return transfer option must be set to true before the file option.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $fp);

Update
After some debugging, if you look at the response of Facebook, you get the error message that the browser of curl is outdated.
So to bypass that:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
));

So the whole code would be:
$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);


text:
Q: Yaml Syntax - can not read a block mapping entry; a multiline key may not be an implicit key I have a .yaml file like this:
title: 'We'll do cool stuff'
draft: true

However, I get the following error:
Error parsing YAML: YAMLException: can not read a block mapping entry;
a multiline key may not be an implicit key at line 2, column 6:

  draft: true
       ^

How can I fix it?
Note: this setup seems different than the other questions where this same error was raised, including the following posts:

*

*Error parsing YAML

*Getting following error on serverless.yaml

*yaml syntax issues?

A: You can use a site like YAML Formatter to format and validate your yaml:

In this case, the error message and location is a bit of red-herring.
The error is actually caused by a string that was accidentally terminated because of an unescaped quote symbol within the string.  A hint for this is the syntax highlighting of 'We'll do cool stuff'.
To fix, in this case, you can just skip wrapping the string quotes and rewrite like this:
title: We'll do cool stuff
draft: true

Further Reading

*

*Do I need quotes for strings in YAML?

*How to escape double and single quotes in YAML

A: title: "We'll do cool stuff"
draft: true

I have got the exact same issue, The problem with it is, we are using a single quote' in between the string and also wrapping the string with a single quote.
I resolved it by wrapping the string with a double quote.
You can also trace the issue more by reading this


text:
Q: Круг Google Maps Android Как отрисовывать круг определенного радиуса (в метрах) вокруг текущей позиции в Google Maps API? Позиция круга, соответственно, должна обновляться при каждом обновлении позиции пользователя.

A: Используйте объекты типа Circle - документация API Google maps. Внесите необходимые изменения в параметры круга, требуемые вам:

var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);

  var mapOptions = {
      center: LatLng,
      zoom: 13,
      mapTypeId:  google.maps.MapTypeId.ROADMAP

  };
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);

 var cityCircle = new google.maps.Circle({
              strokeColor: '#FF0000',
              strokeOpacity: 0.8,
              strokeWeight: 2,
              fillColor: '#FF0000',
              fillOpacity: 0.35,
              map: map,
              center: LatLng,
              radius: 100
            });
});

Источник


text:
Q: jQuery equivalent for getElementsByClassName('name')[n]? Is there any jQuery equivalent similar to
$(document).ready(function(){
    $('para')[2].css("color","red");
});

for the code below

document.getElementsByClassName('para')[2].style.color = "red";

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

I want the CSS to be applied to the nth paragraph.

A: Try .eq if you want to access a specific jQuery element from a list of matched stuff:
$(".para").eq(2).css("color","red");
Edit: The dot notation, .para, is functionally equivalent to getElementsByClassName("para")

A: A jQuery alternative could be crafted as follows. Note that nth-of-type is not zero index based
$('p.para:nth-of-type(3)').css('color', 'red')

JSFiddle Link

A: You can use n-th child to set the style accordingly
$(document).ready(function(){
$( ".para:nth-child(2)" ).css("color","red");
});

A: I would normally use the :eq() selector for this:
$('.para:eq(2)').css('color', 'red');


text:
Q: Herança de templates com django Estou tendo um certo problema em aplicar a heraça de templates com o django. Aparentemente esta tudo certo porém meu html filho não é renderizado no template
base.html
<!doctype html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Simple MOOC - Uma simples plataforma de ensino a distância" />
    <title>Simple MOOC</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
    <link rel="stylesheet" href="{%static 'css/styles.css'%}" />

        SIMPLE MOOC

Início

Cursos

Contato

{% block content %}{% endblock %}

        Simple MOOC - Uma simples plataforma de ensino a distância

home.html
{% extends "base.html" %}

{% block content %}

                        Uma Simples Plataforma de Ensino a Distância

                        O Simple MOOC visa simplificar o ensino a distância, provendo ferramentas objetivas e de fácil uso para cursos a distância.

                        Saiba mais

Vídeo-aulas e materiais digitais

Publique suas aulas

                    O Simple MOOC tem um sistema simples e prático para que o professor disponibilize vídeo-aulas e materiais digitais como: pdf, slides, imagens ...

Fórum de Dúvidas

Interaja com seus Alunos

                    No Simple MOOC você pode ter seu próprio sistema de fórum para que seus alunos possam interagir com você e com os outros alunos

Exercícios

Crie exercícios para avaliar seus alunos

                    Você pode criar exercícios para que os alunos possam ser avaliados e todo o controle de notas e resolução dos exercícios é controlado pela plataforma, facilitando sua vida

Mural de Avisos

Envie anúncios diretamente para os alunos

                    Organize os avisos do seu curso de forma fácil e simples.

{% endblock %}

A: Tenta usar o caminho completo ne extends. Ex:
{% extends 'core/site/base.html' %}
A hierarquia deve ser template/core/site/base.html

A: Comece pelo settings.py, se esta devidamente especificados o DEBUG e
templates e o que se refere aos arquivos estáticos
 DEBUG = True # em desenvolvimento

 INSTALLED_APPS = [
  'suaAplicação',
 ]

 TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': ['templates'],# < onde encontrara os templates
             ......

    STATIC_URL = '/static/' #arquivos estáticos
    STATIC_ROOT = Path.joinpath(BASE_DIR,' staticfiles')

     ]

Okay....
Cada aplicação possui uma pasta chamada "templates" , contida nela pode haver paginas ou arquivos com pagina base.html e ola.html e index.html
base.html
{% load static %}
<!DOCTYPE html>

    <link rel="stylesheet" href="{% static 'stilos.css' %}">

{%block content %} {% endblock %}

ola.html
 {% load static %}

Ola

index.html
{% extends 'base.html' %}

 {%block content %}
    {% include 'hola.html' %}
{% endblock  %}

Dessa forma dividi o template em 3 partes a base, o conteúdo e o index.
Entre apenas 2.
base.html

{% block content %} {% endblock %}

index.html
{% extends 'base.html' %}
{% block content %}  {% endblock %}

na view apenas indique o index.html
Quando criado usando

django-admin startproject .

o espaço e depois ponto indica que criara o projeto sem subpastas, dentro do diretório que quer o projeto
.Pasta_projeto
|_projeto
|_aplicações
  |_templates
  |_static
  |_ view..admin
|_aplicação2
  |_templates
  |_static
  |_ de mais arquivos dj

qia


text:
Q: how to use click in this jquery     jQuery.noConflict();
    jQuery(document).ready(function ($) {
        var $oe_menu = $('#oe_menu');
        var $oe_menu_items = $oe_menu.children('li');
        $oe_menu_items.bind('mouseenter', function () {
            var $this = $(this);
            $this.addClass('selected');
            $this.children('div').css('z-index', '9999').stop(true, true).slideDown(300, function () {
                $(this).parent().not('.selected').children('div').hide();
            });
        }).bind('mouseleave', function () {
            $(this).children('div').hide();
            var $this = $(this);
            $this.removeClass('selected').children('div').css('z-index', '1');
        }).bind('click', function () {
            $(this).children('div').hide();
            var $this = $(this);
//          if (window.mobilecheck()) {
            $this.removeClass('selected').children('div').css('z-index', '1');
//          }
        });
        $oe_menu.bind('mouseenter', function () {
            var $this = $(this);
            $this.addClass('hovered');

        }).bind('mouseleave', function () {
            var $this = $(this);
            $this.removeClass('hovered');
            $this.children('div').hide();
        }).bind('click', function () {
//          if (window.mobilecheck()) {
            var $this = $(this);
            $this.removeClass('hovered');
            $this.children('div').hide();
//          }
        });
        if ($('.grid-categories-megamenu').parent().parent()) {
            $('.grid-categories-megamenu').parent().parent().mouseenter(function () {
                height1 = $(this).attr('id');
                var max_height_title = 0;
                $.each($('#' + height1 + ' .level1-title'), function (key, e) {
                    if (max_height_title < $(this).height()) {
                        max_height_title = $(this).height();
                    }
                });
                $('#' + height1 + ' .level1-title').height(max_height_title);
                var max_height1 = 0;
                $.each($('#' + height1 + ' .level1-megamenu'), function (key, e) {
                    if (max_height1 < $(this).height()) {
                        max_height1 = $(this).height();
                    }
                });
                $('#' + height1 + ' .level1-megamenu').height(max_height1);

            });
        }
        if ($('.list-categories-megamenu').parent().parent()) {
            $('.list-categories-megamenu').parent().parent().mouseenter(function () {
                height2 = $(this).attr('id');
                var max_height2 = 0;
                $.each($('#' + height2 + ' .level1-megamenu'), function (key, e) {
                    if (max_height2 < $(this).height()) {
                        max_height2 = $(this).height();
                    }
                });
                $('#' + height2 + ' .level1-megamenu').height(max_height2);
            });
        }
        if ($('.group-category').parent().parent().parent()) {
            $('.group-category').parent().parent().parent().mouseenter(function () {
                height3 = $(this).attr('id');
                var max_height3 = 0;
                $.each($('#' + height3 + ' .level1-megamenu'), function () {
                    if (max_height3 < $(this).height()) {
                        max_height3 = $(this).height();
                    }
                });
                $('#' + height3 + ' .level1-megamenu').height(max_height3);
            });
        }
        if ($('.products-megamenu-grid').parent().parent()) {
            $('.products-megamenu-grid').parent().parent().mouseenter(function () {
                height4 = $(this).attr('id');
                var max_height_name = 0;
                $.each($('#' + height4 + ' .product-name'), function (key, e) {
                    if (max_height_name < $(this).height()) {
                        max_height_name = $(this).height();
                    }
                });
                $('#' + height4 + ' .product-name').height(max_height_name);
            });
        }
    });

The script above is being used to control a megamenu for a magento website. In a mobile phone view i need to be able to click to open the menu then click to close it. If possible is there away i can hide the sub-categories with a plus sign? Please adivce.


text:
Q: How do I capture what a user puts in a web form and use it to calculate another number with some jquery? How do I capture what a user puts in a web form and use it to calculate another number with some jquery?
I would like to  capture a number that a user enters into a web form. When they hit "NEXT" the number will be multiplied by a constant (which depends on which service they select in another form field) and then presented on the web page using jquery I think the .change jquery function could be used for that.
thanks for any advice with this

A: I would pull the value of the text field in the click event of the "next" button... I think something like this would work:
$('#btnNext').click(function(){
     var yourConstant = 10;
     var newVal = $('#usrValue').val() * yourConstant;

     //display result
     $('#divResult').html(newVal);
});

Fiddle:
http://jsfiddle.net/QTJ62/

A:
Product:

<select id="product">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

Quantity:

<input type="number" id="quantity" />

Result:

http://jsfiddle.net/rVe6R/3/
The above does not use a next button, instead it uses the change and keyup events. Below is another version with a next button.

Product:

<select id="product">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

Quantity:

<input type="number" id="quantity" />

Result:

<button id="trigger" value="next">Next</button>

http://jsfiddle.net/rVe6R/4/


text:
Q: How do properly stream a video using partial content ranges from Azure blob storage? I have an mp4 video I've uploaded to Azure Blob Storage (blocks, storage v2). I am unable to serve the video using a <video> tag without there being a delay in playback as the video is completely downloaded from the server (with a 200 response status code).
(To make matters worse, and while not exactly relevant to my question because I think it's more of a browser issue, the video is set to loop, and it is being redownloaded with each loop.)
I would instead like to stream the video using partial content ranges so that playback begins immediately.
I've tried sourcing the video directly, providing the absolute URI to the <video> tag src attribute; and I've also tried serving the video via an ASP .NET Core 3.1 controller method, returning a FileStreamResult and setting the enableRangeProcessing parameter to true. Here is that code:
public async Task<IActionResult> GetVideo(string videoUrl)
{
    var httpClient = new HttpClient();
    var stream = await httpClient.GetStreamAsync(videoUrl);
    return File(stream, new MediaTypeHeaderValue("video/mp4").MediaType, true);
}

It seems regardless of what I try, I cannot get a range response with a 206 status code. I've seen suggestions about using Azure Media Services, but it seems like overkill and that this should be something that's just supported without having to incorporate yet another service.
Any help/suggestions would be greatly appreciated - thanks!

A: According to my research, if you set enableRangeProcessing parameter to true, we will get range response。 For more details, please refer to the issue.
My test code
public async Task<IActionResult> Video() {
            var s = Request.Headers;
            var memory = new MemoryStream();

            BlobServiceClient blobServiceClient = new BlobServiceClient("DefaultEndpointsProtocol=https;AccountName=blobstorage0516;AccountKey=eGier5YJBzr5z3xgOJUb+snTGDKhwPBJRFqb2nL5lcacmKZXHgY+LjmYapIHL7Csvgx75NwiOZE7kYLJfLqWBg==;EndpointSuffix=core.windows.net");
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("test");
            var blob =containerClient.GetBlobClient("test.mp4");
            StorageTransferOptions options = new StorageTransferOptions();
            options.InitialTransferLength = 1024 * 1024;
            options.MaximumConcurrency = 20;
            options.MaximumTransferLength = 4 * 1024 * 1024;
            await blob.DownloadToAsync(memory,null, options);
            memory.Position = 0;
            return File(memory, new MediaTypeHeaderValue("video/mp4").MediaType, true); //enableRangeProcessing = true

        }


text:
Q: Can't insert row using JSON Can someone help me! I cant create a row using JSON.
/**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewServiceActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            // getting updated data from EditTexts
            String ticketno = txtTicketNo.getText().toString();
            String status = txtStatus.getText().toString();
            String bracode = txtBrCode.getText().toString();
            String compid = txtcomId.getText().toString();
            String compname = txtcomName.getText().toString();
            String comcity = txtcomAddress.getText().toString();
            String repby= txtRepBy.getText().toString();
            String repon = txtRepOn.getText().toString();
            String sect = txtSection.getText().toString();
            String dept = txtDept.getText().toString();
            String problem = txtProblem.getText().toString();
            String creby = txtCreatedBy.getText().toString();
            String dtstart = dtStart.getText().toString();
            String dtstop = dtStop.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("report_no", ticketno));
            params.add(new BasicNameValuePair("status", status));
            params.add(new BasicNameValuePair("branch_code", bracode));
            params.add(new BasicNameValuePair("company_id", compid));
            params.add(new BasicNameValuePair("company_name", compname));
            params.add(new BasicNameValuePair("city", comcity));
            params.add(new BasicNameValuePair("reported_by", repby));
            params.add(new BasicNameValuePair("reported_on", repon));
            params.add(new BasicNameValuePair("section", sect));
            params.add(new BasicNameValuePair("department", dept));
            params.add(new BasicNameValuePair("problem", problem));
            params.add(new BasicNameValuePair("created_by", creby));
            params.add(new BasicNameValuePair("dt_start", dtstart));
            params.add(new BasicNameValuePair("dt_finish", dtstop));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

Here is my java class for inserting a row in the database.
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['report_no']) && isset($_POST['status']) &&         isset($_POST['branch_code']) && isset($_POST['company_id']) && isset($_POST['company_name']) && isset($_POST['city']) && isset($_POST['reported_by']) && isset($_POST['reported_on']) && isset($_POST['section']) && isset($_POST['department']) && isset($_POST['problem']) && isset($_POST['created_by']) && isset($_POST['dt_start']) && isset($_POST['dt_finish'])) {

$report_no = $_POST['report_no'];
$status = $_POST['status'];
$branch_code = $_POST['branch_code'];
$company_id = $_POST['company_id'];
$company_name = $_POST['company_name'];
$city = $_POST['city'];
$reported_by = $_POST['reported_by'];
$reported_on = $_POST['reported_on'];
$section = $_POST['section'];
$department = $_POST['department'];
$problem = $_POST['problem'];
$created_by = $_POST['created_by'];
$dt_start = $_POST['dt_start'];
$dt_finish = $_POST['dt_finish'];

// include db connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO report(report_no, status, branch_code, company_id, company_name, city, reported_by, reported_on, section, department, problem, created_by, datetime_start, datetime_finish) VALUES($report_no, '$status', '$branch_code', '$company_id', '$company_name', '$city', '$reported_by', '$reported_on', $section, $department, '$problem', '$created_by', '$dt_start', '$dt_finish')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Report successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
    // required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

And here is my script. When I execute the app the logcat says Required field is missing. Help me please.
EDIT: I now see the problem but I don't have the solution yet. The JSON that was sent to the edittexts in the class is shown with data when it run in my device but when I was going to use the data in the edittexts, it says it was null.


text:
Q: Can we approximate this function by a polynomial? For the more mathematically minded,
we have $x \in \mathbb{R}^2$ and the function $h(x)$ defined as:
$h(x)=\alpha_1x_1^2+\alpha_2x_2^2+\alpha_3x_1+\alpha_4x_2+\alpha_5x_1x_2+\alpha_6$
and the vector of alpha's is known and further guaranteed to be such that $h(x)$ is a general
 elliptic paraboloid (i.e. a convex function).
Now, define $g(x)=(h(x))^+$  where $(z)^+$ is the positive part of $z\in\mathbb{R}$.
The questions follows:

*

*Is there a way to globally approximate $g(x)$ by a polynomial ? If so what it is?

*Can this approach (the answer to the previous sub-question) be extended to $x\in\mathbb{R}^p$ with $p$ moderatly large ?

*Would the problem be any easier if we were to assume $\alpha_5=0$ ?

Following Whuber's comment: is it possible to find a polynomial approximation to $g(x)$ that would be better than $h(x)$? in the event that many approximations solution for this problem exist, what are they ?
I can obviously solve $argmin.\int_{\mathbb{R}^2}(g(x)-\hat{g}(x))^2 dx$. I'm wondering if there are explicit, known solutions to this problem (i.e. polynomial series for example of which i know close to nothing).

A: The $L^2$ distance between $g$ and a polynomial approximation will be finite if and only if the polynomial approximation behaves asymptotically like $g$, which means it behaves asymptotically like $h$, which implies it must equal $h$.  Therefore $h$ is the unique $L^2$ approximator.
Thus:
(1) Yes; the global approximator to $g$ is $h$.
(2) Yes; the same reasoning holds for all finite $p$.
(3) No; the value of $\alpha_5$ makes no difference.
Follow-up question (i): No, you cannot do better than $h$.
Follow-up question (ii) [how many approximations]: Not applicable due to the answer to (i).
You can get a considerably better set of answers if you're willing to limit the domain of $g$ to a compact [measurable] subset.

A: Note that $h(x)$ itself is a polynomial in $x_1$ and $x_2$ and $g(x)$ is what I would call a truncated polynomial.
The region where $h(x)$ is negative, $g(x)$ will be zero. You can approximate this region where $h(x)$ is flat by a non-constant polynomial (non-constant because you also need to approximate the region where $h(x) > 0$) but this will always be a 'wiggly' approximation (at least for a finite number of terms in the approximating polynomial).
It's not clear to me what you want to achieve, $g(x)$ actually has a quite simple analytical form and maybe for your problem you just have to consider the two regions $h(x) < 0$ and $h(x) \ge 0$ separately.


text:
Q: What do I have to do to display the largest and the smallest number using a loop? I don't  have  any idea how to display the largest and smallest number after the user enter -1.
Note:  I also have to display the sum of all of this number and the average of this sum.
Here's my code so far:
public static void main(String[] args) {
    // store
    int cnt = 0;
    int acumulator = 0;
    int larger = 0;
    int smaller = 0;
    int number;
    // inputs
    System.out.println("enter the number all the number");
    Scanner kb = new Scanner(System.in);
    number = kb.nextInt();
    // loop
    while (number != -1) {
        acumulator += number;
        number = kb.nextInt();
        cnt++;//
    }
    double average = (acumulator / cnt);
    System.out.println(" The total of your number is=" + acumulator);
    System.out.println(" The average of your number is=" + average);
}

A: Seems like schoolwork, but what you could do is making a var and checking in your while if the input number is higher or lower then the saved var.
if(input > max)
  max = input;

And
if(input < min)
  min = input;

A: I would make the following changes:

*

*use a for loop instead of a while loop (you need intialization, condition and iteration)

*use the JDK's API more - Math.min() and Math.max()

*spell "accumulator" correctly

*remove all variables you are not using (cnt)

Try this:
public static void main(String[] args) {
    int accumulator = 0;
    int largest = Integer.MIN_VALUE;
    int smallest = Integer.MAX_VALUE;
    int count = 0;
    // inputs
    System.out.println("enter a number (-1 to end)");
    Scanner kb = new Scanner(System.in);
    for(int number = kb.nextInt(); number != -1; number = kb.nextInt()) {
        count++;
        accumulator += number;
        largest = number > largest ? number : largest;
        smallest = number < smallest ? number : smallest;
    }
    double average = (accumulator / count);
    System.out.println(" The total of your numbers is=" + accumulator);
    System.out.println(" The average of your numbers is=" + average);
    System.out.println(" The largest of your numbers is=" + largest);
    System.out.println(" The smallest of your numbers is=" + smallest);
}

FYI: Math.min/max could be used instead of the ternary statements, but the above is the simplest java that will achieve the result.

A: Basically you need to check each all numbers with each other.Lets say we have numbers 1,2 and 3
here is the code:
public static void main(String[] args){
    int one=1;
    int two=2;
    int three=3;
    if(three>one){
     if(three>two){
       System.out.println("three is biggest");
     }
   }
   if(two>one){
    if(two>three){

   }
}

etc etc.
I think you got idea

A: You need to use an "if" statement.


text:
Q: R parallel job hangs I am running the snow-test.R script as written on the site:
https://hpcf.umbc.edu/other-packages/how-to-run-r-programs-on-maya/
The script is run on a cluster using SLURM with the command:
mpirun -np 1 R CMD BATCH --no-save --no-restore snow-test.R out.dat

The R version is 3.5.1. Although the script runs and displays the
result, it hangs at the end. Thus, I need to kill the process
manually from the SLURM queue with scancel command.
Also, when I change the R version to 3.4.4 using the same scripts,
R cannot run the script, it complains with the message:
Error in Rmpi::mpi.comm.spawn(slave = mpitask, slavearg = args, nslaves = count,  :
  MPI_ERR_SPAWN: could not spawn processes
Calls: makeMPIcluster -> <Anonymous> -> .Call
Execution halted

Thanks.


text:
Q: Using PHP CURL to post data to external URL and redirect Here's my scenario.
I have an external URL : https://staging.mead.com.ph/login/sso
Now I have to post data to that URL, assuming like the one below :

*

*Name

*Type

*Mobile Num

Now, after posting I have to be redirected to the
[redirect_url] inside curl_getinfo(). [redirect_url] has the following value : https://staging.mead.com.ph/login/key=abcde
HOWEVER,after echoing the result of the curl_exec, it says "Object Moved Here" and "HERE" redirects to https://myservername/login/key=abcde
instead of the https://staging.mead.com.ph/login/key=abcde
Here's my code :
$url    =  "https://staging.mead.com.ph/login/key=abcde";
$token  = "token1234";
$params = array(
    "Name" => "Ana",
    "Type" => "A",
    "Mobilenum" => "0919123456"
    );
 foreach($params as $key => $value) {
    $fields .= $key . '=' . $value . '&';
 }
 rtrim($fields, '&');
 $post = curl_init();

 curl_setopt($post, CURLOPT_URL, $url);
 curl_setopt($post, CURLOPT_POST, count($params));
 curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
 curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($post, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($post, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);

 curl_setopt($post, CURLOPT_PROXYUSERPWD, PROXY_AUTH);
 curl_setopt($post, CURLOPT_PROXY, PROXY_URL);
 curl_setopt($post, CURLOPT_PROXYPORT, PROXY_PORT);
 curl_setopt($post, CURLOPT_TIMEOUT,6);

 $result = curl_exec($post);

 echo $result;

 curl_close($post);

What could be wrong? Thanks in advance.

A: UPDATE
Is there a reason for these:
 curl_setopt($post, CURLOPT_PROXYUSERPWD, PROXY_AUTH);
 curl_setopt($post, CURLOPT_PROXY, PROXY_URL);
 curl_setopt($post, CURLOPT_PROXYPORT, PROXY_PORT);

If so, you need to use the correct parameters, otherwise delete them.
------- End of Update ---------
There are many things that could be going wrong.  There is a way to troubleshoot.
add these options:
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Then get the Headers, response, and stats
$requestHeaderText = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$responseHeaderText = substr($data,0,$skip);
$response = substr($data,$skip);
$stats = curl_getinfo($ch);

In the redirect header you will see a "location", this is where you are being redirected.
You may want to try curl_setopt($post, CURLOPT_POSTFIELDS, $params);
this will change the requestContent-Typetomultipart/form-data`
Often cookies are set on the redirect page.  Look for SET-COOKIE in the response Headers.  If there are cookies then you need to use CURLOPT_COOKIEJAR
Also look for javascript in the response.  Sometimes the redirect is done using javascript while performing security checks etc.
You may want to change curl_setopt($post, CURLOPT_FOLLOWLOCATION, true); to false.  Then you will only get the headers and stats for the first request.


text:
Q: Deriving solution $x$ from system of linear equations ($Ax=b$) for variable dimension $n$ I'm trying to find the solution $x=(x_1,\ldots,x_n)$ for the following system of linear equations:
$$
\begin{aligned}
(a_1+a_2)x_1-a_2x_2&=a_1\\
-a_{2j-1}x_{j-1}+(a_{2j-1}+a_{2j})x_{j}-a_{2j}x_{j+1}&=0\\
-a_{2n-1}x_{n-1}+(a_{2n-1}+a_{2n})x_{n}&=0
\end{aligned}
$$
Clearly, I can rewrite this into
$$
\begin{pmatrix}
(a_1+a_2) & -a_2      & \\
-a_3      & (a_3+a_4) & -a_4 \\
& & \ddots \\
& &-a_{2n-3}      & (a_{2n-3}+a_{2n-2}) & -a_{2n-2} \\
& & &-a_{2n-1}      & (a_{2n-1}+a_{2n})
\end{pmatrix}
\cdot
\begin{pmatrix}
x_1 \\
 \\
\vdots \\
 \\
x_n \\
\end{pmatrix}
=
\begin{pmatrix}
a_1 \\
0 \\
\vdots \\
 \\
0 \\
\end{pmatrix}
$$
Actually, I'm mostly interested in the value $x_1$. I was able to solve the system using SageMath for some values $n\in\mathbb{N}$ and from observation I deduced the formula
$$x_1=\frac{\sum_{j=0}^{n-1}\big(\prod_{k=1}^{n-j}a_{2k-1}\big)\big(\prod_{l=n+1-j}^na_{2l}\big)}{\sum_{j=0}^n\big(\prod_{k=1}^{n-j}a_{2k-1}\big)\big(\prod_{l=n+1-j}^na_{2l}\big)}$$
However, I would like to verify this formula for sure, even though it seems right for some values of $n\in\mathbb{N}$. Is there a good way how I could verify this?
Any hint or help is appreciated! Thank you in advance!

A: Numerical experiment
Writing in Wolfram Mathematica 13.0:
a[x_] := ToExpression[SubscriptBox["a", ToString[x]]]
nmax = 40;
Timing[
 num1 = RecurrenceTable[{f[n] == (a[2 n] + a[2 n - 1]) f[n - 1] -
                                  a[2 n - 1] a[2 n - 2] f[n - 2],
                         f[1] == a[1],
                         f[2] == a[1] (a[3] + a[4])},
                         f[n], {n, nmax}];
 den1 = RecurrenceTable[{f[n] == (a[2 n] + a[2 n - 1]) f[n - 1] -
                                  a[2 n - 1] a[2 n - 2] f[n - 2],
                         f[1] == a[1] + a[2],
                         f[2] == (a[1] + a[2]) (a[3] + a[4]) - a[2] a[3]},
                         f[n], {n, nmax}];
]

226.406 s

a[x_] := ToExpression[SubscriptBox["a", ToString[x]]]
nmax = 40;
Timing[
 num2 = Table[A = SparseArray[{{i_, j_} /; j == i - 1 -> -a[2 i - 1],
                               {i_, j_} /; j == i -> a[2 i] + a[2 i - 1],
                               {i_, j_} /; j == i + 1 -> -a[2 i]}, {n, n}];
              A[[All, 1]] = SparseArray[{{i_} /; i == 1 -> a[1]}, n];
              Det[A], {n, nmax}];
 den2 = Table[A = SparseArray[{{i_, j_} /; j == i - 1 -> -a[2 i - 1],
                               {i_, j_} /; j == i -> a[2 i] + a[2 i - 1],
                               {i_, j_} /; j == i + 1 -> -a[2 i]}, {n, n}];
              Det[A], {n, nmax}];
]

11.9063 s

a[x_] := ToExpression[SubscriptBox["a", ToString[x]]]
nmax = 40;
Timing[
 num3 = Table[Sum[Product[a[2 j - 1], {j, 1, n - i}]
                  Product[a[2 j], {j, n - i + 1, n}],
                 {i, 0, n - 1}], {n, nmax}];
 den3 = Table[Sum[Product[a[2 j - 1], {j, 1, n - i}]
                  Product[a[2 j], {j, n - i + 1, n}],
                 {i, 0, n}], {n, nmax}];
]

0.546875 s

Simplify[num1 == num2 == num3 && den1 == den2 == den3]

True

it's deduced that the three formulations considered lead to the same result for every n from 1 to 40, but by comparing the execution times it can also be deduced that they aren't equally efficient.
Therefore, assuming the Wikipedia recurrence relation correct, writing:
a[x_] := ToExpression[SubscriptBox["a", ToString[x]]]
nmax = 100;

f[n_] := Sum[Product[a[2 j - 1], {j, 1, n - i}]
             Product[a[2 j], {j, n - i + 1, n}],
             {i, 0, n - 1}];
Norm[
 FullSimplify[
  Join[{f[1] - a[1]},
       {f[2] - a[1] (a[3] + a[4])},
       Table[f[n] - (a[2 n] + a[2 n - 1]) f[n - 1] +
                     a[2 n - 1] a[2 n - 2] f[n - 2],
             {n, 3, nmax}]]]]

f[n_] := Sum[Product[a[2 j - 1], {j, 1, n - i}]
             Product[a[2 j], {j, n - i + 1, n}],
             {i, 0, n}];
Norm[
 FullSimplify[
  Join[{f[1] - a[1] - a[2]},
       {f[2] - (a[1] + a[2]) (a[3] + a[4]) + a[2] a[3]},
       Table[f[n] - (a[2 n] + a[2 n - 1]) f[n - 1] +
                     a[2 n - 1] a[2 n - 2] f[n - 2],
             {n, 3, nmax}]]]]

0

0

we can see that your formulation verifies the recurrence relation for every n from 1 to 100 (we could also go further but I don't see the reason). Of course we haven't proved anything, but now it's evident that the calculations coincide.
Up to now everything has been focused on the computation of x1, but with a slight generalization of these formulations, all n solutions can be obtained. Checks from 1 to 40 are as follows:
a[x_] := ToExpression[SubscriptBox["a", ToString[x]]]
nmax = 40;
Timing[
 Monitor[
  Norm[
   Table[
    A = SparseArray[{{i_, j_} /; j == i - 1 -> -a[2 i - 1],
                     {i_, j_} /; j == i -> a[2 i] + a[2 i - 1],
                     {i_, j_} /; j == i + 1 -> -a[2 i]}, {n, n}];
    B = SparseArray[{{i_} /; i == 1 -> a[1]}, n];
    tab = Table[Sum[Product[a[2 k - 1], {k, 1, n - j}]
                    Product[a[2 k], {k, n - j + 1, n}],
                   {j, 0, n - i}], {i, 0, n}];
    X = tab[[2 ;; n + 1]]/tab[[1]];
    Norm[FullSimplify[A.X - B]], {n, nmax}]],
  Row[{ProgressIndicator[n, {1, nmax}], n}, " "]]]

{17.7656, 0}


text:
Q: HTML beginner with Javascript; code not running I'm trying to run this code that I made in HTML involving javascript, but it's not running. Can someone point out what's wrong?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function math() {
var a = 1;
var b = 0;
var c = 0;
var sum = 0;
for (var a = 1; a <10; a++) {
    sum = a+c;
    c = a+b;
    a = b;
}
alert(sum);
}
</script>
</head>

<body>
<script type="text/javascript">
    math();
</script>
</body>
</html>

A: Your code is running but you have created an infinite loop.
You always set a = b inside your for loop. Since b is equal to zero, the loop will never terminate because a is always less than 10.

A: It's an infinite loop.
You are iterating over a, but you are changing it to 0 in the for loop so the script never terminates.

A: Your for loop is an infinite loop. You never assign b to any value but 0. The final step in each loop, therefore, is assigning a to 0. a will never reach 10 and the loop will never break.

A: Your will get a result of an infinite loop
You can't loop over a when you have set a equal to 0 inside your for loop ( a=b) and you know that variable b is equal to zero


text:
Q: How can I import a json file in a JavaScript file? I have two files data.json and index.js.
data.json looks like this:
{
      "stacy": {
           "age": 24,
           "name": "Stacy",
           "properties": [ "crazy", "funny", "straight" ]
      },
      "john": {
           "age": 41,
           "name": "John",
           "properties": [ "experienced", "direct", "straight" ]
      },
}

How can I import data.json into index.js?
I thought about something like this: import * as persons from data.json;

A: You will find all of your JSON data in the data variable.
By using fetch API you can load JSON data. Code below:
fetch('data.json')
  .then(res => {
    return res.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(err => console(err));

try to write the exact file location.