text:
Q: ¿Cómo recibo los datos de un select multiple en PHP? Tengo un select multiple que se llena dependiendo de los datos de otros select, el caso es que quiero mandarlo por medio de ajax a un archivo php para hacer una comunicación con la base de datos, el caso es que yo para tomar los datos del formulario utilizo $("#").serialize() entonces, no sé como recibir los datos por php, sí alguien me puede ayudar, se lo agradezco.
JQuery Ajax
function enviarRegistro(){
        if(validarCampos()){
            var datos = $("#formRegistro").serialize();
            $("#pageLoader").fadeIn("fast");
            if($("#checkinput").prop("checked")){
                $.ajax({
                    data: datos,
                    url: '/Jomar/users_control/controller/ControlAsisController.php?action=guardarHasta',
                    type: 'post',
                    success: function (response){
                        var html;
                        if(response.trim() != "1"){
                            html = "
 No se han podido insertar "+ response.trim() +" registros
";
                            $("#respuesta").addClass("alert-danger");
                            $("#respuesta").html(html);
                            $("#pageLoader").fadeOut("fast");
                            $("#respuesta").fadeIn("slow");
                            setTimeout(function(){
                                $("#respuesta").fadeOut(2000, function() {
                                    $("#respuesta").html("");
                                    $("#respuesta").removeClass("alert-danger");
                                    });
                            }, 2000);
                        }else{
                            $("#respuesta").addClass("alert-success");
                            html = "
 Se ha insertado correctamente
";
                            $("#respuesta").html(html);
                            $("#pageLoader").fadeOut("fast");
                            $("#respuesta").fadeIn("slow");
                            $("#empleado").val(0);
                            $("#nota").val("");
                            llenarEmpleados();
                            $("#errores").fadeOut("slow");
                            setTimeout(function(){
                                $("#respuesta").removeClass("alert-success");
                                $("#respuesta").fadeOut(2000, function() {
                                    $("#respuesta").html("");
                                    });
                            }, 2000);
                        }
                    }
                });

HTML
<select class="selectpicker" multiple data-size="6" data-live-search="true" id="empleado" name="empleado" disabled="disabled">
                        <option value="0" disabled>Seleccionar empleado</option>
                    </select>

A: Hay que tener en cuenta que la función serialize() de JQuery te devuelve un string que luce similar a una cadena pasada por get en la URL. Ejemplo:
"frutas=platano&frutas=fresa&frutas=manzana"

Esta cadena no es un JSON por lo que el type que has definido en la llamada AJAX no es el adecuado. Además de que JSON no se trata de un formato que nos sirva en nuestro caso, ya que nosotros tenemos múltiples campos como la misma key y este no nos lo permite tener.
Es por ello por lo que te propongo usar la función serializeArray() en vez de serialize().
Ejemplo de conversión del select multiple a array:

<form>
  <select name="frutas[]" multiple="multiple">
    <option selected="selected">platano</option>
    <option>fresa</option>
    <option selected="selected">manzana</option>
  </select>

  <input name="verdura" type="text" value="lechuga">
</form>

Ejemplo de llamada envío AJAX usando el array conseguido mediante serializeArray()
function enviarRegistro() {
  var datos = $("#formRegistro").serializeArray();
  console.log(datos);
  $.ajax({
    data: datos,
    url: '/Jomar/users_control/controller/ControlAsisController.php?action=guardarHasta',
    type: 'post',
    success: function (response){
      //Lo que quieras hacer tras recuperar la respuesta del servidor
    }
  });
}

Luego desde PHP lo único que tendrías que hacer es recuperar de $_POST los datos enviados:
$frutas = $_POST['frutas'];

print_r($frutas);

A: Para recoger los multiples valores de un select necesitas enviar el array de los datos seleccionados usando el name del campo del formulario.
 <select class="selectpicker" multiple data-size="6" data-live-search="true" id="empleado" name="empleado[]" disabled="disabled">
    <option value="0" disabled>Seleccionar empleado</option>
 </select>

Simplemente el name del campo será empleado[].
var values = $(select).serialize();
console.log (values);


text:
Q: perl regex to extract table names from stored procedure I need to extract the list of table names from the stored procedure for example the SP may contain one or more SQLs.
select
t.ticket, t.subsid, null, null
from
    Trans t
where
    subsid = @subsid

select *
from
   Trans t, Cpty c, Book b
where
t.ticket            =  c.ticket

Now i need to extract Trans , Cpty and Book as table names. The sqls are in multi line how to extract theses information in perl regex.
Please help.

A: use strict; use warnings;
open my $f, "<", 'input' or die("$!");
my %tables;
while (<$f>) {
    next if !/\bfrom\b/;
    while (<$f>) {
        $tables{$_} = 1 for map { (split)[0] } split(/,/);
        last if !/,\s*$/
    }
}
close $f;
print join(",", keys %tables), "\n";

Produces:
Book,Cpty,Trans

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bash: variable insertion into curl call not working I have a very simple bash script with three commands.
The first command strips the first word off of the last git commit, the second command attempts to make a POST call to an api endpoint, with that same variable as part of the call, and the third command just prints that variable, to ensure it was working properly. See the code below
SOMETHING=$(git log -1 --pretty=%B | head -n1 | sed -e 's/\s.*$//' | cut -d ' ' -f1)
curl -X POST \
  http://www.someurl.com/ \
  -H 'Cache-Control: no-cache' \
  -d '{"item":"$SOMETHING"}'
echo "variable was $SOMETHING"

When I run that bash script, I get a response from the service saying that "item was not set properly" in XML, however it does correctly echo the correct variable. So I know that first line is working. If I copy that curl command and paste it into bash, replacing $SOMETHING with the actual value, it works fine.

A: Single quotes do not expand the $variables inside them.
Try
'{"item":"'"$SOMETHING"'"}'

instead. Brief explanation:

*

*'{"item":"' is a string delimited by single quotes that contains double quotes

*"$SOMETHING" is a string delimited by double quotes, that expands the variable $SOMETHING

*'"}' is again a ''-delimited string that contains double quotes

*Simply writing those strings in a row without gaps is string concatenation

In this way, you get your variable expansion, but don't have to insert any backslashes to escape the double quotes.


text:
Q: Smartadmin, Datatables subelements are not binded (AngularJS) I bought the smartadmin from (wrapbootstrap.com/theme/smartadmin-responsive-webapp-WB0573SK0) and use the version 1.5 angular.
I extracted the datatable (wrapbootstrap.com/preview/WB0573SK0) and put it in my own project. So far it works except when I click on the row and the subelement opens, the data there is not binded.
When I check the scope with the Angular Chrome Plugin I can see on your version as well as in my project that the scope has the actual data but somehow the ng-bing is not working. (As you can see on the screenshot)
My Project - empty Subelement
http://s14.directupload.net/images/141120/f9xzm3ab.png
What its supposed to be like
http://fs1.directupload.net/images/141120/2pp3icxa.png
The View:

                      Project Title:

                      Deadline:

                      Extra info:
                      And any further details here (images etc)...

                      Comments:

                      Action:

Controller:
  $scope.projects = [
{
  "name": "name",
  "est": "est",
  "contacts": "contacts",
  "status": "status",
  "target-actual": "target-actual",
  "actual": "actual",
  "tracker": "tracker",
  "starts": "01-21-2013",
  "ends": "03-15-2015",
  "comments": "comments",
  "action": "actions"
}];

$scope.tableOptions = {
"data": $scope.projects,
"iDisplayLength": 15,
"columns": [
  {
    "class": 'details-control',
    "orderable": false,
    "data": null,
    "defaultContent": ''
  },
  {"data": "name"},
  {"data": "est"},
  {"data": "contacts"},
  {"data": "status"},
  {"data": "target-actual"},
  {"data": "starts"},
  {"data": "ends"},
  {"data": "tracker"}
],
"order": [[1, 'asc']]};

directive: (on click handler)
if (attributes.tableOptions) {
    console.log("extending angular tableOptions");
    options = angular.extend(options, scope.tableOptions)
  }

  var _dataTable;

  var childFormat = element.find('.smart-datatable-child-format');
  if (childFormat.length) {
    var childFormatTemplate = childFormat.remove().html();
    element.on('click', childFormat.data('childControl'), function () {
      var tr = $(this).closest('tr');

      var row = _dataTable.row(tr);
      if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
      }
      else {
        // Open this row
        var childScope = scope.$new();
        childScope.d = row.data();
        var html = $compile(childFormatTemplate)(childScope);
        row.child(html).show();
        tr.addClass('shown');
      }
    })
  }

  _dataTable = element.DataTable(options);

Any help is much apreciated!

A: I had to apply the scope in the directive. $compile was not enough.
childScope.$apply(function() {
          childScope.d = row.data();
        });


text:
Q: Arithmetic and clojure functions on core.logic lvars Two related questions in one:
Can Clojure's core.logic module perform arithmetic, logical comparison, etc, like ordinary Prolog?  I am envisioning something like the following:
(defrel points person n)
(fact :bob 2)
(fact :charlie 3)
(run* [q] (fresh [x y]
   (points :bob x)
   (points :charlie y)
   (< x y)
   (== q (+ x y))))

=> (5)

In this example, neither the logical comparison (< x y) nor the attempted binding of q to (+ x y) works.  I suppose that this is because I'm working with LVars, not integers at this point, and I can't make these comparisons because the symbols aren't yet bound.  But it works in prolog:
points(bob, 2).
points(charlie, 3).
?- points(bob, X), points(charlie, Y), Result is X + Y.

=> Result = 5.

In a similar vein, can I somehow use Clojure functions (which return booleans or other "truthy" values) as logic predicates?  In other words, to use functions to tell Minikanren which terms unify or not.  Something along the lines of:
(defmagic startswithhi-o [v]
  (.startsWith v "hi"))
(defrel person n)
(fact person "bob")
(fact person "hillary")
(run* [q]
   (fresh [n]
     (person n)
     (startswithhi-o n)
     (== q n)))

=> ("hillary")

If I try things like this I get errors also complaining that the LVars aren't bound.  Is there a way to do this?
Lastly if anyone has read this far, I might as well ask: are there plans to incorporate probabilistic logic into core.logic, along the lines of:
http://dtai.cs.kuleuven.be/problog/  ?
I'm not holding my breath but it would be awesome!

A: I believe you have to "project" (nonrel/project) a logic variable to its binding before you can apply a function to it:
(defrel points person n)
(fact points :bob 2)
(fact points :charlie 3)
(run* [q]
  (exist [x y]
    (points :bob x)
    (points :charlie y)
    (project [x y]
      (== true (< x y))
      (== q (+ x y)))))

Note that exist substitutes for fresh in the original snippet and the additional argument for  the fact declarations.

A: Non-relational arithmetic is possible via project.
(run 1 [q]
   (fresh [x y]
        (== x 1)
        (== y 2)
        (project [x y]
                 (== q (+ x y)))))
(3)

I believe the Prolog example given is also non-relational.
The second half of your question can also be solved via project, but you must be careful that you always input a ground value.
(defn startwith [x]
    (project [x]
         (== true (.startsWith x "hi"))))

PS: Hold your breath for Constraint Logic Programming to come to core.logic!


text:
Q: finding user with admin role as true I am working on an e-commerce project and I only want to allow users with admin as true to be able to create and update products in the products collection(MongoDB database), but somehow I am getting it wrong because when I use a user with admin true token as a bearer token in authorization I receive the catch error
this is my user model code
import mongoose from "mongoose";
import bcrypt from 'bcrypt'
import dotenv from 'dotenv'
dotenv.config()

const userSchema = new mongoose.Schema({
    username:{
        required:true,
        type:String
    },

    email:{
         type:String,
         unique:true,
         required:true,
    },
    password:{
        type:String,
        required:String
    },
    profilePic:{
        type:String,
        required:true,
        default:'https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg'
    },
    admin:{
        type:Boolean,
        required:true,
        default:false
    }

}, {
    timestamps: true
});

my Middleware code  for the protection for product creation
import jwt from 'jsonwebtoken'
import asyncHandler from 'express-async-handler'
import userModel from '../models/user.model.js'

export const productCreationProtection = asyncHandler(async(req, res, next) => {

    let authorizationToken;

    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
        try {
            authorizationToken = req.headers.authorization.split(" ")[1]

            // decode user id
            const decode = jwt.verify(authorizationToken, process.env.PRIVATE_KEY)
            // Find the userModel and we use select to exclude password for find
            req.user = await userModel.findOne(decode.id).select('admin')
            next();

        } catch (error) {
            res.sendStatus(401)
            throw new Error("You're not authorized to performe this function")
        }

    }

    if(!authorizationToken){
        res.sendStatus(401)
        throw new Error("Not Authourized to performe this action")
    }

});

A: The findOne method takes an object as parameter but you are passing a string. If you are trying to find a user with given ID, then try refactoring your code as shown below:
req.user = await userModel.findOne({ _id: decode.id }).select('admin')

// Check if admin field is true
if (!req.user.admin) {
  return "Forbidden"
}
next()

This will return document where _id is equal to decode.id. Do replace _id if you are querying based on any other field.

Alternatively, you can also add admin field in query itself:
const user = await userModel.findOne({ _id: decode.id, admin: true })
if (!user) {
  // User with given ID not found or is not an admin
  return "Forbidden"
}
next();


text:
Q: Merge Columns without deleting or affecting the rows Im seeking some experienced advice, as I have been working on a little project to automate how we gather data in my office using Google Sheets(Please note that I can't use add-ons).
I'm encountering difficulties in finding a way to merge columns that have the same name, but without deleting/merging the row(because im pulling stats for the different tasks employees handle).
In the example you can see that column A has names that repeat because each individual completes one or more tasks, so my goal would be to find a way to automatically merge the repeating names in column A without affecting the rest of the columns.
I believe it is important to know that the table auto-populates as im currently using a filter function, because I paste all my data in the excel and it filters only my agents names.
Here is the formula that im using in c26:
=FILTER(A3:G22,ARRAYFORMULA(ISNUMBER(MATCH(A3:A22,{"Mary";"Jason";"Ana";"Jen";"Ben";"Helen";"Dan";"Richard";"Breg"},0))))

Please tell me that there is a way to do this!
Here is a link to the example Doc That I made
https://docs.google.com/spreadsheets/d/1RsCeHfzzbRsUDnj6UmmCdfzjryp-2xW09UTCx_qfIpA/edit?usp=sharing

A: Here you can do it, but can't merge by formula:
= ARRAYFORMULA (
    ifna (
      vlookup (
        ifna (
          sort (
            { row(A4:A22) *
              len ( vlookup ( A4:A22,
                  {"Ana";"Jen";"Ben";"Helen";"Dan";"Richard";"Breg"},1,0)
              )^0}
            ,1,true
          ),""
        )
        , { row(A4:A22),
            left(A4:A22, 1000 *
                transpose (
                   split (join("","1," & rept("0,",countif(A4:A22,unique(A4:A22))-1)),",",true,true))
                ),
            B4:G22
          },{2,3,4,5,6,7,8},false
      ),""
    )
  )

Another formula with the same result:
= ARRAYFORMULA (
     ifna(vlookup (
          sort (
            { row(A4:A22) *
              len ( vlookup ( A4:A22,
                  {"Ana";"Jen";"Ben";"Helen";"Dan";"Richard";"Breg"},1,0)
              )^0}
            ,1,true
          ),
          { row(A4:A22),
            if(transpose(split(join(
               "","1," & rept("0,",COUNTIF(A4:A22,unique(A4:A22))-1)),",",true,true))=1,
               A4:A22,""
            ),B4:G22
          },{2,3,4,5,6,7,8},false),""
     )
  )

A: After a little bit of discussion on the sheet, this query() will display only one name per agent, but still list all the rows for that agent.
=ARRAYFORMULA(ARRAY_CONSTRAIN(QUERY({Sheet1!A1:G22,IF(COUNTIFS(Sheet1!A1:A22,Sheet1!A1:A22,ROW(Sheet1!A1:A22),"<="&ROW(Sheet1!A1:A22))>1,"",Sheet1!A1:A22)},"select Col8,Col2,Col3,Col4,Col5,Col6,Col7,Col1 where Col1 matches '"&TEXTJOIN("|",TRUE,A2:A)&"' order by Col1 label Col8'Name'",3),9^99,7))


text:
Q: How to remove AddThis from my site Someone outside of our organization embed AddThis code into our website as below. I try to remove those code from Cpanel, but couidn't find it anywhere, we are on Magento platform. Please can anyone give me a hand to figure this out pls?
Thanks a heap

A: Seems suspicious that someone outside of organization can change your website. You should probably look into securing your website with better password/security features for admin. You did not really share any code, so I cannot pinpoint any locations for edits.
However, take a look at how someone installs AddThis, and following the steps in reverse (remove the things the tutorials asks to add) should get rid of the module. http://www.addthis.com/academy/en/how-to-install-the-addthis-tools-to-magento/


text:
Q: Do web crawlers read the HTTP headers? I own a url shortening service and I want to detect whether the request that I received was from a web crawler or not. In response to the request, I send a HTTP header 302 that redirects the requester to the original link. I was thinking that I could provide an invisible link with the response, so that a bot would send me a request for that page too but a normal user wont. This is based on the hypothesis that even if bots read the header and redirects, they still scans the page and send requests to the links found in it. Is the hypothesis correct? If it is not, I could also redirect them via Javascript but that would not be the standard way of redirecting(I suppose).

A: Yes, crawlers definitely follow redirects. Their purpose is to find as many pages (or content) as possible. Following redirects is a basic requirement for that goal. However, I do not know if commercial crawlers read the body of a redirect response. I think they don't since information displayed on a redirect page is never shown to a user since they are always redirected away from that page.
There are other crawlers like Crawljax that are build for testing web applications. They will read all the data but those crawlers aren't (or shouldn't be) used to crawl the public web.


text:
Q: Go & Javascript secure authentication I'm currently signing users (authenticating) from the frontend, and making requests to the backend to sign up the user(save data in the database). I realize i cannot completely prevent this, but i don't want my API(signup) to be abused.
Go:
func SignIn(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    u_ip := base64Decode((params["u_ip"]))
    u_wallet := base64Decode(string(params["u_wallet"]))
    u_password := base64Decode(params["u_pass"])

    u_addr := strings.TrimPrefix(u_wallet, "0x")
    u_addr_temp := u_addr[0:7]
    for rowExists("select 1 from users where position(user_addr in $1)>0", u_addr_temp) {
        randInt := rand.Intn(5)
        u_addr_temp = u_addr[randInt : randInt+7]
    }

    sqlStatement := `INSERT INTO users (ip, user_addr, user_wallet, user_pass)
     VALUES($1, $2, $3, $4) returning id;`
    id := 0
    db := opendb()
    err := db.QueryRow(sqlStatement, u_ip, u_addr_temp, u_wallet, u_password).Scan(&id)
    if err != nil {
        panic(err)
    }
    w.WriteHeader(http.StatusCreated)
    w.Header().Set("Content-Type", "application/json")
    resp := make(map[string]string)
    resp["message"] = string(id) + "-" + string(u_addr_temp)
    jsonResp, err := json.Marshal(resp)
    if err != nil {
        log.Fatalf("Json Err. Err: %s", err)
    }
    w.Write(jsonResp)
}

Javascript:
              const u_wallet = window.btoa(result);
              const u_password = window.btoa(password.toString());
              await fetch(
                `http://localhost:8080/sign/${u_wallet}&${u_password}`,
                {
                  method: "POST",
                }
              )
                .then((response) => response.json())
                .then((data) => console.log(data));
            })();

You can see users can call http://localhost:8080/sign/${u_wallet}&${u_password} replace the wallet, and password (Base64 encoded) And GoLang will automatically create the row(in the database).
Go CORS:
    c := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"},
        AllowCredentials: true,
    })
    handler := c.Handler(router)

I can define Allowed Origins as strict-origin-when-cross-origin, but users will use the devtools console(JS).
My question isn't sending the data(safely), but how to communicate from the frontend and backend, and try and block users from calling the API.


text:
Q: Format datetime to Month - Year then order desc Can anyone help with this problem, I'm trying to select the last 12 month of dates from table, then change the format so that the date appears as:
Feb 2013
Jan 2013 etc
I can change the format to above, but that changes the date to string which then makes it impossible to order DESC.
How can I keep the above format, and still order by desc
SELECT DISTINCT TOP 12
--CONVERT(date, NewsDatePosted, 120) AS ArchiveTravelNewsByMonth
--CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120) AS MY
--DatePart(Year,NewsDatePosted) AS YearPosted
--datename(month,NewsDatePosted) + ' ' + DatePart(Year,NewsDatePosted) AS YearPosted
FROM dbo.at_News
order by ArchiveTravelNewsByMonth DESC

Thanks
George

SELECT DISTINCT TOP 12 SUBSTRING(CONVERT(VARCHAR(11), NewsDatePosted, 113), 4, 8)
AS ArchiveTravelNewsByMonth,
NewsDatePosted
FROM dbo.at_News
ORDER BY CONVERT(DATETIME, CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120))

A: Please try by adding an order by clause and inner select like
SELECT
    ArchiveTravelNewsByMonth,
    NewsDatePosted
FROM(
    SELECT DISTINCT TOP 12 SUBSTRING(CONVERT(VARCHAR(11), NewsDatePosted, 113), 4, 8) AS ArchiveTravelNewsByMonth,
        NewsDatePosted
    FROM dbo.at_News)x
ORDER BY CONVERT(DATETIME, ArchiveTravelNewsByMonth)

A:   create table at_News(NewsDatePosted datetime,Row int identity(1,1))

  Insert into at_News values('2011-01-01')
  Insert into at_News values('2006-10-25')
  Insert into at_News values('2012-09-10')
  Insert into at_News values('2002-06-20')
  Insert into at_News values('2008-12-01')
  Insert into at_News values('2008-10-01')
  Insert into at_News values('2008-04-01')

  select CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120)      from  at_News order by NewsDatePosted desc

Use Datetime column in ORDER BY CLAUSE with-out any format.


text:
Q: How do I take a video version of screenshot on iPod Touch 4th Gen? I want to create videos of myself doing app demos on my iPod, how do I create a video version of screen shot?

A: You could try Reflector (reflector.com) which is an app that runs on your Mac and grabs sound & video from your ios device over airplay. There's also AirServer but I found that wasn't nearly as responsive and it didn't have video recording ability. Reflector was called Reflection until recently.


text:
Q: Why is this number so close to $1$? The only positive solution of the equation $\sin (\tan x) = x$ is at a number $a = 0.999906...$. Is it a coincidence that the number $a$ is so close to $1$, or is there a conceptual explanation?
It was obvious $a$ was going to have to be less than $1$, but not this close. The answer seems to be related to $\tan 1 \approx \pi/2$, but that merely shifts the problem to explaining why that is the case.
(I became interested in this question after reading this other question: Prove: $\sin (\tan x) \geq {x}$ )
Edit: I have thought about the question some more, and added some ideas in the form of an answer partially addressing why we have $\tan 1 \approx \pi/2$.

A: J Swanson and Christian Blatter's answers address the question of why, given that $\tan 1 \approx \pi/2$ (within $1 \%$), we have $\sin \tan 1 \approx 1$ within $0.01\%$. Taylor's formula for $\sin x$ about $x = \pi/2$ shows why the accuracy would be approximately squared.
That leaves open the question of why $\tan 1 \approx \pi/2$.
Gauss's continued fraction for $\tan z$ (see http://en.wikipedia.org/wiki/Gauss_continued_fraction ) is:
$$\tan z = \cfrac{z}{1 - \cfrac{z^2}{3 - \cfrac{z^2}{5 - \cfrac{z^2}{7 - {}\ddots}}}}.$$
In particular, for $z = 1$, this yields
$$ \tan 1 \approx  \cfrac{1}{1 - \cfrac{1}{3 - \cfrac{1}{5}}} = \frac{14}{9}.$$
This is an excellent approximation, valid to within just over $0.1\%$. So we need only consider the question of why $\pi \approx 28/9$.
I don't have a very good answer for this part, as I haven't been able to locate any standard approximating sequences of $\pi$ one of whose first terms is $28/9$. However, you can obtain $28/9$ as an approximation of $\pi$ in the following way, as explained in A History of Pi by Beckmann. (If the circle has area $\pi$, then the octagon has area $28/9$.)

A: It happens that $\pi/2 - \tan 1 \approx 0.0133886$. This may just be a numerical coincidence or there may be a good reason. But in any case, $\sin$ is very flat close to $\pi/2$, so even values that are just pretty close to $\pi/2$ get translated to values very close to $1$, hence $\sin \tan 1 \approx 0.9999103$. By continuity/smoothness the fixed point must be very close to $1$, as you say.
I'll make this more quantitative in an effort to make it more "explanatory". Suppose $f(x)$ is smooth near $x=1$ and $f(1) - \pi/2 = \delta$. Then $\sin(f(1)) = \cos(\delta) = 1 - \delta^2/2 + \cdots$. Hence $\sin f(x) - x$ at $x=1$ is $-\delta^2/2 + \cdots$. If $|\delta| \approx 0$, the difference is approximately $0$, so if a fixed point exists, it should be near here, which can be made rigorous by comparing the derivative of $\sin f(x) - x$ to $-\delta^2/2 + \cdots$ at $x=1$.
In the present case with $f = \tan$, we find $\delta \approx -0.0133886$, we have $-\delta^2/2 \approx -0.0000896273$, and this is tiny compared to $(\sin \tan x - x)'(1) \approx -0.954138$, so we'll definitely get a fixed point very close to here. Indeed, the actual fixed point differs from $1$ by $0.0000939875$, which is very close to my estimate, and moreover $0.0000896273/0.954138 \approx 0.0000939354$. That is, the closeness of the fixed point to $1$ is just an amplified version of the closeness of $\tan 1$ to $\pi/2$ thanks to the sine function.
Some thoughts on $\pi/2 - \tan 1 \approx 0.0133886$: we can change the problem in at least two ways--replace $\sin$, $\pi/2$, $1$; replace $\tan$--and sometimes the above reasoning will still go through. There are a lot of potential tweaks, so I'd be satisfied by the coincidence explanation. On the other hand, it would be more interesting if was something really was going on with $\tan$ and $\pi/2$.

A: Consider that you try to solve your equation using Newton method starting at $x=1$. The first iterate is given by
$$x = 1 + \frac {-1 + \sin(\tan(1))} {1 - \cos(\tan(1)) \sec(1)^2};$$
the change is $-0.000093934$.
If you use Halley method, the formula becomes much more complex and the change is $-0.0000939875$.

A: From
$${4\over3}=1+{(1)^3\over3}<\tan 1<\tan{\pi\over3}=\sqrt{3}$$
it follows that
$$\tan 1={\pi\over2}+\tau$$ for a $\tau$ of small absolute value. That in fact $\tau\doteq-0.0134$ and therefore $|\tau|\ll1$ is pure luck.
For a $\delta$ with $0<\delta\ll 1$ we therefore have
$$\tan(1-\delta)\doteq{\pi\over 2}+\tau-\delta\left(1+{\pi^2\over4}\right)\doteq {\pi\over2}+\tau-{7\over2}\delta\ ,$$
where we have made use of $\pi^2\doteq10$. It follows that
$$\sin\bigl(\tan(1-\delta)\bigr)\doteq 1-{1\over2}\left(\tau-{7\over2}\delta\right)^2\ ,$$
and this should be equal to $1-\delta$ for some positive $\delta\ll1$. The equation
$$\left(\tau-{7\over2}\delta\right)^2=2\delta$$
has two solutions $\delta_1\doteq{\tau^2\over2}$ and $\delta_2\doteq{8\over49}$, the first of which is the one we are interested in. Given the value of $\tau$ from above we obtain $\delta_1\doteq0.0000896$, which leads to $x=0.9999103$.


text:
Q: change variable name in foreach with jquery Is there any chance to change PHP variable with jquery?
My code
$(function() {
  $('#websites').hide();
  $('#main-cat').change(function() {
    if ($('#main-cat').val() == 'websites') {
      $('#websites').show();
      var echo = "<?php echo $ws->websites;?>";
    } else {
      $('#row_dim').hide();
    }
  });
});

  Izvēlieties apakškategoriju

    <select class="select-general form-control" name="category">
      <option label="---Izvēlēties---"></option>
      <?php foreach ($websites as $ws){ ?>
      <option value="<?php echo **$ws->websites**;?>">
        <?php echo $ws->websites;?>
      </option>
      <?php } ?>
    </select>

But i want to change $ws->websites to $ws->applications dynamically depending on main category choice.

A: Try this.echo the code depend on js condition
var echo="";
if($('#main-cat').val() == 'websites') {
        echo = "<?php echo $ws->websites;?>";
     } else {
        echo = "<?php echo $ws->application;?>";
     }


text:
Q: blueimp jQuery-File-Upload - How do I submit form without files attached? I have found solutions on how to add additional form data when submitting the file upload form. This question is how to upload the additional data if there is no file to upload.
I am using blueimp jquery-file-upload in a task management app in order to drag and drop files and attach them to a task.
The script is initialized and setup to not automatically upload when files are attached. On the fileuploadadd callback I attach data.submit() to my submit event handler. This accomplishes that we submit the task data and the files in one POST request.
Until files are added I'm unable to get access to the file-upload data to use the data.submit() function. I came up with a work around by adding an empty file (and then removing it) on page load which would trigger the binding data.submit() to the submit button. The problem is that the plugin is returning an error while trying to loop through an empty array of files. This problem would also occur if you added a file and then removed it before submitting the form.
I have been looking for a solution to this for a while and have looked high and low but couldn't find anything in the (IMHO) terrible documentation.
Have a look at my code below:
    $('#post_task').fileupload({
        autoUpload: false,
        singleFileUploads: false,
        disableImagePreview: true,
    }).on('fileuploadadd', function (e, data) {
        $.each(data.files, function (index, file) {
            var filename = file.name,
                filesize = bytesToSize(file.size)
                ext = filename.substr(filename.lastIndexOf('.')+1,5),
                icon = '',
                node = $('
').append($('').html(icon + filename + ' ' + filesize + '&times')).attr('data-index',index);

            node.find('a').click(function(e){
                e.preventDefault();
                var $self = $(this),
                    $listItem = $self.parents('li'),
                    listIndex = $listItem.attr('data-index');
                $listItem.remove();
                $('#files li').attr('data-index',function(index){return index;});
                data.files.splice(listIndex,listIndex);
                console.log(data);
                vardata = data;
            });
            $('#files').append(node);
        });
        $('#post_task').unbind('submit').submit(function(ev){
            ev.preventDefault();
            data.submit();
        });
    });

A: I faced the same problem and I ended up adding an empty file prior to submitting if there is no file.
$("#fileupload").fileupload('add', {
    files: ['']
});

This works perfectly in my situation and the backend receives the POST while the submitted file is null.
With most browsers (tested Chrome and FF) my Backend will receive no file (null) but with IE8 there is one with size 0. I haven't tested it with any other IE.

A: I just made two separate handlers like so:
$('#avatar').fileupload({
            singleFileUploads: true,
            multipart        : true,
            dataType         : 'json',
            autoUpload       : false,
            url              : config.settings.api + 'services/user/updateByActivationKey',
            type             : 'POST',
            add              : function (e, data) {

                submitbtn.on("click", function () {
                    console.log('submitting with image');
                    data.submit();
                });
            },
            done             : function (result) {

                console.log(result);
                if (!result.error) {
                    $('#modal-account-activated-success').modal('show');
                    $("#submitbtn").removeAttr('disabled');
                    $('#mercname').html('');
                    window.setTimeout(function () {
                        window.location.href = config.settings.user_url;
                    }, 3000);

                } else {
                    //analytics.track('completeProfileError', {
                    //  error        : JSON.parse(result.responseText).error,
                    //  activationKey: sessionStorage.getItem("activationkey")
                    //});
                    $('#modal-account-activated-error').modal('show');
                    $('#submitloader').html('');
                    $("#submitbtn").removeAttr('disabled');
                }
            }
            ,
            fail             : function (e) {
                //analytics.track('completeProfileError', {
                //  error        : e,
                //  activationKey: sessionStorage.getItem("activationkey")
                //});
                $('#errormessage').html(JSON.parse(e.responseText).error.messages[0]);
                $('#modal-account-activated-error').modal('show');
                $('#submitloader').html('');
                $("#submitbtn").removeAttr('disabled');

            }
        });

        //if no image was uploaded
        submitbtn.on("click", function () {
            if ($('#preview').html().length < 1) {
                console.log('submitting without image');

                $.ajax({
                    url       : config.settings.api + 'services/user/updateByActivationKey',
                    type      : 'POST',
                    data      : JSON.stringify({
                        'email'                     : $("#email").val(),
                        'activationKey'             : $("#activationKey").val(),
                        'firstName'                 : $("#firstname").val(),
                        'lastName'                  : $("#name").val(),
                        'password'                  : $("#password").val(),
                        'gender'                    : $("#gender").val(),
                        'birthdate'                 : $("#birthdate").val(),
                        'acceptedTermsAndConditions': $("#checkbox-accept-terms").val(),
                        'allowsDirectMarketing'     : $("#checkbox-allow-marketing").val()

                    }),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("Content-Type", "application/json");
                    },
                    success   : function (result) {
                        console.log(result);
                        if (!result.error) {
                            $('#modal-account-activated-success').modal('show');
                            $("#submitbtn").removeAttr('disabled');
                            $('#mercname').html('');
                            window.setTimeout(function () {
                                window.location.href = config.settings.user_url;
                            }, 3000);

                        } else {
                            //analytics.track('completeProfileError', {
                            //  error        : JSON.parse(result.responseText).error,
                            //  activationKey: sessionStorage.getItem("activationkey")
                            //});
                            $('#modal-account-activated-error').modal('show');
                            $('#submitloader').html('');
                            $("#submitbtn").removeAttr('disabled');
                        }
                    },
                    error     : function (e) {
                        //analytics.track('completeProfileError', {
                        //  error        : e,
                        //  activationKey: sessionStorage.getItem("activationkey")
                        //});
                        $('#errormessage').html(JSON.parse(e.responseText).error.messages[0]);
                        $('#modal-account-activated-error').modal('show');
                        $('#submitloader').html('');
                        $("#submitbtn").removeAttr('disabled');
                    }
                })
            }
        });

A: @Hirshy and @Luk, your solution is really quite elegant and works like a charm. The files input field does not even get sent to the server so it's easy to determine when a file is in the payload.
In my Angular app, I have a single view for both adding a new document and some attendant data and for editing the data and/or uploading a replacement document.
Here is my solution:
/*------------------------------------------------------------------------*/
/* Prepare file uploader.                                                 */
/*                                                                        */
/* jQuery-File-Upload does not submit a form unless a file has been       */
/* selected. To allow this, we manually add an empty file to be uploaded, */
/* which makes the submit handler available, and we replace the submit    */
/* handler with one that will submit the form without a selected file.    */
/*                                                                        */
/* see: http://stackoverflow.com/q/21760757/2245849.                      */
/*------------------------------------------------------------------------*/
var uploadForm = $('#DocumentForm');
var fileInput  = $('#DocumentForm input:file');

$scope.uploadOptions =
  {
  url:              Services.Documents.uploadRoute,
  autoUpload:       false,
  dropZone:         uploadForm,
  fileInput:        fileInput,
  replaceFileInput: false
  };

/*---------------------------------------------------------------*/
/* Initialize the uploader. This must be done with the options   */
/* or an error will be thrown when an empty file is added below. */
/* It is also necessary to initialize with the options here as   */
/* well as in the element html or the results are unpredictable. */
/*---------------------------------------------------------------*/
uploadForm.fileupload($scope.uploadOptions);

/*--------------------------------------------------------------------*/
/* File processing is called in the default add handler and this      */
/* handler is called after a successful add. It displays the file     */
/* name in the drop zone, sets the document name for a new document,  */
/* and sets the submit handler to submit the form with file and data. */
/*                                                                    */
/* If editing a document, a dummy empty file object is manually       */
/* added to make the submit handler available so the user can make    */
/* data changes without uploading a new document.                     */
/*--------------------------------------------------------------------*/
uploadForm.bind("fileuploadprocessdone", function(e, data)
  {
  /*------------------------------------------------------------*/
  /* Get the user selected file object and display the name.    */
  /* Set the document name to the file name if not already set. */
  /*------------------------------------------------------------*/
  if (data.files[0].name)
    {
    $scope.document.file = data.files[0];
    if (!$scope.document.name)
      $scope.document.name = $scope.document.file.name;
    MessageService.clear();
    }

  /*--------------------------------------*/
  /* If this is the dummy file add, reset */
  /* 'acceptFileTypes' to global config.  */
  /*--------------------------------------*/
  else
    delete $scope.uploadOptions.acceptFileTypes;

  /*------------------------------------------------------------*/
  /* Set the submit handler. We have to do this every time a    */
  /* file is added because 'data' is not passed to the handler. */
  /*------------------------------------------------------------*/
  uploadForm.unbind('submit').submit(function(e)
    {
    e.preventDefault();
    data.submit();
    });
  });

/*---------------------------------------------------------------------------*/
/* If we get here, the file could not be added to the process queue most     */
/* likely because it is too large or not an allowed type. This is dispatched */
/* after the add event so clear the current file and show the error message. */
/*---------------------------------------------------------------------------*/
uploadForm.bind("fileuploadprocessfail", function(e, data)
  {
  $scope.document.file = null;
  MessageService.notice(data.files[data.index].error);
  });

/*-----------------------------------------------------------------*/
/* Add a dummy empty file if not a new document so the submit      */
/* handler is set and the user does not have to upload a document. */
/*-----------------------------------------------------------------*/
if (!$scope.new_document)
  {
  $scope.uploadOptions.acceptFileTypes = null;
  uploadForm.fileupload('add', { files: [{}] });
  }

UPDATE
It turns out uploadForm.fileupload('add', { files: [''] }); will result in an exception being thrown in the browser if the server returns a failed status. JFU tries to assign data.files[0].error and data.files[0] doesn't exist.
The problem is handled nicely by assigning an empty array instead of an empty string: uploadForm.fileupload('add', { files: [[]] });
I have updated the example above.
UPDATE 2/29/16
It turned out I did want to restrict the file types after all so I modified my script to clear 'acceptFileTypes' property before the dummy file add and reset it in the add handler. Also discovered I could not access the process errors in the add handler so replaced it with 'fileuploadprocessdone' and handled the error in 'fileuploadprocessfail'.
I have updated the example above but we're still using JFU 5.42.0.
IMPORTANT
I am using 5.42.0 which is a very old version of JFU. I did not write this code and my first attempt to upgrade failed. When I do upgrade, I'll update this solution.**

A: Try this puglin simpleUpload, no need form
Html:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>

Javascript:
$('#simpleUpload').simpleUpload({
  url: 'upload.php',
  trigger: '#enviar',
  success: function(data){
    alert('Envio com sucesso');

  }
});


text:
Q: Set IE to run as administrator for restricted users? I have locked down a user with windows steady state, but I have put the user folder onto a different partition so that no data from firefox, thunderbird,etc is lost when the user logs off or restarts which is caused by steady state.
I want the restricted user to be able to open Internet Explorer as an administrator, I have been able to do this with the code below but it asks for a password every time the user logs on and not just the first time because windows steady state restores back to how it was.
%windir%\system32\runas.exe /user:localhost\administrator /savecred "C:\Program Files\Internet Explorer\iexplore.exe http://google.co.uk"

I've read theres no way to add password to this code but I did find a work around when I last did this but can't remember how, any ideas?


text:
Q: ASP.Net MVC Razor Document Downloading as Corrupt I'm working on an ASP.Net project that is based off of Razor. We are posting documents from the client side using formdata and need to change the name of this file based on who is uploading it. We have a method for doing so, which you can see here:

var fileToSave = "";

if (filename != null) {
    fileToSave = '@ViewBag.CompName' + "-" + filename.name;
    fileToSave = fileToSave.replace(/\s+/g, '-');
}

var formData = new FormData();
formData.append("Document", filename, fileToSave);

This saves the document with the proper name, e.g. "Test-Company-test.docx"
The problem exists when I go to download the file and open it up. The document downloads properly, and has the appropriate size of the uploaded file, for this purpose, "test.docx".
When opening the downloaded file, Word prompts you with the following:

Pressing "OK" then shows the following message:

Following this message, if you click "Yes," the document opens and the entirety of the document is there. There is no corrupt data, and everything is formatted exactly how it is supposed to be.
This error does not exist if we just save the document as the original document name. Which normally we would do, but this is a large application that is client facing and allows users to upload documents themselves. This can be a problem if Company A uploads a document called "Test.docx" and Company B also uploads a document called "Test.docx" thus overwriting Company A's document. Hence, the renaming of the documents.
How is it that we can prevent this error from happening?

A: Coming back to answer this question. It turns out that I had forgotten to add the filesize to the download information, so when it was downloading it didn't know how large the file was supposed to be. We just had to add the following line of code:
Response.AddHeader("Content-Length", file.Length.ToString());

So to close everything together, this is what the download function looked like at the end:
    public void DownloadCompanyDoc(int id)
    {
        try
        {
            var getFile = rep.GetCompanyDocById(id);
            var path = Path.Combine(HostingEnvironment.MapPath("~/Documents/CompanyDocs"), getFile);
            FileInfo file = new FileInfo(path);

            if (file.Exists)
            {
                Response.Clear();

                Response.AppendHeader("content-disposition", "attachment; filename=" + getFile);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
                Response.WriteFile(path);
                Response.TransmitFile(path);
                Response.Flush();
                Response.End();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Hope this helps someone else in the future (pending someone else ever experiences this).


text:
Q: how to make animatorInflater correct? I'm trying to correct AnimatorInflater but it doesn't work and I can't find my error.
MainActivity.java:
package com.example.administrator.propertyanimation;

import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.widget.Button;
import android.util.*;

public class MainActivity extends ActionBarActivity {

    private Button mbttn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mbttn = (Button) findViewById(R.id.btn);

        ObjectAnimator anim = (ObjectAnimator) AnimatorInflater.loadAnimator(MainActivity.this, R.animator.propertyanimation);
                anim.setTarget(mbttn);
        anim.start();

        return ;
    }
}

propertyanimation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
    android:propertyName="rotation"
    android:valueFrom="0"
    android:valueTo="360"
    android:duration="3000"
    android:repeatCount="1"
    android:repeatMode="reverse"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>

This is the logcat output:
03-27 10:27:05.422    3825-3825/com.example.administrator.propertyanimation E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.administrator.propertyanimation, PID: 3825
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.administrator.propertyanimation/com.example.administrator.propertyanimation.MainActivity}: java.lang.ClassCastException: android.animation.AnimatorSet cannot be cast to android.animation.ObjectAnimator
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: android.animation.AnimatorSet cannot be cast to android.animation.ObjectAnimator
            at com.example.administrator.propertyanimation.MainActivity.onCreate(MainActivity.java:25)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
03-27 10:27:05.434      584-596/system_process W/ActivityManager﹕ Force finishing activity

Then a dialog always appears that says "Unfortunely, Activity has stopped"

A: You're loading an AnimatorSet and then try to assign it to an ObjectAnimator, which gives you the exception you see in logcat.
Remove the set tag from your propertyanimation.xml
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="rotation"
    android:valueFrom="0"
    android:valueTo="360"
    android:duration="3000"
    android:repeatCount="1"
    android:repeatMode="reverse"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>

Alternatively, if you want to keep the set because you want to add to it later, you can change your code to load an AnimatorSet instead like this:
AnimatorSet anim = (AnimatorSet) AnimatorInflater.loadAnimator(MainActivity.this, R.animator.propertyanimation);


text:
Q: Getting a map object in form of Map>> from JSON Array There's a JSON array response I am getting as below.
    [{
        contracted: 1
        payrolltype: basicsalary
        otherdata: sampledata
        salary: 1000
    },{
        contracted: 1
        payrolltype: basicsalary
        otherdata: sampledata
        salary: 1001
    },{
        contracted: 2
        payrolltype: basicsalary
        otherdata: sampledata
        salary: 10002
    },
    {
        contracted: 1
        payrolltype: addon
        otherdata: sampledata
        salary: 1004
    }]

I want to structure this data in the form of Map<String, Map<String,List<SalaryMapper>>>
First, I needed to arrange the data by contractId with the List of Object mapped with the objects where contractId field is common.
For this, I have used java stream as given:
List<SalaryMapper> salMap = myArray;
Map<String, List<SalaryMapper>> map = salMap.stream().collect(Collectors.groupingBy(SalaryMapper::getContractId));

Now I am getting the result grouped by contractId. And I am trying to group the map to another level by payrollType: Map<contractId, Map<payrollType, List<SalaryMapper>>>.
For this, I tried to iterate the main map and push it to Map<contractId, Map<payrollType, List<SalaryMapper>>> object, but I am getting lost here.
    Map<String, Map<String,List<SalaryMapper>>> subMap = null;

    Map<String,List<SalaryMapper>> newMapForPayrollType = null;

    for(Map.Entry<String, List<SalaryMapper>> entry : map.entrySet()) {

    }

    return subMap;

A: You can do nested level groupingBy by passingdownstream Collector to do a secondary groupingBy
Map<Integer, Map<String, List<SalaryMapper>>> map = salMap.stream()
    .collect(Collectors.groupingBy(SalaryMapper::getContractId,
      Collectors.groupingBy(SalaryMapper::getPayrollType)));

As per the data shown in above the contractid is of Integer type and payrolltype is String, more examples can be found here

A: The naive approach to your question would be as below:
Map<String, Map<String, List<SalaryMapper>>> subMap = new HashMap<>();

for (SalaryMapper sal: salMap) {
    Map<String, List<SalaryMapper>> payrollTypeMap = new HashMap<>();
    if (subMap.containsKey(sal.getContractId()) {
        payrollTypeMap = subMap.get(sal.getContractId());
        if (payrollTypeMap.containsKey(sal.getPayrollType())) {
            payrollTypeMap.put(sal.getPayrollType(), payrollTypeMap.get(sal.getPayrollType()).add(sal));
        } else {
           payrollTypeMap.put(sal.getPayrollType(), new ArrayList<>(){{add(sal);}};
        }
    } else {
        payrollTypeMap.put(sal.getPayrollType(), new ArrayList<>(){{add(sal);}};
    }
    subMap.put(sal.getContractId(), payrollTypeMap);
}

Above code can be optimized and written with fewer lines of code as below:
Map<Integer, Map<String, List<SalaryMapper>>> subMap = salMap.stream()
       .collect(Collectors.groupingBy(SalaryMapper::getContractId,
         Collectors.groupingBy(SalaryMapper::getPayrollType)));


text:
Q: How to save a parent object by saving a child object I have 3 entities: Instructor entity, Course entity and InstructorDetail entity.
There are two relationships between 3 entities:
Instructor[one] - course[many]
Instructor[one] - InstructorDetail[one]

Now I get this error when I save a new course in a session:
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: hibernate.one_to_many_bi.entity.Instructor

In main():
Session session = sessionFactory.openSession();
try {
    Instructor instructor = new Instructor("Susan", "Snow", "Susan@gmail.com");
    instructor.setInstructorDetail(new InstructorDetail("youtube", "video game"));
    Course course1 = new Course("Air Guitar - The Ultimate Guide");
    instructor.addCourse(course1);
    session.beginTransaction();
    session.save(course1);
    session.getTransaction().commit();
}
finally {
    session.close();
    sessionFactory.close();
}

Why my code is not working? I already have all types of cascade annotation in my Course class except CascadeType.REMOVE. Why Instructor and InstructorDetail are not saving into Database automatically by cascade?
Instructor class:
@Entity
@Table(name = "instructor")
@Slf4j
@Data
public class Instructor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column()
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "instructor_detail_id")
    @ToString.Exclude
    @Setter(AccessLevel.NONE)
    private InstructorDetail instructorDetail;

    @OneToMany(mappedBy = "instructor",
               cascade = {
                    CascadeType.DETACH,
                    CascadeType.MERGE,
                    CascadeType.PERSIST,
                    CascadeType.REFRESH
    })
    @ToString.Exclude
    @Setter(AccessLevel.NONE)
    private List<Course> courses;

    public Instructor() {}

    public Instructor(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public void setInstructorDetail(InstructorDetail instructorDetail) {
        instructorDetail.setInstructor(this);
        this.instructorDetail = instructorDetail;
    }

    public void addCourse(Course course) {
        if (courses == null) {
            courses = new ArrayList<>();
        }
        course.setInstructor(this);
        courses.add(course);
    }
}

Course class:
@Entity
@Table(name = "course")
@Slf4j
@Data
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "title")
    private String title;

    @ToString.Exclude
    @ManyToOne(cascade = {
                            CascadeType.DETACH,
                            CascadeType.MERGE,
                            CascadeType.PERSIST,
                            CascadeType.REFRESH
    })
    @JoinColumn(name = "instructor_id")
    private Instructor instructor;

    public Course() {
    }

    public Course(String title) {
        this.title = title;
    }
}

InstructorDetail class:
@Entity
@Table(name = "instructor_detail")
@Slf4j
@Data
public class InstructorDetail {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "youtube_channel")
    private String youtubeChannel;

    @Column(name = "hobby")
    private String hobby;

    @OneToOne(mappedBy = "instructorDetail",
            cascade = {CascadeType.DETACH,
                    CascadeType.MERGE,
                    CascadeType.DETACH,
                    CascadeType.PERSIST,
                    CascadeType.REFRESH})

    @ToString.Exclude
    Instructor instructor;

    public InstructorDetail() {
    }

    public InstructorDetail(String youtubeChannel, String hobby) {
        this.youtubeChannel = youtubeChannel;
        this.hobby = hobby;
    }
}

I new to hibernate. I did some research online and didn't find much about dependencies between parent and child objects. I really appreciate it if someone can tell me why my code is not working.


text:
Q: rsync & source/dest & tar.gz beginner thing, too primitive for FAQs: actually, I AM being ashame about my question (both parts of it) but could anyone help me with my problem?
*) I have read how to use rsync BUT could anyone give me an example how to type it in?
rsync -a source dest
is comprehensible BUT how do I write source and dest?
(they are called sda1 and sda2 in my linux)
is it "rsync -a sda1 sda2" (for example, for copying all of sda1 to sda2 ?)
and
*) I have downloaded a driver and an executable for linux (they are .tar.gz)
since I dont care about the MD5 key (I would not know how to use that, either)
my problem is only
a) in which folder /root/??? do I have to copy the contents of the driver .tar.gz
(or does that need an extra installation routine? I want to use it with DSL damn small linux from CD without installing the -- I think -- debian which it is, so I still should be able to copy it into a virtual disk part in memory claimed to be used by DSL) ?
and
b) in which folder /root/??? do I have to copy the executable (and how do I start it) ?
(or, same question, does that need an extra installation?)
thank you for your patience, whoever would care about me
Regina

A: First, sda1 and sda2 are likely partition names, not mounted file systems. You will need to check if they are already mounted. To do this, use the command mount without any parameters. If they don't appear in this list, you have to mount them first, e.g. with mount /dev/sda1 /mnt/data1 and mount /dev/sda2 /mnt/data2.
If this is done, you can just use
rsync -av /mnt/data1 /mnt/data2

If one or both are already mounted, replace /mnt/data1/ (or data2 with the respective mount point).
Also, should you actually have two directories named sda1 and sda2, the command will in fact be
rsync -av /path/to/sda1 /path/to/sda2

Please rephrase the second question, stating what you have and what you want to do, without irrelevant additional infos like the MD5 part. Also, try to use the formatting tools that are available to make your text more readable. As it stands, it is quite confusing.


text:
Q: Не получается получить координаты с GPS Почему у меня "вылетает" приложение, когда я пытаюсь получить координаты с GPS. Если что в коде я пометил комментарием где ошибка вылетает, во время запуска.
public abstract class MainActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync((OnMapReadyCallback) this);
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);// Вот тут приложение вылетает !!!
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }

    public class coordinats{
        public double Latitude;
        public double Longitude;
    }

    public void onLocationChanged(Location location)
    {
        if (location != null)
        {
            coordinats position = new coordinats();
            position.Latitude = location.getLatitude();
            position.Longitude = location.getLongitude();
            new Gson().toJson(position);

        }
    }

    public void conect (View v){
        Thread network = new Thread(new ClientThread());
        network.start();
    }

    private Socket socket;

    private static final int SERVERPORT = 1111;
    private static final String SERVER_IP = "1.23.45.67";

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }

    public void onMapReady(GoogleMap map) {
        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
        Marker melbourne = map.addMarker(new MarkerOptions()
                .position(MELBOURNE)
                .title("Melbourne")
                .snippet("Population: 4,137,400")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.fingerbig)));

--- UPD ---
05-10 16:28:54.579 3967-3974/myhome.gps_tracker I/art: Debugger is active
05-10 16:28:54.590 3967-3967/myhome.gps_tracker I/System.out: Debugger has connected
05-10 16:28:54.590 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:54.800 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:55.010 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:55.220 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:55.429 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:55.640 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:55.849 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:56.059 3967-3967/myhome.gps_tracker I/System.out: waiting for debugger to settle...
05-10 16:28:56.269 3967-3967/myhome.gps_tracker I/System.out: debugger has settled (1431)
05-10 16:28:56.283 3967-3967/myhome.gps_tracker W/System: ClassLoader referenced unknown path: /data/app/myhome.gps_tracker-1/lib/x86
05-10 16:28:56.379 3967-3967/myhome.gps_tracker W/System: ClassLoader referenced unknown path: /data/app/myhome.gps_tracker-1/lib/x86
05-10 16:28:56.536 3967-4022/myhome.gps_tracker I/GMPM: App measurement is starting up
05-10 16:28:56.547 3967-4022/myhome.gps_tracker E/GMPM: getGoogleAppId failed with status: 10
05-10 16:28:56.547 3967-4022/myhome.gps_tracker E/GMPM: Uploading is not possible. App measurement disabled
05-10 16:28:56.551 3967-3967/myhome.gps_tracker D/AndroidRuntime: Shutting down VM
05-10 16:28:56.551 3967-3967/myhome.gps_tracker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: myhome.gps_tracker, PID: 3967
                                                                  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{myhome.gps_tracker/myhome.gps_tracker.MainActivity}: java.lang.InstantiationException: java.lang.Class<myhome.gps_tracker.MainActivity> cannot be instantiated
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                   Caused by: java.lang.InstantiationException: java.lang.Class<myhome.gps_tracker.MainActivity> cannot be instantiated
                                                                      at java.lang.Class.newInstance(Native Method)
                                                                      at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: MainActivity обьявлена как abstract, а вы прописали ее в манифесте и система не может создать ее экземпляр.
Вот и вся разгадка, GPS совсем ни при чем.


text:
Q: Retrieving a parameter from GSP in Controller, Grails I do have this code on my demo.gsp file. But I´m new to grails and I don´t really know very well how to retrieve the value of the input on my Controller to validate it like i.e "inputResult=="hi" then ok else bad".
<g:form action='${postUrl}' method='post' id='loginForm' class='cssform' autocomplete='off'>

    <g:message code="access.code"/>:

   <input name="j_password" class="loghominput" id="password" type="password"/>

  <g:message code="home.enter"/><input type="submit" style="display:none" value="Enter"/>

</g:form>

My Controller is like this.
class AskDemoController {

    def demo = {

    }
}

Thanks!

A: You can access parameters submitted by your form in the controller by using the params object.  Something like this...
def somethingInTheForm = params.nameOfTheParam;

if (somethingInTheForm){
   render 'good'
}else{
   render 'bad'
}

Take a look here for documentation.
However - i would suggest going through some to the Tutorials to gain a better understanding of the power of grails.


text:
Q: Yii CDbCriteria get all records with same character in column i'm not good with sql, i'm making a CListView for all records with a selected id in column to be displayed on the page.. just for practice, i wanted to add a dropdown that will select another kind of sort (id DESC is already there).
i have a table with columns: id, Name, Project_id, User_id, Assigned, etc...
for now this is my code:
public function actionView($id)
    {
        $model = $this->loadModel($id);

        $criteria = new CDbCriteria(array(
            'order'=>'id desc',
            'condition'=>'Project_id='.$id
        ));

        $dataProvider = new CActiveDataProvider('Task', array(
            'criteria'=>$criteria
        ));

        $this->layout = 'column2';

        $this->render('view', array('model'=>$model, 'dataProvider'=>$dataProvider));
    }

i'm selecting all records that has the requested project_id, so what i'm trying to do, which i have no clue how to do, is to add another criteria selection on the column "Assigned" the problem is, some of this records has more than 1 single assigned and its being saved as "1,2,5,6". so if i add another selection with assigned 1, it will just show me thoses records that have in assigned "1" and not thoses that have "1,3,5,6".. i was thinking on make a search on string but i dont know how it works on sql (Because i dont know SQL that much)

A: Try this -
$criteria = new CDbCriteria(array(
    'order'=>'id desc',
    'condition'=>'Project_id='.$id.' AND find_in_set($assigned, Project_id)'
));

But here $assigned can have only single value i.e. $assigned = 1 or $assigned = 2.
If $assigned = "1,2" where 1,2 itself will be considered as single value and so result will be returned only if the pattern is 1,2.. in the table and not 2,1,...
I hope it gives some idea.

A: found my solution.. seems like im using SQLite and SQLite does not support find_in_set(), instead. i would have to use (',' || Assigned || ',') LIKE '%,1,%'. like this..
$criteria = new CDbCriteria(array(
            'order'=>'id desc',
            'condition'=>'Project_id='.$id.' AND ("," || Assigned || ",") LIKE "%,5,%"'
        ));


text:
Q: ¿Cómo insertar valores de variables en array? tengo 4 variables, cada una con su valor y necesito meter en un array los valores de esas variables. Estoy probando con un for pero no llego a conseguir el resultado que deseo.
Este es mi código:
$variable1 = "hola";
$variable2 = "mundo";
$variable3 = "prueba";
$variable4 = "esto";

$arrayValores = array();

$nombre = "variable";

for($i = 1; $i <= 4; $i++) {
    array_push($arrayValores, $nombre.$i);
}

print_r($arrayValores);

El resultado que obtengo es el siguiente:
Array ( [0] => variable1 [1] => variable2 [2] => variable3 [3] => variable4 )

¿Alguna ayuda?

A: Espero sea lo que buscas.
<?php
    $variable1 = "hola";
    $variable2 = "mundo";
    $variable3 = "prueba";
    $variable4 = "esto";

    $arrayValores = array();

    $nombre = "variable";

    for($i = 1; $i <= 4; $i++) {
        array_push($arrayValores, ${$nombre.$i });
    }
    print_r($arrayValores);
?>

Salida: Array ( [0] => hola [1] => mundo [2] => prueba [3] => esto )

Te recomiendo y leas un poco la documentación para comprendas mucho mejor

A: Concatena el valor numérico y después usa la variable:
for($i = 1; $i <= 4; $i++) {
    $nombre = 'variable'.$i;
    array_push($arrayValores, $$nombre);
}

Usa comillas simples siempre que puedas, las comillas dobles hacen que php busque variables dentro de ellas, por ejemplo:
for($i = 1; $i <= 4; $i++) {
    $nombre = "variable$i";
    array_push($arrayValores, $$nombre);
}

A: Si bien ya tienes excelentes respuestas, me gustaría proponer:
$arrayVariables = [
        $variable1 = "hola",
        $variable2 = "mundo",
        $variable3 = "prueba",
        $variable4 = "esto",
    ];

$arrayNuevo = [];

for($contador = 0; $contador < count($arrayVariables); $contador++) {
    array_push($arrayNuevo, $arrayVariables[$contador]);
}

print_r($arrayNuevo);

Cuya salida sería esta:
Array
(
    [0] => hola
    [1] => mundo
    [2] => prueba
    [3] => esto
)

Como notas:

*

*Las variables quedan dentro de un array

*El ciclo for iterará mientras el contador sea menor al conteo de elementos de dicho array

*Cuando vamos agregando los elementos al array vacío, empleamos la sintaxis de: $arrayOriginal[$variableContador]

*Por fuera del loop obtenemos el array con los valores de las variables acumulados en el


text:
Q: How to obtain partial derivative symbol in mathematica I would like Mathematica to return symbolic partial derivative instead of actual derivative.
StressMatrix = ( {
    {\[Sigma]11, \[Sigma]12, \[Sigma]13},
    {\[Sigma]21, \[Sigma]22, \[Sigma]23},
    {\[Sigma]31, \[Sigma]32, \[Sigma]33}
   } );
varList = ( {
   {\[Rho], \[Theta], z}
  } )
StressMatrix[[2, 3]]
varList[[1, 1]]
D[StressMatrix[[2, 3]], varList[[1, 1]]]

The code above returns zero but I would like it to return symbolically Partial derivative of Sigma[[2,3]] with respect to rho.
How can I do this?

A: You can use Inactivate,
Inactivate[D[StressMatrix[[2, 3]], varList[[1, 1]]]]

or Hold
Hold[D[StressMatrix[[2, 3]], varList[[1, 1]]]]

A: Various methods, including specified values (which need to be set after hold).
Clear[σ23]

StressMatrix = Map[Hold,
   {{σ11, σ12, σ13}, {σ21, σ22, σ23}, {σ31, σ32, σ33}}, {2}];
varList = {{ρ, θ, z}};

σ23 = 4 ρ^2;

expr = StandardForm[
   "∂" <> StringTake[ToString[StressMatrix[[2, 3]]], {6, -2}]/
    "∂" <> ToString[varList[[1, 1]]]];

symbolic = Inactive[D][ReleaseHold@StressMatrix[[2, 3]], varList[[1, 1]]];

result = D[ReleaseHold@StressMatrix[[2, 3]], varList[[1, 1]]];

Row[{expr, " = ", symbolic, " = ", result}]

Alternatively
symbolic2 = StringJoin["D[",
  StringTake[ToString[StressMatrix[[2, 3]]], {6, -2}], ",",
  ToString@varList[[1, 1]], "]"];

Row[{expr, " = ", symbolic2, " = ", ToExpression[symbolic2]}]

And finally
Clear[σ23]

StressMatrix =
  Map[HoldForm, {{σ11, σ12, σ13}, {σ21, σ22, σ23}, {σ31, σ32, σ33}}, {2}];
varList = {{ρ, θ, z}};

σ23 = 4 ρ^2;

expr = StandardForm[
   "∂" <> ToString[StressMatrix[[2, 3]]]/
    "∂" <> ToString[varList[[1, 1]]]];

symbolic = Inactive[D][ToString@StressMatrix[[2, 3]], varList[[1, 1]]];

result = D[ReleaseHold@StressMatrix[[2, 3]], varList[[1, 1]]];

Row[{expr, " = ", symbolic, " = ", result}]


text:
Q: Defining Safe zone I am developing an application which will send a alert message when that particular person goes out of the safe zone. I am using GPS to track the location information. Can anyone suggest me some ideas on how to set the safe zone.

A: Best way to do that; Calculating position and proximity on Mobile phone with Built in Proximity Alerts
You should create basic server application to keep all safe zones in your database. That server application also should generate some definition file (xml or json) to transfer all safe points to Android application.
Then your application can download that safe points from your server.
Example area definition json file;
{"areas": [
{"area-name": "Dangerous areas in NY",
 "danger-score": 5,
 "coordinates": [
    {"lat": "00.00000","lon": "00.00000", "radius": 2},
    {"lat": "00.00000","lon": "00.00000", "radius": 5},
    {"lat": "00.00000","lon": "00.00000", "radius": 10},
    {"lat": "00.00000","lon": "00.00000", "radius": 25}
]},
{"area-name": "Less Dangerous areas in NY",
"danger-score": 2,
 "coordinates": [
    {"lat": "00.00000","lon": "00.00000", "radius": 25},
    {"lat": "00.00000","lon": "00.00000", "radius": 50},
    {"lat": "00.00000","lon": "00.00000", "radius": 12},
    {"lat": "00.00000","lon": "00.00000", "radius": 45}
]}

]}
Your application can poll users current location in every X minute. (Just think about the battery life!) For calculating distance to safe points you can user Android built in function "Proximity Alerts".
Android Proximity Alert Reference
Example project which is pretty close to your case.
Happy coding...


text:
Q: Pylint AttributeError: 'module' object has no attribute 'append' I was configuring my new laptop (macbook pro) and everything was fine until I wanted to try my pylint command.
Traceback (most recent call last):
  File "/usr/local/bin/pylint", line 11, in <module>
    load_entry_point('pylint==1.6.4', 'console_scripts', 'pylint')()
  File "/usr/local/lib/python2.7/site-packages/pylint-1.6.4-py2.7.egg/pylint/__init__.py", line 13, in run_pylint
    Run(sys.argv[1:])
  File "/usr/local/lib/python2.7/site-packages/pylint-1.6.4-py2.7.egg/pylint/lint.py", line 1270, in __init__
    'init-hook')))
  File "/usr/local/lib/python2.7/site-packages/pylint-1.6.4-py2.7.egg/pylint/lint.py", line 1371, in cb_init_hook
    exec(value) # pylint: disable=exec-used
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute 'append'

From that I don't understand what's wrong with my pylint .... I tried a lot of things but as I'm not quite sure of what I've done at the end, I prefer to not list things.
Is there someone who already got it ? Someone who have an idea how to solve it?
Thanks for your help

A:
Hi, can you show the value of init-hook from the configuration file you are using? What happen is that you have configured, somehow, init-hook with some invalid code. You can see this in your traceback through the last exec call, which happens only when init-hook is provided. Seeing its value could lead to solving this problem. My intuition is that you probably have something as in ``init-hook="import sys; sys.append(some_path)"

Thanks to PCManticore, that was that, I had a .pylintrc in my home folder that had something weard for the init-hook value. I changed that and everything is working well now.


text:
Q: How to have function affect all objects in a class and not just the last one created I have an if statement that creates text objects by reading strings from array based on index position.
if (ifpn > 12){
     list = game.add.text(game.world.centerX+850, yfp, text, style);
      game.physics.arcade.enable(list);
      list.inputEnabled = true;
      list.input.enableDrag();
      list.events.onDragStart.add(startList, this);
      list.events.onDragStop.add(stopList, this);
    }

in that statement I have a listener event that fires a custom function out side of its scope.
function startList(selected){
  var posx = game.input.mousePointer.x;
  var posy = game.input.mousePointer.y;

  if (canc > 0){
    console.log('too many');
  }
  else {
    if (list.position.y > posy){
      list.position.y = list.position.y-40; //doesn't work as expected
    }
    else{
      console.log('too tall');
    }

    game.world.remove(selected);
  }
};

What this function does is when a user starts dragging the list object it gets the y position of the mouse and subtracts 40px form the height of any other list objects below the mouse at the point of the click.
But because list is defined as a global variable list = null; and then given a value out side the scope the statement only affects the last created list object due to closure.
How do I make the height properties of all the list objects change and not just the last one created?
please correct any errors you see in my codes or explanation of the issue.
Thanks


text:
Q: Mocking an Anonymous type parameter in Dapper and Filtering result by parameter's property I'm not very familiar with Moq and NUnit, that's why I'm struggling with this one. I'm using Dapper for my generic repository, and it's been injected into a service and, then, used to fulfil the logic. My problem is that I use it in a LinQ's Select passing a parameter from the previous Object. And I have no idea how to reflect that in the Mock...
This is my Service:
public class StudyService: IStudyService
    {
        private readonly ILogger<StudyService> _logger;
        private readonly IDataRepository _dataRepository;

        public StudyService(ILogger<StudyService> logger, IDataRepository dataRepository)
        {
            _logger = logger;
            _dataRepository = dataRepository;
        }
[...]
        // This is the method to test:
        public async Task<StudiesResponse> GetAllStudies()
        {
            StudiesResponse studies = new StudiesResponse();
            List<StudyReponse> list = new List<StudyReponse>();

            foreach (StudyDAO study in await _dataRepository.GetEntitiesAsync<StudyDAO>())
            {
                StudyReponse resp = new StudyReponse()
                {
                    StudyCode = study.StudyCode,
                    Participators = _dataRepository.GetEntitiesAsync<RoleUserDAO>(new { @StudyId = study.Id }).Result.Select(x => new ParticipatorsResponse()
                    {
                        UserEmail = _dataRepository.GetEntityAsync<UserDAO>(new { @Id = x.Id }).Result.Email,
                        RoleName = _dataRepository.GetEntityAsync<RoleDAO>(new { @Id = x.Id }).Result.Name
                    })
                };

                list.Add(resp);
            }

            studies.Studies = list;
            return studies;
        }
[...]
   }
}

As you can see the calls to retrieve UserEmail and RoleName are fed by the Select of the previous "_dataRepository.GetEntitiesAsync" This is what I don't have a clue how to mock...
This is my generic/anonymous repository:
   public class DataRepository : IDataRepository
    {
        private readonly IConfiguration _configuration;

        public DataRepository(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<IEnumerable<T>> GetEntitiesAsync<T>()
        {
            using(IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("SqlConnection")))
            {
                return await conn.GetListAsync<T>();
            }
        }
        public async Task<IEnumerable<T>> GetEntitiesAsync<T>(object query)
        {
            using (IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("SqlConnection")))
            {
                return await conn.GetListAsync<T>(query);
            }
        }

        public async Task<T> GetEntityAsync<T>(object query)
        {
            using (IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("SqlConnection")))
            {
                IEnumerable<T> result = await conn.GetListAsync<T>(query);
                return result.FirstOrDefault();
            }
        }
[...]

This is my test class:
[TestFixture]
    public class Tests
    {
        IEnumerable<StudyDAO> _studies;
        IEnumerable<UserDAO> _users;
        IEnumerable<RoleDAO> _roles;
        IEnumerable<RoleUserDAO> _roleUsers;

        [SetUp]
        public void Setup()
        {
            _studies = MockedDAOs.GetMockedStudies();
            _users = MockedDAOs.GetMockedUsers();
            _roles = MockedDAOs.GetMockedRoles();
            _roleUsers = MockedDAOs.GetMockedRoleUsers();
        }

        [Test]
        public void GetAllStudiesTest()
        {
            var _data = new Mock<IDataRepository>();
            _data.Setup(m => m.GetEntitiesAsync<StudyDAO>()).Returns(Task.FromResult(_studies));
            _data.Setup(m => m.GetEntitiesAsync<RoleUserDAO>(It.IsAny<Object>())).Returns(Task.FromResult(_roleUsers));
            _data.Setup(m => m.GetEntityAsync<UserDAO>(It.IsAny<Object>())).Returns(Task.FromResult(_users.Where(u => u.Id ==????)));
            _data.Setup(m => m.GetEntityAsync<RoleDAO>(It.IsAny<Object>())).Returns(Task.FromResult(_roles.Where(u => u.Id ==????)));

            var _logger = Mock.Of<ILogger<StudyService>>();
            StudyService _service = new StudyService(_logger, _data.Object);

            var result = _service.GetAllStudies();

            Assert.Pass();
        }
    }

And this is my "mocked" data constructors:
 public static class MockedDAOs
    {
        public static IEnumerable<UserDAO> GetMockedUsers()
        {
            List<UserDAO> users = new List<UserDAO>();
            users.Add(new UserDAO()
            {
                Id = 1,
                Email = "lordvaderr@galacticempire.com",
                Address = "Alderaan Sector 1234",
                LanguajePreference = "English",
                UpdateUser = "Admin"
            });
            users.Add(new UserDAO()
            {
                Id = 2,
                Email = "senatorpalpatine@galacticempire.com",
                Address = "Alderaan Sector 1233",
                LanguajePreference = "English",
                UpdateUser = "Admin"
            });
            users.Add(new UserDAO()
            {
                Id = 3,
                Email = "generalrommohc@galacticempire.com",
                Address = "Alderaan Sector 1232",
                LanguajePreference = "English",
                UpdateUser = "Admin"
            });
            users.Add(new UserDAO()
            {
                Id = 4,
                Email = "secenthsister@galacticempire.com",
                Address = "Alderaan Sector 1231",
                LanguajePreference = "English",
                UpdateUser = "Admin"
            });
            return users;
        }

        public static IEnumerable<StudyDAO> GetMockedStudies()
        {
            List<StudyDAO> studies = new List<StudyDAO>();
            studies.Add(new StudyDAO()
            {
                Id = 1,
                StudyCode = "order66",
                Company = "Galactic Empire",
                UpdateUser = "Admin"
            });

            return studies;
        }

        public static IEnumerable<RoleDAO> GetMockedRoles()
        {
            List<RoleDAO> roles = new List<RoleDAO>();
            roles.Add(new RoleDAO()
            {
                Id = 1,
                Name = "General Director",
                Curriculum = "Ruthless Management I",
                UpdateUser = "Admin"
            });
            roles.Add(new RoleDAO()
            {
                Id = 2,
                Name = "CEO",
                Curriculum = "Smoke and Mirrors I",
                UpdateUser = "Admin"
            });
            roles.Add(new RoleDAO()
            {
                Id = 3,
                Name = "Strategy Director",
                Curriculum = "Detecting Critical Targets",
                UpdateUser = "Admin"
            });
            roles.Add(new RoleDAO()
            {
                Id = 4,
                Name = "Deliver",
                Curriculum = "Silent Aproaches",
                UpdateUser = "Admin"
            });
            return roles;
        }

        public static IEnumerable<RoleUserDAO> GetMockedRoleUsers()
        {
            List<RoleUserDAO> roleUsers = new List<RoleUserDAO>();
            roleUsers.Add(new RoleUserDAO()
            {
                Id = 1,
                UserId = 1,
                RoleId = 1,
                StudyId = 1,
                UpdateUser = "Admin"
            });
            roleUsers.Add(new RoleUserDAO()
            {
                Id = 2,
                UserId = 2,
                RoleId = 2,
                StudyId = 1,
                UpdateUser = "Admin"
            });
            roleUsers.Add(new RoleUserDAO()
            {
                Id = 3,
                UserId = 3,
                RoleId = 3,
                StudyId = 1,
                UpdateUser = "Admin"
            });
            roleUsers.Add(new RoleUserDAO()
            {
                Id = 4,
                UserId = 4,
                RoleId = 4,
                StudyId = 1,
                UpdateUser = "Admin"
            });
            return roleUsers;
        }

        public static StudiesResponse GetMockedStudiesResponse()
        {
            List<ParticipatorsResponse> participatorsResponse = new List<ParticipatorsResponse>();
            participatorsResponse.Add(new ParticipatorsResponse(){
                UserEmail = "lordvaderr@galacticempire.com",
                RoleName = "General Director"
            });
            participatorsResponse.Add(new ParticipatorsResponse()
            {
                UserEmail = "senatorpalpatine@galacticempire.com",
                RoleName = "CEO"
            });
            participatorsResponse.Add(new ParticipatorsResponse()
            {
                UserEmail = "generalrommohc@galacticempire.com",
                RoleName = "Strategy Director"
            });
            participatorsResponse.Add(new ParticipatorsResponse()
            {
                UserEmail = "secenthsister@galacticempire.com",
                RoleName = "Deliver"
            });

            List<StudyReponse> studyResponse = new List<StudyReponse>();
            studyResponse.Add(new StudyReponse()
            {
                StudyCode = "order66",
                Participators = participatorsResponse
            });

            return new StudiesResponse()
            {
                Studies = studyResponse
            };
        }
    }

I'm out of ideas and I can't find any example with a scenario like this...
EDIT:
Ok, I found a post with something that I thought can be used:
Test:
        [Test]
        public void GetAllStudiesTest()
        {
            var _data = new Mock<IDataRepository>();
            _data.Setup(m => m.GetEntitiesAsync<StudyDAO>()).Returns(Task.FromResult(_studies));
            _data.Setup(m => m.GetEntitiesAsync<RoleUserDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _roleUsers.Where(x => x.Id == obj.Id));
            _data.Setup(m => m.GetEntityAsync<UserDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _users.Where(x => x.Id == obj.Id).FirstOrDefault());
            _data.Setup(m => m.GetEntityAsync<RoleDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _roles.Where(x => x.Id == obj.Id).FirstOrDefault());

            var _logger = Mock.Of<ILogger<StudyService>>();
            StudyService _service = new StudyService(_logger, _data.Object);

            var result = _service.GetAllStudies();

            Assert.True(comparator.Compare(result, MockedDAOs.GetMockedStudiesResponse()).AreEqual);
        }

But it's not working. With this code, the first call to recover the IEnumerable returns 0 results... I'll keep looking. Any help will be appreciated.

A: I managed to solve the issue. The correct code for the Test is:
        [Test]
        public void GetAllStudiesTest()
        {
            var _data = new Mock<IDataRepository>();
            _data.Setup(m => m.GetEntitiesAsync<StudyDAO>()).Returns(Task.FromResult(_studies));
            _data.Setup(m => m.GetEntitiesAsync<RoleUserDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _roleUsers.Where(x => x.StudyId == (int)obj.GetType().GetProperty("StudyId").GetValue(obj, null)));
            _data.Setup(m => m.GetEntityAsync<UserDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _users.Where(x => x.Id == (int)obj.GetType().GetProperty("Id").GetValue(obj, null)).FirstOrDefault());
            _data.Setup(m => m.GetEntityAsync<RoleDAO>(It.IsAny<Object>())).ReturnsAsync((Object obj) => _roles.Where(x => x.Id == (int)obj.GetType().GetProperty("Id").GetValue(obj, null)).FirstOrDefault());

            var _logger = Mock.Of<ILogger<StudyService>>();
            StudyService _service = new StudyService(_logger, _data.Object);

            StudiesResponse result = _service.GetAllStudies().Result;
            StudiesResponse expectedResult = MockedDAOs.GetMockedStudiesResponse();

            var comparation = comparator.Compare(result, expectedResult);

            Assert.True(comparation.AreEqual);
        }

As you can see I'm using KellermanSoftware.CompareNetObjects to do the assertion, that's why I had to modify the method to test, parsing the Participators from a LinQ WhereSelect response to a List, so the comparator would not see a difference with my constructed expected response.
This is the slightly different method code:
        public async Task<StudiesResponse> GetAllStudies()
        {
            StudiesResponse studies = new StudiesResponse();
            List<StudyReponse> list = new List<StudyReponse>();
            foreach (StudyDAO study in await _dataRepository.GetEntitiesAsync<StudyDAO>())
            {
                StudyReponse resp = new StudyReponse()
                {
                    StudyCode = study.StudyCode,
                    Participators = _dataRepository.GetEntitiesAsync<RoleUserDAO>(new { @StudyId = study.Id }).Result.Select(x => new ParticipatorsResponse()
                    {
                        UserEmail = _dataRepository.GetEntityAsync<UserDAO>(new { @Id = x.Id }).Result.Email,
                        RoleName = _dataRepository.GetEntityAsync<RoleDAO>(new { @Id = x.Id }).Result.Name
                    }).ToList()
                };
                list.Add(resp);
            }
            studies.Studies = list;
            return studies;
        }


text:
Q: React-native: Handling multiple element selection while using redux I have 8 <TouchableWithoutFeedback> elements in a grid form. They are not dynamically rendered using map.
 this.props.selectCell('rain')}>
<TouchableWithoutFeedback  onPress={()=>this.props.selectCell('rain')}>
    <Row  style={[styles.orangish,styles.cell]}>
        <Image source={Rain} />
    </Row>
</TouchableWithoutFeedback>

The idea is to select one onPress.
action
export const selectCell = (cellId) => {
    console.log(cellId);
    return {
        type: 'select_cell',
        payload: cellId
    };
}

Reducer
export default (state= {}, action) => {
  switch(action.type) {
    case 'select_cell': {
      //trying to figure out what to do here

  }
};

1) How do I toggle the selection in reducer?
2) How to I render the a new image based on the state?

A: Have a selectedCellId property in the reducer state and set it as follows:
export default (state= {}, action) => {
  switch(action.type) {
    case 'select_cell': {
      return {
         ...state,
         selectedCellId: action.payload
     };
  }
};

An alternative is to have an array of 8 cells with selected = false.
const defaultState = {
  cells: [
    { selected: false },
    { selected: false },
    { selected: false },
    { selected: false },
    { selected: false },
    { selected: false },
    { selected: false },
    { selected: false }
  ]
};

Then in the reducer,
export default (state= defaultState, action) => {
  switch(action.type) {
    case 'select_cell': {
      let { cells } = state;
      cells = cells.slice();
      cells[action.payload] = { selected: true };
      return {
         ...state,
         cells
     };
  }
};

If you have named cells, then make the cells collection an object map instead of an array.