text:
Q: If with multiple or statements creating endless loop I have a loop that goes down a column and identifies if the cell equals to one of the listed security types. If it does not, it will cut and paste the data offset 1 column to the left. Sometimes the data is offset 1-3 columns which is why i added the i = i - 1 to check the same row until it satifies the if. This code leads to 2 issues:
1.) Is there a more simple line of code for the If statement with multiple or's?
2.) This code works in sections but when it runs on the whole sheet (~29K rows) it enters into an endless loop. Any ideas why this happens?
LastCashrow = Sheets("Cash Data").Range("A" & Sheets("Cash Data").Rows.Count).End(xlUp).Row

For i = 8 To LastCashrow

SecType = Left(Cells(i, 5), 2)

  If SecType = "aw" Or SecType = "ca" Or SecType = "cb" Or SecType = "cd" Or SecType = "cl" Or SecType = "cp" Or SecType = "cs" Or SecType = "cv" Or SecType = "ep" _
                Or SecType = "ex" Or SecType = "fi" Or SecType = "fm" Or SecType = "gb" Or SecType = "gm" Or SecType = "hf" Or SecType = "lp" Or SecType = "mb" _
                Or SecType = "mf" Or SecType = "oa" Or SecType = "pf" Or SecType = "pr" Or SecType = "ps" Or SecType = "pt" Or SecType = "re" Or SecType = "rl" _
                Or SecType = "tb" Or SecType = "tp" Or SecType = "ut" Or SecType = "wt" Or SecType = "zb" Or SecType = "zt" Then

  ElseIf IsEmpty(SecType) = "True" Then
        Exit For

  Else
        Set Shift = Range(Cells(i, 5), Cells(i, 17))
        Shift.Cut
        Cells(i, 4).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        i = i - 1

  End If

Next i

A: 1.) Is there a more simple line of code for the If statement with multiple or's?
Yes. I'd start by improving your code this way:
' Declare all of your variables explicitly
Dim LastCashRow As Long
Dim i As Long
Dim SecType As String
Dim cell As Range

Dim validSecTypes() As String
validSecTypes = Split("aw,ca,cb,cd", ",") ' write all of your values here...
' returns an array of strings: ["aw", "ca", "cb", "cd"]

LastCashRow = 12

For i = 8 To LastCashRow
    Set cell = Cells(i, 5)
    If IsEmpty(cell) Then Exit For ' This is really the first thing to check for.

    SecType = Left(cell.Value, 2)

    If ArrayContains(validSecTypes, SecType) Then
        MsgBox SecType & " is IN!"
    Else
        MsgBox "This is OUT: " & SecType
        'your lines of code go here
    End If

Next i

This uses the helper function:
Function ArrayContainsValue(arr As Variant, val As Variant) As Boolean
    ArrayContainsValue = (UBound(Filter(arr, val)) > -1)
End Function

2.) This code works in sections but when it runs on the whole sheet (~29K rows) it enters into an endless loop. Any ideas why this happens?

No. We'd have to see your sheet.
But are you really sure it's endless? Because processing that many rows using your code as it currently is written can take some time.
As I had guessed, your code is just taking a long time to run.
The culprit is likely this bit of code:
    Shift.Cut
    Cells(i, 4).Select
    ActiveSheet.Paste

A: You could do this to simplify the multiple or condition:
If InStr(1, "/aw/ca/cb/cd/cl/cp/cs/cv/ep/ex/fi/fm/gb/gm/hf/lp/mb/mf/oa" + _
            "/pf/pr/ps/pt/re/rl/tb/tp/ut/wt/zb/zt", SecType) > 1 Then


text:
Q: Use git for two branch think I am going to use these three files in Master Branch
MASTER :
index.php

  hello

test.php
img.jpeg

now I create a branch from Master
NewBranch :
index.php

     hello

test.php
img.jpeg

and now I will edit Master index.php file, and I will add two lines of code to master branch
MASTER :
index.php

  hello
  test

good

and I will change some code in NewBranch
NewBranch :
index.php

     hello

this is new branch line

I want to update NewBranch so I will have my own edited lines on New Branch and also updated lines on Master Branch
NewBranch : (should be like as below)
index.php

     hello

this is new branch line

     test

good

How can I achieve that? I have used netbeans Pull and Fetch, but did not worked. I also do not want to use git submodule ( as I do not have separate folder )

A: *

*You changes on both the branches should be "committed". Only changing will do no good.

*Then you can rebase your NewBranch over master (git rebase master NewBranch)

*Now you new branch has changes of itself and that of master. But master will have only its changes.

For more details on rebase please refer this.

A: These are the steps (assuming that you are using gitBash):
git checkout newbranch

do the changes for newbranch
    git commit -a -m "Your message"
git checkout master

do the changes for master
git commit -a -m "Your message"

now merging
git checkout newbranch
git merge master
git push
git checkout master
git merge newbranch
git push
gitk //you should see that both are at the same level in the git tree

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does one generate a side pane of contents in pdf using Latex? Like the way it is mentioned here: http://www.latex-community.org/forum/viewtopic.php?f=5&t=7400
It says use hyperref package but doesn't give a straight example. Can you please help?

A: I am pretty sure that the bookmark pane is meant here.
Use the hyperref package (or bookmark, for more sophisticated setups).
The level of bookmarks can be controlled with the tocdepth counter and the specific \toclevel@chapter etc. commands.
In order to show the bookmark pane opened when the .pdf file is opened, use bookmarkopened=true as an option to the hyperref package. Bookmarks appear numbered with bookmarksnumbered=true.
If more entries to the bookmark shall be done, use \pdfbookmark, \belowpdfbookmark and \currentpdfbookmark from hyperref or the more general \bookmark command from bookmark.
\documentclass{book}

\usepackage[bookmarksopen=true,bookmarksnumbered=true,bookmarksopenlevel=4]{hyperref}

\setcounter{tocdepth}{3}
\begin{document}
\tableofcontents

\chapter{Introduction}

\section{First section of \chaptername{} \thechapter}

\subsection{First subsection}

\subsubsection{First subsubsection}

\subsubsection{Second subsubsection}

\subsection{Second subsection}

\subsubsection{First subsubsection}

\subsubsection{Second subsubsection}

\chapter{Another chapter}

\section{First section of \chaptername{} \thechapter}

\subsection{First subsection}

\subsubsection{First subsubsection}

\subsubsection{Second subsubsection}

\subsection{Second subsection}

\subsubsection{First subsubsection}

\subsubsection{Second subsubsection}

\end{document}


text:
Q: CSS bug causes elements to re-render when scrolling I'm trying to figure out why my third element div.servicespost re-renders when you scroll past it.
See here. The third post under "What's on" re-renders on a new row as you scroll through it. I can't give any other information about it. Has someone seen this before?
The inspector shows nothing out of the ordinary, or any errors at all.

A: There are a few factors that are causing issues:
1) There are margins at play that are being stripped when you add the .onScreen class. This wouldn't necessarily be a problem if the classes were all added and removed at the same time, but that leads to the second problem.
2) The columns are not equal heights, which means the .onScreen class is being removed at different times.
The end result is the third column (.postwrapper-3) having it's .onScreen class still active while the other two don't. Since it uses a negative margin to stay aligned properly and the .onScreen class strips that negative margin, it gets shifted to a new line.
Simple fix, remove the margin clearing from the .onScreen class:
#services .onScreen {
  margin: 0; //remove this
  opacity: 1;
}


text:
Q: imageURI from firebase database crash I am building a simple message app, at the moment I would like to view the users image next to their text.
I am trying to get the users image from the firebase database.
However, whenever I try to getValue() of the an image the app crashes.
If I choose to replace imageURI with an image link, then I see it works with that link.
08-27 23:14:02.392 4817-4817/com.myproj.blogapp E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                         at com.myproj.blogapp.MessageAdapter$1.onDataChange(MessageAdapter.java:79)
                                                                         at com.google.android.gms.internal.to.zza(Unknown Source)
                                                                         at com.google.android.gms.internal.vj.zzHX(Unknown Source)
                                                                         at com.google.android.gms.internal.vp.run(Unknown Source)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)

@Override
public void onBindViewHolder(final MessageViewHolder viewHolder, final int index) {

    final Message c = messagesList.get(index);

    final String sender = c.getFrom();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(sender);
    databaseReference.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            imageUrl = dataSnapshot.child("image").getValue().toString(); //error on this line
            viewHolder.setUserimage(context,imageUrl);

            String name = dataSnapshot.child("name").getValue().toString();
            viewHolder.displayName.setText(name);

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }

    });

    viewHolder.messageText.setText(c.getMessage());
    viewHolder.time.setText(EpochtimeToDateAndTimeString(c.getTime()));
}

Database Image

A: Your data is not complete. Look at the rust user. It has no image...
You must either use a proper null check after getChild(String path) before you toString it
Or use hasChild(String path) before getting it at all
In the case where the value is null or the child doesn't exist, you might want to consider having a default image
Note: you could be using getValue(String.class) on the children instead of using toString, or use a POJO on the whole initial Snapshot instead of fetching individual children
You'll also want to implement onCancelled so you can see your Firebase errors


text:
Q: RPC lib for Python What RPC framework/lib for python could you recommend me? The architecture is client-server, server should stand high load, and connection tunneled over ssl. I've googled such things as pyro, twisted.spread, rpyc.

A: The are some alternatives to Pyro if you really need high loads:

*

*http://pypi.python.org/pypi/jpc (see more on http://winpdb.org/2009/11/enter-jpc/)

*From the same guy: http://code.google.com/p/rfoo/
Both are really fast. The second one needs Cython, however; so you can try jpc on the first place.

A: You may like rpclib that is good presented in this lighting talk from PyCon 2012.

A: Look at http://rpyc.sourceforge.net/index.html It is very nice micro RPC library with async calls, SSL, etc.


text:
Q: Bold ExecCommand in Firefox not working I was using execCommand in order to make the text on my WYSIWYG editor bold. The command was working fine but now for some reason in Firefox 14.0.1 it stopped working. What happens is that if I have a text and make it bold and then save, I get something like this, (this is what I want to have, so so far it is ok):
 <span font-weight: bold;">hello</span>

The problem now is that if I select again the text in order to remove the bold, Firefox does not understand the font-weight attribute so it adds the b tag again in my text. This is not happening in Firefox 10, Chrome or IE for example. There the browser understands and just remove the font-weight.
So my question is if someone knows something about that?
Thanks in advance


text:
Q: Best way to store PHP session from iPhone website when added to homescreen? I have a website/webapp where you can login and it starts a php session.
If a user adds the site to their homescreen they have to log in every time they start the app.
I know this is a well know issue but I can't find a good and complete solution. I want the users to be able to open the app and if they have been logged in before they should become logged in from start.
I have read a bit about local storage which seems to maybe be something but I'm worried about the security issues of storing something locally. I don't want an user to pose as another. Maybe you can encrypt the stored values somehow?
Does anyone know how I can solve this?

A: Seems obvious.... is there a reason you haven't tried Cookies?
Store the session data in a database on your server, with some sort of hash, then simply pass that hash to the user in a cookie so they can retrieve it when they get back to your site.


text:
Q: Are $\mathrm{arccot}(x)$ and $\arctan(1/x)$ the same function? In my textbook it asks for me to:
Prove that there is no constant $C$ such that $\text{arccot}(x) - \text{arctan}(\frac{1}{x}) = C $ for all $x \ne 0$. Explain why this does not violate the zero-derivative theorem.
But I believe I have found such a $C$, i.e. $C =0$!
I even asked WolframAlpha (http://www.wolframalpha.com/input/?i=arccot%28x%29+-+arctan%281%2Fx%29) which corroborates my answer.
This question appears in Apostol's Calculus Volume I, Second Edition: Exersize 6.22-11b
Edit: Mathematica's definition of arccot is different from the one in my textbook. Apostol's arccot maps a real number into $(0, \pi)$ while Mathematica's maps a real number into $(-\pi/2, \pi/2)$ Here they are super-imposed: http://www.wolframalpha.com/input/?i=integral%28-1%2F%281%2Bx%5E2%29%29+%2B+pi%2F2%3B+arccot

A: This is not a rigorous proof, it is intuitive one.
Let $y = \arctan\left(\dfrac1x\right)$ then
$$
\begin{align}
\tan(y) &= \frac1x\\
\frac1{\tan(y)} &= x\\
\cot(y) &= x\\
y &= \text{arccot}(x)\\
\arctan\left(\frac1x\right) &= \text{arccot}(x)\\
\arctan\left(\frac1x\right) - \text{arccot}(x)&=0.
\end{align}
$$
It holds for $x \neq 0, \ x\in\mathbb{R}$.

A: So we'll take your textbook's definition:
$$
\mbox{arccot}(x)=\frac{\pi}{2}-\arctan(x).
$$
Then
$$
\lim_{0^+} \mbox{arccot} (x)=\frac{\pi}{2}=\lim_{0^+} \arctan(1/x)
$$
while
$$
\lim_{0^-} \mbox{arccot} (x)=\frac{\pi}{2}=-\lim_{0^-} \arctan(1/x).
$$
Since its derivative is $0$ on $\mathbb{R}^*$,
$$
\mbox{arccot}(x)-\arctan(1/x)=0
$$
for all $x>0$ while
$$
\mbox{arccot}(x)-\arctan(1/x)=\pi
$$
for all $x<0$.
This does not contradict the zero-derivative theorem because the function is not defined at $0$, so its domain is not connected.


text:
Q: Getting most recent record through another related table How would I create a MySQL command to get the most recent categories that have had a post favorited?
I am attempting to join the tables and group them, but am unsure how to limit the results to a maximum number of categories.
So to give a simple example of what I'm trying to do:
Users (id)
Favorites (id, last_updated, post_id, user_id)
Posts (id, title, category_id)
Categories (id, name)

And then for sql:
SELECT favorites.*, posts.category_id
FROM favorites
INNER JOIN posts ON favorites.user_id = 1 AND favorites.post_id = posts.id
INNER JOIN categories ON posts.category_id = categories.id
GROUP BY categories.id, favorites.id
ORDER BY favorites.last_updated DESC

Obviously, this statement is not working as intended, as it returns many results for each category, instead of one for each category - the most recent.

A: You can't GROUP BY a field not present in SELECT.
Here is a solution assuming that you want this only for user_id = 1:
SELECT c.id, MAX(f.last_updated)
FROM favorites f
INNER JOIN posts p ON (f.user_id = 1 AND f.post_id = p.id)
INNER JOIN categories c ON (p.category_id = c.id)
GROUP BY c.id
ORDER BY MAX(f.last_updated) DESC

With this you get the IDs of the desired categories. You can join the result with categories again to get the rest of the columns.


text:
Q: PCA on data having more dimensions than observations I have a 73 by 426 matrix, where 73 is the number of my observations, and 426 is the number of my features/dimensions. When I perform the PCA, I expect to get a 73 by 426 score matrix; instead, I get a 73 by 72 matrix. I assume this is because I have more dimensions than observations. Is there a way to overcome this problem?
Here is my code in Matlab:
[coeff,score,~,~,explained] = pca(class1Sgn);

A: Recall that principal components are, by construction, orthogonal. Your original data has a rank of 73 at most, so you cannot derive more than 73 principal components from it. In fact you will lose a degree of freedom yielding 72 PC's.
But what in the world do you plan on doing with 72 principal components?
I can't suggest whether to go this route without knowing your use case, but using a handful of principal components (the first 5-10 for instance) out of your 72 is done in some cases. Things can go wrong in PCA, even for the first few PC's, if your eigenvalues/scree plot do not show those first PC's having much larger eigenvalues than the others.
There is no way for PCA to give you a 73 by 436 score matrix. You could force factor analysis to do it, but I don't think you would yield anything useful. If going the PCA route, you could bootstrap several estimates to test the stability of your first few principal components.
https://arxiv.org/pdf/0911.3827.pdf
https://stats.stackexchange.com/a/45859/69090

A: Took some digging, but if you look at the MATLAB documentation it uses the SVD function to accomplish this task. If you look at the SVD documentation it states:
https://www.mathworks.com/help/matlab/ref/svd.html
[m-by-n matrix A]

m > n — Only the first n columns of U are computed, and S is n-by-n.

m = n — svd(A,'econ') is equivalent to svd(A).

m < n — Only the first m columns of V are computed, and S is m-by-m.

And then if you take what @user3348782 said you lose 1 degree of freedom when you do PCA and the result is a m-by-(m-1) matrix.


text:
Q: Почему некоторые места прозрачные, при импорте модели из Substance Painter? Мы создаем игру на Unity и возникла небольшая проблема. При импорте модели некоторые места прозрачные, что не очень хорошо смотрится.

Можете помочь с этим?

A: Зачастую, по умолчанию, поверхности односторонние (то есть полигоны "смотрят" в одну сторону и с нее видны, а с другой стороны - нет). Вам надо где-то выставить галку "двухстороннести" / "Doublesided".


text:
Q: My Google recaptcha verification is not working I am using this code to work recaptcha services. But it tells me you are a bot.
I tried php server side integration but it does not work.
Here is html
<form id="contact-form" name="contact-form" action="submithr.php" method="POST">

                                            Subject
                                            <input type="text" id="subject" name="subject" class="form-control" required>

                                            Select Category
                                            <select type="text" id="category" name="category" class="form-control">
                                                <option value="1">Suggestion</option>
                                                <option value="2">Claim</option>
                                                <option value="3">Help</option>
                                            </select>

                                            Your message
                                            <textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required></textarea>

                                    Send

                            </form>

And here is php code
<?php
$subject = $_POST['subject'];
$category = $_POST['category'];
$message = $_POST['message'];

$secretKey = "---My Secret Key---";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];

$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);

if ($response->success) {
    echo "";
}
else{
        echo "";
}
?>

If check box is checked correctly it should alert me that i checked it correctly But even if i check it correctly it always alert me you are a bot.

A: Set this file in your html page containinig the form

Then set the google div box before your submission button

here is the php code
<?php

$subject = $_POST['subject'];
$category = $_POST['category'];
$message = $_POST['message'];

        // Ensure that recaptchabox is not empty
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){

            $secretKey = 'Your_reCAPTCHA_Secret_Key_goes here';

            // send request and Verify the reCAPTCHA via g_recaptcha_response post parameter.
            $verifyRequest = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
            $result = json_decode($verifyRequest);

            // Check if captcha enterd is valid
            if($result->success){
                // send your form data and update database
               echo "";

            }else{
               echo "";
            }

        }else{
            echo "Recaptcha box cannot be empty";
        }

?>


text:
Q: Comment xml segment using shell script / command I am trying to do a shell script with 2 parameters.
xmlcomment -c cholo

or
xmlcomment -u cholo

Given the following xml file,
<?xml version="1.0"?>
<guyList>
  <guy>
    <name>paco</name>
    <fullname>Paco Tilla</fullname>
    <theme>paco</theme>
  </guy>
  <guy>
    <name>cholo</name>
    <fullname>Cholo Cote</fullname>
    <theme>cholocote</theme>
  </guy>
  <guy>
    <name>temo</name>
    <fullname>Temo Lesto</fullname>
    <theme>temol</theme>
  </guy>
</guyList>

The first comments out the block "<guy>" that contains a "<name>paco</name>" , resulting in the following file change.
<?xml version="1.0"?>
<guyList>
<guy>
    <name>paco</name>
    <fullname>Paco Tilla</fullname>
    <theme>paco</theme>
  </guy>
<!--
  <guy>
    <name>cholo</name>
    <fullname>Cholo Cote</fullname>
    <theme>cholocote</theme>
  </guy>
-->
  <guy>
    <name>temo</name>
    <fullname>Temo Lesto</fullname>
    <theme>temol</theme>
  </guy>
</guyList>

The second example just uncomments that same block (if commented) like presented in the first XML.
Any Idea on a good approach to do this? sed? some other XML editor?
Thanks

A: You can use an XSLT processor for this, like xsltproc:
<xsl:template match="guy[name='cholo']">
  <xsl:comment>
    <xsl:apply-templates select="@*|node()" />
  </xsl:comment>
</xsl:template>

This approach does not fully reproduce the original XML structure, but it comments out the appropriate guy section.
The output is:
<guyList>
    <guy>
        <name>paco</name>
        <fullname>Paco Tilla</fullname>
        <theme>paco</theme>
    </guy>
    <!--
      cholo
      Cholo Cote
      cholocote
    -->
    <guy>
        <name>temo</name>
        <fullname>Temo Lesto</fullname>
        <theme>temol</theme>
    </guy>
</guyList>

A: Can be done with sed (maybe not the best approach). The scripts are the same, just replacing line addresses and what substitute in each case.
sed '/<guy>/ {
    :a
    N
    /<\/guy>/ {
            /cholo/ {
                    s/^/<!--\n/
                    s/$/\n-->/
            }
    p
    d
    }
    ba
}' file-without-comment
<?xml version="1.0"?>
<guyList>
<guy>
    <name>paco</name>
    <fullname>Paco Tilla</fullname>
    <theme>paco</theme>
  </guy>
<!--
  <guy>
    <name>cholo</name>
    <fullname>Cholo Cote</fullname>
    <theme>cholocote</theme>
  </guy>
-->
  <guy>
    <name>temo</name>
    <fullname>Temo Lesto</fullname>
    <theme>temol</theme>
  </guy>
</guyList>

sed '/<!--/ {
    :a
    N
    /-->/ {
            /cholo/ {
                    s/<!--\n//
                    s/\n-->//
            }
    p
    d
    }
    ba
}' file-with-comment
<?xml version="1.0"?>
<guyList>
<guy>
    <name>paco</name>
    <fullname>Paco Tilla</fullname>
    <theme>paco</theme>
  </guy>
  <guy>
    <name>cholo</name>
    <fullname>Cholo Cote</fullname>
    <theme>cholocote</theme>
  </guy>
  <guy>
    <name>temo</name>
    <fullname>Temo Lesto</fullname>
    <theme>temol</theme>
  </guy>
</guyList>

EDIT 23/mar/2020
The script above works with GNUsed.
In BSD sed (and Mac sed?) it works with a escaped literal new line.
sed '/<guy>/ {
    :a
    N
    /<\/guy>/ {
            /cholo/ {
                    s/^/<!--\
/
                    s/$/\
-->/
            }
    p
    d
    }
    ba
}' file-without-comment

But it doesn't work with the "uncomment" script, I don't know why.
I can be done with this sed script:
sed -E '/<!--|-->/d' file-with-comment


text:
Q: How can I select data from a json object in mysql/php? I'm sending JSON to my server via jQuery's ajax method.
Here's my jquery, and im pretty sure this is fine:
function stuffs() {
    this.fname = document.getElementById("fname").value;
    this.lname = document.getElementById("lname").value;
    this.email = document.getElementById("email").value;
}
$(function() {
function ajaxhelper(data){
    //console.log(JSON.stringify(data));
    //this returns "{"fname":"mike","lname":"smith","email":"a@a.a"}" which is what i expect
        $.ajax({
        url: 'postdb.php',
        type: 'POST',
        data: {data : JSON.stringify(data)},
        success: function(data) {
            console.log(JSON.stringify(data));
            console.log("Success");
        },
        error: function(e) {
            console.log(e);
        }

    });
}
$("form").on('submit', function(e){
    e.preventDefault();
    var data = new stuffs();
    ajaxhelper(data);
    //window.location = "postdb.php";
    });
    });
</script>

I get back an 500 server error. Here's my php code. (yes i'm only sending it an fname that i've preloading into my database, $con is valid i just didnt share the code to connect to my database)
$obj = json_decode($_POST['data']);

$sql = "SELECT * FROM testtable WHERE fname = \"$obj->{'fname'}\"";
$query = $con->query($sql);

I think my sql is incorrect due to the quotes? This is where im stuck.

A: Try using $obj->fname instead of $obj->{'fname'}.

A: Here is the correct syntax for your SQL Statement
$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";


text:
Q: how to save the mode which is list as csv file I am trying to  save list as .csv file
I am using the "psych" to obtain cohen.kappa. I have the data(named as ic2) which have 1000 observations and 51 variables.
kappa <- function(ic2, colN) {
    tab <- vector("list", colN)
    for (i in seq_len(ncol(ic2))) {
    tab[[i]]=cohen.kappa(res[[i]])}
    tab}
a=kappa(ic2, ncol(ic2))
a

The output will be :
[[1]]
Call: cohen.kappa1(x = x, w = w, n.obs = n.obs, alpha = alpha)

Cohen Kappa and Weighted Kappa correlation coefficients and confidence boundaries
                 lower estimate upper
unweighted kappa     1        1     1
weighted kappa       1        1     1

 Number of subjects = 1000

[[2]]
Call: cohen.kappa1(x = x, w = w, n.obs = n.obs, alpha = alpha)

Cohen Kappa and Weighted Kappa correlation coefficients and confidence boundaries
                 lower estimate upper
unweighted kappa  0.87      0.9  0.93
weighted kappa    0.87      0.9  0.93

 Number of subjects = 1000

so there are 51 outputs. And I want to save 51 output as one csv file. How could I save it?
I would like to save the output has 3 columns and two rows( row's names are unweighted kappa and weighted kappa; column's names are lower, estimate, and upper), because I will extract the estimate value from the output.

A: It's not clear to me what the other rating is that you are comparing to each of the 51 columns.  But here is an example that may help you do what you want.  I create a fake data frame like yours but smaller, only 10 rows and 5 columns.  I use the numbers from 1 to 10 as a reference rating for which Cohen's kappa is computed for each row.  The results are saved in a data frame with the same number of rows as the original data frame had columns, and 6 variables representing the lower, estimate, and upper of the unweighted and weighted kappa, respectively.
# fake data
ic2 <- data.frame(matrix(sample(1:5, size=10*5, replace=TRUE), nrow=10))

# reference rating ?
ref <- 1:nrow(ic2)

# Cohen's kappa
results <- data.frame(t(apply(ic2, 2, function(x) as.numeric(t(cohen.kappa(cbind(ref, x))$confid)))))
names(results) <- c("klo", "k", "kup", "kwlo", "kw", "kwup")
results


text:
Q: Maven - Run JUnit Testsuite in module I have 3 Projects:

*

*ParentProj (parent of A+B)

*ProjA (is a module of ParentProj, contains sources)

*ProjB (is a module of ParentProj, contains sources and tests)

Build order is: 1. ParentProj, 2. ProjA, 3. ProjB (could not be changed!)
I want to tell maven to execute a TestSuite that is located in ProjB.
If I run the build with this command: mvn clean -e test -Dtest=AllServiceTests, the build will fail because maven could not find the "AllServiceTests"-class in ProjA, which is build before ProjB.
Is there any solution for this problem? (Changing the build order is no solution)

A: I just found the solution:
clean install test -Dtest=myTestSuite -DfailIfNoTests=false

-DfailIfNoTests=false will force maven to continue with the build if ProjA contains no Test classes.
That finally fixed my problem.

A: Have you looked into the --also-make and --projects options?
$ mvn --help

usage: mvn [options] [<goal(s)>] [<phase(s)>]

Options:
 -am,--also-make                        If project list is specified, also
                                        build projects required by the
                                        list

 -pl,--projects <arg>                   Comma-delimited list of specified
                                        reactor projects to build instead
                                        of all projects. A project can be
                                        specified by [groupId]:artifactId
                                        or by its relative path.

Then I suppose this might work:
mvn clean test -pl ProjB -am -Dtest=AllServiceTests

Please post back and let us know if that works!  I'm really curious. :)

A: The simpliest solution is to change to the ProjB directory and execute your command line there.


text:
Q: Facebook App without owner Suddenly I couldn't find my Facebook App in Developer Apps section, I used my 'App Access Token' to get the app roles through Facebook Graph API but the surprise was that my app has no owner, I think someone got my 'App Access Token' and removed all the admins from the app, The problem is [My Facebook App has no owner]. any ideas to get it back ?
Facebook Applications API

A: This is obviously a graph API bug, because 'Must specify at least one developer who has administrator permission.' error dialog would pop up if you delete the last admin(you) on https://developers.facebook.com/apps/APP_ID/roles. Report the bug on https://developers.facebook.com/bugs, and also ask them how to contact for recover your apps.


text:
Q: How to Compare Two variable of HANDLE type I have a variable of HANDLE type.
First HANDLE variable is a process HANDLE (with name hProcess) that does not have PROCESS_QUERY_INFORMATION access right.
Second variable is a process HANDLE (with name hwndProcess) too that I have opened via OpenProcess function and have PROCESS_QUERY_INFORMATION access right. I am sure both processes should have same handle.
But when i compare them as below, it returns false;
if (hProcess==hwndProcess) {do something}
How shall I do it?

A: There is not an explicit way to check whether two handles refer to the same process. The only way would be to query the process information and check that, e.g. using GetProcessId on each handle to check the process IDs.
If you don't have the necessary access rights to call the desired query functions then you can try calling DuplicateHandle to get a new handle with more access rights. However, if this fails then you have no way of telling whether the handles are to the same process or not.

A: hProcess must not hold the ProcessHandle of the Process that will be closed. It can and will most times be NULL. I'm doing something similar to get the PIDs of terminated processes.
if((hProcess == NULL) || (hProcess == GetCurrentProcess())){
        pid = GetCurrentProcessId();
     } else {
        pid = ProcessHandleToId(hProcess);
     }
Are your sure, that it's an access rights problem and your function doesn't fail, because the handle is NULL?

A: The Windows 10 SDK has CompareObjectHandles(HANDLE, HANDLE) which returns TRUE if the handles refer to the same underlying kernel object.
And you don't have to worry about access rights.


text:
Q: Impact of fragmentation in Games I'd like to ask, if you install about 15 GB (2 - 3 games) on a system partition (and your pagefile.sys is located on the other drive), could it cause the fragmentation to occur in that way, that the game lags every 2 seconds and waits for HDD? (e.g. gTA IV )
I don't think it could be my graphics as I have a powerful machine and my gpu chip still has a reserve according to the game itself and performing tools.
Does it mean, that I should defragment imminent the after install / uninstall?
Specs:
Asus G73JH-A1 Notebook
Intel I7 720QM
ATI Mobility Radeon HD 5870 1GB GDDR5
2x 7200 RPM 500 GB HDD (Pagefile.sys on the 2nd one at fixes size 1.5 RAM)
8 GB RAM

A: If the lag is consistently occurring exactly every 2 seconds then I would say that it may not be simply fragmentation that is causing it, it is more likely a problem somewhere else in the system.
If, at random-ish times, the game lags before certain things like large buildings or new types of car appear then it could point to fragmentation but more generally it could be showing up either overall poor hard drive performance or other system issues.
While it can be beneficial to defragment after an install, on any reasonably modern system I would say that unless the game files are horrifically fragmented into thousands upon thousands of pieces then performance should not be affected by that serious an amount.

A: Well this depends much on the previous state of your HDD. If it had fragmentation problems before, you would need to defragment it after such an installation. On the other hand, if you didn't have any problems with fragmentation and low disk space before, it's something else. In the end I'd recommend that you do defragment the HDD. You have nothing to lose (leave it working while you sleep for example) and it could solve the problem.


text:
Q: Running CustomAction in wix as elevated user As I see it - WiX supports two kinds of CustomActions:

*

*Deferred - The user running this action is (by default) elevated, but it is not the user who ran the install (for example, LocalSystem, or some user like that).

*Immediate - The user running this action is (by default) not elevated - it's the user who ran the installer in the first place.
I need something quite in the middle - I want the elevated form (UAC) of the user who ran the installer.
The reason I need this is to access databases that can only be accessed by the user installing the package in its elevated form (LocalSystem is not accessible).

A: This does not exist. There are only two possible contexts for custom actions to run in. One is the launching user (often via impersonation). The other is the elevated context of the Windows Installer service. On some machines (such as Windows XP, or machines with UAC disabled), or with elevating bootstraps, the launching user is an adminstrative user; you can check for this case with a combination of the MSIUSEREALADMINDETECTION and AdminUser properties. But in no case is there a third context.


text:
Q: Updating parameter with button on click and unclick I have 4 buttons on my webpage, each having a value. So depending on which buttons are pressed/clicked in the webpage I need the parameter "Buttonvals" to be modified in the url accordingly, as these values will be used as filters for my SQL query.
Eg if buttons 1 2 and 4 are selected
the url must be: url?buttonvals=value1|value2|value4.
Please suggest how I go about doing this. Please provide code if possible as I am still new to Javascript and php
  <input type="checkbox" name="item1" value="value1"> value1

  <input type="checkbox" name="item2" value="value2">  value2

  <input type="checkbox" name="item3" value="value3">  value3

  <input type="checkbox" name="item4" value="value4">  value4

  <input type="submit" value="Submit">

  the url must become something like   url?buttonvals=value1|value2|value4

Thanks in advance :)

A: Hi R P I have a solution for you.
Your HTML Code
<input type="checkbox" name="item1" value="value1" onclick="setUrlParams(this)"> value1

<input type="checkbox" name="item2" value="value2" onclick="setUrlParams(this)">  value2

<input type="checkbox" name="item3" value="value3" onclick="setUrlParams(this)">  value3

<input type="checkbox" name="item4" value="value4" onclick="setUrlParams(this)">  value4

<input type="submit" value="Submit">

JS Code
   function setUrlParams($obj){

  var myButtonClasses = $obj.classList;

 if (myButtonClasses.contains("chbox-clicked")) {

    myButtonClasses.remove("chbox-clicked");

 }else{
   myButtonClasses.add("chbox-clicked");
 }

  //now get all selcted classes
  var valueStr = "";
var chboxCheckd  = document.getElementsByClassName('chbox-clicked');
for (var i = 0; i < chboxCheckd.length; ++i) {
    var item = chboxCheckd[i];
    valueStr = valueStr+item.value+"|";
}
  var finalurl = window.location.href;
  if( finalurl.indexOf('?') >= 0){
    finalurl = finalurl+"&buttonvals="+valueStr.slice(0, -1);
   }else{
    finalurl = finalurl+"?buttonvals="+valueStr.slice(0, -1);
   }
  //var finalurl = "http://abc.xyz/buttonvals="+valueStr.slice(0, -1);
  console.log(finalurl);
  //window.history.replaceState(null, null, finalurl);
  //window.location.href = finalurl
}

Well uncomment replacestate line to change location without reloading page. Or uncomment last line to reload the page with url.
Currently it's only printing on console. Not allowed here on JS editor also so.
DEMO


text:
Q: for loop in GNU Parallel I am trying to download a large number of files from a webpage (which contains only a image, so I can use a simple wget), but want to speed it up using GNU Parallel. Can anyone please help me parallelize this for loop? Thanks.
    for i in `seq 1 1000`
    do
    wget -O "$i.jpg" www.somewebsite.com/webpage
    done

A: You could do it like this:
 seq 1 1000 | parallel wget www.somewebsite.com/webpage/{}.jpg

You can also use the -P option to specify the number of jobs you want to run concurrently.
Also you may decide to use curl instead like:
parallel -P 1000 curl -o {}.jpg www.somewebsite.com/webpage/{}.jpg ::: {1..1000}


text:
Q: How do flag the unselected records in a top selection I have a requirement  I need to choose only a selected number of records from a group.  However, I also need to flag the not choosen records in the even that they will need to be referred to at a later date.
I have over 80K records in Segment 1.  The requirement is to select 50000 records
I've tried this:
UPDATE mytable
   SET [SuppressionReason] = 'REC LIMIT REACHED - S1'
 WHERE
   [ID] NOT IN
    (
     SELECT TOP 50000 [ID] FROM mytable
      WHERE segment = '1'
    );

However, this results in 0 records getting labeled in the SuppressionReason field as  'REC LIMIT REACHED - S1'.  What am I missing or doing wrong?

A: Based on testing with the following code, are you absolutely certain that you have more than 50,000 records?
DROP TABLE IF EXISTS #TEMP
CREATE TABLE #TEMP
(
    ID INT IDENTITY(1,1),
    FIRSTNAME VARCHAR(10),
    LASTNAME VARCHAR(10),
    SEGMENT INT,
    SUPPRESSION VARCHAR(10)
)

INSERT INTO #TEMP
    (FIRSTNAME, LASTNAME, SEGMENT)
VALUES
    ('JOHN', 'KRAMER',1),
    ('MATT','GEORGE',1),
    ('PHILIP','MCCAIN',1),
    ('ANDREW','THOMAS',1)

UPDATE #TEMP
    SET SUPPRESSION = 'YEP'
WHERE ID NOT IN
    (SELECT TOP(2) ID FROM #TEMP WHERE SEGMENT = 1)

SELECT * FROM #TEMP

This produces the following output, which I suspect is exactly what you are expecting to get.
   1    JOHN    KRAMER  1   NULL
   2    MATT    GEORGE  1   NULL
   3    PHILIP  MCCAIN  1   YEP
   4    ANDREW  THOMAS  1   YEP


text:
Q: Axios not showing informations on react page I would like to use axios to fetch the values from API in react.js, and set it as a form, but it doesn't display any fetched data at all.
export default function Review() {

  const [fetchedData, setFetchedData] = useState([]);
  const [fetchedlanguage, setlanguage] = useState([]);

     useEffect(() => {
       const getStudent = async () => {
         const stu = await axios.get('http://localhost:8000/students/');
         setFetchedData(stu.data.students[0]);
         setlanguage(stu.data.students[0].languages)
       };
       getStudent()
     },[]);

     console.log("student: ", fetchedData);

    const [formdata, setformdata] = useState({
        availability: 6,
        preference:'201, 301',
        experience:'201',
        language:fetchedlanguage[0],
        background:fetchedData.background,
    });

Even though the console.log shows the data correctly, when I set the form here, how come there is no updates on data?

A: Control it all in one place. You will want to spread the original values over the setformdata because it's immutable. I'm not sure what all the API returns so continue to override each formdata property that you get back from the API.
export default function Review() {
    const [formdata, setformdata] = useState({
        availability: 6,
        preference:'201, 301',
        experience:'201',
        language: 'english',
        background: 'initial-background',
    });

    useEffect(() => {
        const getStudent = async () => {
            const stu = await axios.get('http://localhost:8000/students/');
            const student = stu.data.students.length > 0 ? stu.data.students[0] : {};
            setFormData({
                ...formdata,
                langauge: student.languages,
                // TODO: continue to override the formData from student returned from API
            });
        };
        getStudent()
    }, []);

    // TODO: use formdata to feed into form
    return null;
}


text:
Q: How to explode a string with commas and recompose except the first one I have a string like this [tubelist dijfisj, ijdsifjad, ajkdfksd, sdjfkdf] and I would like to separate them into two ###URL### and ###URL2###.
This is the code I got so far
function xyz_plugin_callback($match)
{
  $tag_parts = explode(",", rtrim($match[0], "]"));
  $output = YOUX_TARGET;
  $output = str_replace("###URL###", $tag_parts[1], $output);
  $output = str_replace("###URL2###", $tag_parts[2], $output);
}

$match is the variable that I'm passing in.

A: You can utilize regular expressions here.
So if you do something like:
$temp_match = trim($match[0], "[]");

$urls = array();
preg_match("/([\w\s]*),([\w\s]*),.*/", $temp_match, $urls);

$url1 = $urls[1];
$url2 = $urls[2];

// do your $output str_replace here.

A: finally, I got it working!  Here is the working code.
$tag_parts1 = explode(" ", rtrim($match[0], "]"));

$tag_parts = explode(",",$tag_parts1[1],2);

the first line will strip the [tubelist and ].
the second line with store the first set of value in array[0] and the rest to [1].
voila, case resolved.


text:
Q: sed Pattern to Insert Comma between double Quotes I am very new to sed Regex pattern and stuck with a requirement. I have few Records which i am pulling from Database

"Name" "Age" "From ABC" "12"

now I am exporting it to CSV with Comma Separated i am using 's/[[:space:]]\+/,/g' This Regex
Which is giving me the Result as

"Name","Age","From,ABC","12"

Which is fine except the Third Column where it has inserted , for space
now i want to insert , in between double quotes.
Can any One Guide me for the same?
With 's/"[[:space:]]\+"/","/g' Regex i Am able to get "Name","Age","From,ABC","12" But its is failing when i have "Name","","From,ABC","12" it gives "Name",",","From,ABC","12"
Is there any other way to counter this?

A: Replace " " with ",":
sed 's/"[[:space:]]\+"/","/g'

Edited to catch more than one space

A: I'd do this:
echo \"Name\"     \"Age\" \"From ABC\" \"12\" | sed -e 's/"[[:space:]]\+"/","/g'

which returns
"Name","Age","From ABC","12"

edit
if you want have empty strings " " also matched, then you could do this:
$ echo \"Name\" \" \"    \"Age\" \"From ABC\" \"12\" | sed -e 's/\("[[:alnum:][:space:]]*"\)/\1,/g' \
    -e 's/",[[:space:]]\+/",/g' \
    -e 's/,[[:space:]]\?$//g'

which returns
"Name"," ","Age","From ABC","12"

The first rules matches strings in quotes (that also may be empty), the second
rule removes the spaces between , and the next ", the third rules removes
the last ,.

A: This might work for you (GNU sed):
sed -r 's/\s+$//;s/("[^"]*(\\.[^"]*)*")\s+/\1,/g' file

Remove any white space at the end of line. Then globally replace any pair of double quoted strings followed by a space(s), by the string followed by a comma.
N.B. This caters for quoted characters (including double quotes) within the quoted strings.


text:
Q: Complicated mySQL query in php page If you have seen my previous requests you will see I am a TOTAL NOOB with php and mySQL.  I wish I wasn't even doing this but I have been dumped in the deep end by people that have let me down. It is 1 day away from "completion" and I am left to pick up and mend the pieces of this system I have which doesn't fully function!
I have tried to explain this as logically and clearly as possible.  If you need clarification please let me know and I will do my best!
Thanks in advance for any help as I am now desperate to get this thing done!
I have 3 issues!
ISSUE1
Matching Keys
(x)
TABLE1

|        C_ID        |       C_Eth_O   (x)     |
+--------------------+-------------------------+
|        234         |             8           |
|        341         |             11          |
|        440         |             2           |

TABLE2

|        Eth_ID  (x)    |        C1_Eth_O        |
+-----------------------+------------------------+
|            2          |         Label2         |
|            8          |         Label8         |
|            9          |         Label9         |
|            11         |         Label11        |

I need to list all the "C1_Eth_O" values in a multi select list.  The user will make multiple selections from that list.  When submitted I need to get the "Eth_ID" value(s) and return all the value(s) from TABLE1 where any of the selected options "C_Eth_O" = "Eth_ID". Each "C_ID" can only have one "C_Eth_O".
ISSUE2
Matching Keys
(x)
(o)

TABLE1

|        C_ID   (x)   |
+---------------------+
|        234          |
|        341          |
|        440          |

TABLE3

|        Ail_ID  (o)      |        Ali_Label        |
+-------------------------+-------------------------+
|           1             |        Label1           |
|           2             |        Label2           |
|           3             |        Label3           |
|           4             |        Label4           |
|           5             |        Label5           |
|           6             |        Label6           |

TABLE4

|        CA_ID         |       C1_ID    (x)     |      Ail1_ID    (o)    |
 +---------------------+------------------------+------------------------+
|           1          |            234         |            1           |
|           2          |            341         |            4           |
|           3          |            341         |            6           |
|           4          |            440         |            2           |

I need to list all the "Ali_Label" values from TABLE3 in a multi select list.  The user will make multiple selections from that list.  When submitted I need to get the "Ail_ID" value(s) from TABLE3 and return all the value(s) from TABLE1 where any of the selected match in TABLE4 "Ali1_ID" = "Ail_ID" & "C1_ID" = "C_ID".  Each "C_ID" can have multiple "Ail_ID" values
ISSUE3
Matching Keys
(x)
(o)
(-)

TABLE1

|        C_ID   (x)   |
+---------------------+
|        234          |
|        341          |
|        440          |

TABLE3

|        Ail_ID  (o)     |        Ali_Label        |
+------------------------+-------------------------+
|           1            |        Label1           |
|           2            |        Label2           |
|           3            |        Label3           |
|           4            |        Label4           |
|           5            |        Label5           |
|           6            |        Label6           |

TABLE5

|        R_ID           |        C1_ID  (x)     |        Cf1_ID   (-)   |
+-----------------------+-----------------------+-----------------------+
|           1           |           234         |           768         |
|           2           |           234         |           854         |
|           3           |           234         |           768         |
|           4           |           440         |           854         |

TABLE6

|        CA_ID         |       Cf_ID    (-)     |      Ail1_ID    (o)    |
 +---------------------+------------------------+------------------------+
|           1          |            768         |            1           |
|           2          |            854         |            4           |
|           3          |            768         |            6           |
|           4          |            880         |            2           |

I need to list all the "Ali_Label" values from TABLE3 in a multi select list.  The user will make multiple selections from that list.  When submitted I need to get the "Ail_ID" value(s) from TABLE3 and return all the value(s) from TABLE1 where any of the selected "Ali_ID" = "Ail1_ID"    &    "C1_ID" = "C_ID"    &    "Cf1_ID" = "Cf_ID".  Each "C_ID" can have multiple "Cf1_ID" values AND each "Cf_ID" can have multiple "Ail1_ID" values.
I have the system working returning simple queries such as
SELECT * FROM table1 WHERE C_ID = 234

but nothing with multiple tables and multiple results per C_ID!
Thanks again!

A: ISSUE 1 -
SELECT * FROM table1 INNER JOIN table 2 ON table1.C_Eth_O = table2.Eth_ID

ISSUE 2 -
SELECT * FROM table1 INNER JOIN table4 ON table1.C_ID = table4.C1_ID INNER JOIN table3 ON table3.Ail_ID = table4.Ail1_ID

ISSUE 3 -
SELECT * FROM table1 INNER JOIN table5 ON table1.C_ID = table5.C1_ID INNER JOIN table6 ON table5.Cf1_ID = table6.Cf_ID INNER JOIN table3 ON table3.Ail_ID = table6.Ail1_ID


text:
Q: Convert List of List of Elements to Map < K, List> I have following structure.
Request {
    List<Param> paramList;
    Date startDate;
    Date endDate;
}

Param {
    String paramId;
    List<DataParam> dataParams;
}

DataParam {
    String dataId;
    List<String> values;
}

CustomRequest {
    List<NewDataParam> newDataParam;
    Date startDate;
    Date endDate;
}

NewDataParam {
 String paramId;
 String dataId;
----
}

Iterating over the request with paramList, I want to make map of paramId and generated request like Map<String, List<CustomRequest>>.
With following code, I got Map<String, List<List<CustomRequest>>>. Can someone suggest how to get Map<String, List<CustomRequest>>.
request.paramList().stream()
    .collect(Collectors.groupingBy(Param::getParamId,
        Collectors.mapping(i -> i.dataParams().stream()
           .map(r -> customBuildMethod(i.dataParamId(), r, request)).collect(Collectors.toList()), Collectors.toList())));

private CustomRequest customBuildMethod(String paramId ...) {
    CustomRequest customRequest = new CustomRequest();
    //mapping
    return customRequest;
}

A: If you can use Java 9, you can achieve your goal with Collectors.flatMapping:
request.paramList()
       .stream()
       .collect(Collectors.groupingBy(Param::getParamId,
                                      Collectors.flatMapping(i -> i.dataParams().stream().map(r -> customBuildMethod(i.dataParamId(), r, request))),
                                                            Collectors.toList())));

In Java 8, you can do the following:
Map<String, List<CustomRequest>> result =
    request.paramList()
          .stream()
          .collect(Collectors.groupingBy(Param::getParamId,
                                         Collector.of(ArrayList::new,
                                                     (l,i)->l.addAll(i.dataParams().stream().map(r -> customBuildMethod(i.dataParamId(), r, request)).collect(Collectors.toList())),
                                                     (l1,l2)->{l1.addAll(l2);return l1;})));

A: Instead of Collectors.mapping() you can use Collectors.collectingAndThen() where in finisher function you can do a flatMap using list of data params. Something like that:
Map<String, List<CustomRequest>> map = params.stream()
        .collect(Collectors.groupingBy(
                Param::getParamId, Collectors.collectingAndThen(Collectors.toList(), it -> it.stream()
                        .flatMap(i -> i.getDataParams().stream())
                        .map(r -> new CustomRequest(Arrays.asList(new NewDataParam()), new Date(), new Date()))
                        .collect(Collectors.toList())
                ))
        );

System.out.println(map);

Full example I used for tests:
import java.util.*;
import java.util.stream.Collectors;

public class ListOfListsToMapOfStringAndListExample {

    public static void main(String[] args) {

        final List<Param> params = Arrays.asList(
                new Param("1", Arrays.asList(new DataParam("2", Arrays.asList("a", "b")))),
                new Param("3", Arrays.asList(new DataParam("4", Arrays.asList("c", "d")))),
                new Param("5", Arrays.asList(new DataParam("6", Arrays.asList("e", "f"))))
        );

        Map<String, List<CustomRequest>> map = params.stream()
                .collect(Collectors.groupingBy(
                        Param::getParamId, Collectors.collectingAndThen(Collectors.toList(), it -> it.stream()
                                .flatMap(i -> i.getDataParams().stream())
                                .map(r -> new CustomRequest(Arrays.asList(new NewDataParam()), new Date(), new Date()))
                                .collect(Collectors.toList())
                        ))
                );

        System.out.println(map);
    }

    static class Request {
        List<Param> paramList;
        Date startDate;
        Date endDate;

        public Request(List<Param> paramList, Date startDate, Date endDate) {
            this.paramList = paramList;
            this.startDate = startDate;
            this.endDate = endDate;
        }
    }

    static class Param {
        String paramId;
        List<DataParam> dataParams;

        public Param(String paramId, List<DataParam> dataParams) {
            this.paramId = paramId;
            this.dataParams = dataParams;
        }

        public String getParamId() {
            return paramId;
        }

        public List<DataParam> getDataParams() {
            return dataParams;
        }
    }

    static class DataParam {
        String dataId;
        List<String> values;

        public DataParam(String dataId, List<String> values) {
            this.dataId = dataId;
            this.values = values;
        }

        public String getDataId() {
            return dataId;
        }

        public List<String> getValues() {
            return values;
        }
    }

    static class CustomRequest {
        List<NewDataParam> newDataParam;
        Date startDate;
        Date endDate;

        public CustomRequest(List<NewDataParam> newDataParam, Date startDate, Date endDate) {
            this.newDataParam = newDataParam;
            this.startDate = startDate;
            this.endDate = endDate;
        }

        public List<NewDataParam> getNewDataParam() {
            return newDataParam;
        }

        public Date getStartDate() {
            return startDate;
        }

        public Date getEndDate() {
            return endDate;
        }

        @Override
        public String toString() {
            return "CustomRequest{" +
                    "newDataParam=" + newDataParam +
                    ", startDate=" + startDate +
                    ", endDate=" + endDate +
                    '}';
        }
    }

    static class NewDataParam {

        @Override
        public String toString() {
            return "NewDataParam{}";
        }
    }
}

Output:
{1=[CustomRequest{newDataParam=[NewDataParam{}], startDate=Wed Feb 14 09:03:21 CET 2018, endDate=Wed Feb 14 09:03:21 CET 2018}], 3=[CustomRequest{newDataParam=[NewDataParam{}], startDate=Wed Feb 14 09:03:21 CET 2018, endDate=Wed Feb 14 09:03:21 CET 2018}], 5=[CustomRequest{newDataParam=[NewDataParam{}], startDate=Wed Feb 14 09:03:21 CET 2018, endDate=Wed Feb 14 09:03:21 CET 2018}]}

Update:
In case of passing param.paramId to customBuildMethod you can even get rid of flatMap() onparam.dataParams and map your initial param object to a CustomRequest. Something like:
Map<String, List<CustomRequest>> map = params.stream()
        .collect(Collectors.groupingBy(
                Param::getParamId, Collectors.collectingAndThen(Collectors.toList(), it -> it.stream()
                        .map(param -> customBuildMethod(param.paramId, param.dataParams))
                        .collect(Collectors.toList())
                ))
        );

In this example I pass param.paramId and param.dataParams to this helper method which creates CustomRequest object. It can use a list of data params to create a new list of new data params objects:
private static CustomRequest customBuildMethod(String paramId, List<DataParam> params) {
    return new CustomRequest(
            params.stream().map(dataParam -> new NewDataParam()).collect(Collectors.toList()),
            new Date(),
            new Date()
    );
}

Or more directly according to your code:
Map<String, List<CustomRequest>> map = params.stream()
        .collect(Collectors.groupingBy(
                Param::getParamId, Collectors.collectingAndThen(Collectors.toList(), it -> it.stream()
                        .map(param -> customBuildMethod(param.paramId, r, request))
                        .collect(Collectors.toList())
                ))
        );


text:
Q: How to fit image in UITextView and Tap to get larger I have created a Table-view in main ViewController once i touch the row it will take to the next view controller(DetailViewController) where it display the image and name of dish.And once i tap the image it should get larger but it is not getting bigger .The below code is which i have tried in DetailViewController.
DetailViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
imageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 10,100, 100)];
CGRect textViewFrame = CGRectMake(10, 10, 300, 400);
textView = [[UITextView alloc] initWithFrame:textViewFrame];
textView.returnKeyType = UIReturnKeyDone;
textView.backgroundColor=[UIColor whiteColor];
textView.editable=NO;
textView.delegate = self;
[self.view addSubview:textView];
[textView addSubview:imageView];
textView.alpha = 0.9;
textView.font = [UIFont systemFontOfSize:15];

if(mrowno==0)
{
     imageView.image=[UIImage imageNamed:@"Dosa.jpg"];
    textView.text = @"\n\n\n\n\n\n\n\nDOSA\nDosa, ";
    imageButton = [[UIButton alloc]init];
    [imageButton setFrame:CGRectMake(0, 0, 100, 100)];
    [imageButton addTarget:self action:@selector(imageTapped:) forControlEvents:UIControlEventTouchUpInside];
    [imageView addSubview:imageButton];

}

Here is the method to make image larger
-(void)imageTapped:(UIButton*)in_sender
{

[UIView transitionWithView:in_sender.superview  duration:0.8f  options:UIViewAnimationOptionCurveLinear  animations:^
 {
     [in_sender.superview setFrame:CGRectMake(0, 0, 300, 500)];
 }
                completion:^(BOOL finished)
 {
 }];
}

A: You do not want to use transitionWithView. Instead, you want to use + animateWithDuration: delay:options:animations:completion: (or any of its shorter variants...)
[UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
    viewYouWantToAnimate.frame = CGRectMake(..., ..., ..., ...);
} completion:^{
    //Add completion code here, or pass nil if you don't have anything to do.
}];

Edit: In case you were wondering what transitionWithView was used for... the AppleDocs have a great example of it adding animations for remove/addSubview methods (not frame modifications):
[UIView transitionWithView:containerView
       duration:0.2
       options:UIViewAnimationOptionTransitionFlipFromLeft
       animations:^{
           [fromView removeFromSuperview];
           [containerView addSubview:toView];
       } completion:NULL];

A: You can increase and decrease the size of image by pinch in and pinch out,If it required
-(void)viewDidLoad
 {
 UIPinchGestureRecognizer* pinch=[[UIPinchGestureRecognizer alloc] initWithTarget:self            action:@selector(pinching:)];
[self.imageView addGestureRecognizer:pinch];
  }

-(void)pinching:(UIGestureRecognizer*) recognizer
 {
UIPinchGestureRecognizer* pinch=(UIPinchGestureRecognizer*) recognizer;
self.imageView.transform=CGAffineTransformScale(self.imageView.transform, pinch.scale, pinch.scale);
pinch.scale=1;
NSLog(@"pinching");
 }


text:
Q: FineUploader 3.1: german special-character fine-uploader 3.1 jquery-Version works fine until filename starts with a German special character (äöü). I think this is browser- and OS-independent. HTML and PHP is set to UTF-8.
Uploading a file named "äöü test.txt" I get "test.txt" on [Server]/tmp. A file named "Xäöü text.txt" will be transferred correctly.
How can I fix this?

I think there is nothing strange on client-side. Maybe I'm wrong:
$('#dlgVorgangNewUpload').fineUploader({
  request: { endpoint: '././Objekt.ajax.php' },
  button: null,
  text: { uploadButton: txt,
    cancelButton: 'Abbruch',
    failUpload:  "Upload fehlgeschlagen"
},
  multiple: true,
  retry: { showButton: false },
  validation: {sizeLimit: 10485760 }, // 10 x 1024 x 1024
  debug: true
}).on('submit', function(event, id, filename) {
    UploadCounter++;
    $(this).fineUploader('setParams', {'todo': 'VorgangUpload'});
}).on('complete', function(event, id, fileName, responseJSON ){
    UploadCounter--;
    if (responseJSON.success) {
      if (UploadCounter == 0) BusyShow("importiere Dateien....");
      $.ajax({
    // some stuff to store file-inbformation in Database
        ...
      });
    } else if (responseJSON['error']){
      msgbox (responseJSON['error'],"Fehler:");
    }
}).on('cancel', function(event, id, filename) {
     UploadCounter--;
});

This is the output from Firebug:
Parameter:
  qqfile    äöüß test.doc
  todo  VorgangUpload

Header:
POST /incl/Objekt.ajax.php?todo=VorgangUpload&qqfile=%C3%A4%C3%B6%C3%BC%C3%9F+test.doc HTTP/1.1
Host: xxxxx.xxxxxxxxxxxx.de
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:27.0) Gecko/20100101 Firefox/27.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-File-Name: %C3%A4%C3%B6%C3%BC%C3%9F%20test.doc
Cache-Control: no-cache
Content-Type: application/octet-stream
X-Mime-Type: application/msword
Referer: https://xxxxxxxxxx.xxxxxxxxx.de/incl/Objekt.php?id=4190
Content-Length: 12800
Cookie: .....
PHPSESSID=.....
Connection: keep-alive
Pragma: no-cache

hmmm.
within Shell:
file -i Objekt.ajax.php
Objekt.ajax.php: text/x-php; charset=utf-8

echo $LANG
de_DE

php-file:
...
header('content-type: text/html; charset=utf-8');
...

What else should I do? I don't understand why this should be a server issue. Transfering a file with special chars works fine until a filename starts with a special char. This is very strange to me.


text:
Q: How to replace date component separators with other symbols? In my app I would like to allow users to select a variety of date formats that suit their preferences for displaying a date. However, I don't want to define a fixed date format, so instead I'm getting the most appropriate format for different components based on the current locale. I understand different locals may use different symbols to separate the components, but I am wondering if it would be possible to set those separator symbols while preserving the correct order of the components as appropriate for that locale.
For example, in the US the following code returns "09/06/2014" but in the UK it would be "06/09/2014", and I want to preserve that order but replace the slash with dashes or spaces. However I don't believe I can simply parse the returned String and replace instances of '/' with other characters because in some locales they probably don't use '/' (I'm not certain but it seems very likely).
NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale.currentLocale())

Is it possible to change the date component separator character when at the same time getting the most appropriate format for the current locale?

A: I went through all the languages on my iPad and checked out the short date format. I found out that all languages use one of these three delimiters: / . -
So to allow custom delimiters while preserving the format, I just replace those characters with the custom character. For example:
dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale.currentLocale())
cell.dateLabel.text = dateFormatter.stringFromDate(NSDate())
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString("/", withString: " ", options: nil, range: nil)
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString(".", withString: " ", options: nil, range: nil)
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString("-", withString: " ", options: nil, range: nil)

I'd be nice to find a better solution.


text:
Q: How to obtain the offset of a MASM local variable at assembly time I want to obtain the offset into the stack frame of a MASM procedure's local variable at assembly time (not runtime, the LEA instruction isn't useful here). E.g., if the local variable is at RBP-8 at run time, I want to obtain the constant (-8) during assembly.
Is this possible?
OFFSET operator only works on global (static) variables. Every suggestion I've found on the internet talks about using LEA, which is not what I want.
someProc  proc
          local  a:byte, b:word, c:dword
           .
           .
           . someConst =  MagicOffset(a) ;Magically sets constant "someConst" to the offset of "a" (probably something like -8).

someProc  endp


text:
Q: Solr boost query by field value and inside newest date We have the following setup in our schema.xml:
<field name="last_modified" type="date" indexed="true" stored="true" multiValued="false" omitTermFreqAndPositions="true"/>
...

<field name="prefix" type="string" indexed="true" stored="true" omitTermFreqAndPositions="true"/>

Our goal is to sort the docs by

*

*prefix=9999 with newest docs (last modified) first

*prefix=1004 or prefix=1005 with newest docs (last modified) first

Our code:
{!boost b=recip(ms(NOW,last_modified),3.16e11,1,1)}prefix:9999^1000000 OR {!boost b=recip(ms(NOW,last_modified),3.16e-11,1,1)}prefix:1004^600000 OR {!boost b=recip(ms(NOW,last_modified),3.16e-11,1,1)}prefix:1005^600000

Result:
The query above does not work as expected!
We thought that omitTermFreqAndPositions=true will force to prevent ITF and the scoring should work. But it does not seem so!
Please help us with this :-)

A: So we found a solution!

*

*Create your own Similarity (a simple java class)
For a better and simpler descriptions how, please read How to compile a custom similarity class for SOLR / Lucene using Eclipse
The class we used
package com.luxactive;
import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.search.similarities.DefaultSimilarity;

public class MyNewSimilarityClass  extends DefaultSimilarity {

@Override
public float coord(int overlap, int maxOverlap) {
    return 1.0f;
}

@Override
public float idf(long docFreq, long numDocs) {
    return 1.0f;
}

@Override
public float lengthNorm(FieldInvertState arg0) {
    return 1.0f;
}

@Override
public float tf(float freq) {
    return 1.0f;
}

}

*Create a simple jar with your Similarity

*Copy the jar to any folder into your solr server, we used:
SOLRFOLDER/solr-4.8.0/example/solr/dih
The next steps need to be done to every collection you have!

*Edit the solrconfig.xml at: SOLRFOLDER/solr-4.8.0/example/solr/collection/conf/solrconfig.xml
Add <lib dir="../dih" regex=".*\.jar" /> to import the custom jar

*Edit the schema.xml in the same folder

Add the following
<!-- DEFAULT Factory for custom com.luxactive.MyNewSimilarityClass  -->
<similarity class="solr.SchemaSimilarityFactory"/>

<!-- TYPE String -->
 <fieldType name="no_term_frequency_string" class="solr.StrField" sortMissingLast="true" >
    <similarity class="com.luxactive.MyNewSimilarityClass"/>
</fieldType>

<!-- TYPE Date -->
<fieldType name="no_term_frequency_date" class="solr.TrieDateField" sortMissingLast="true" >
    <similarity class="com.luxactive.MyNewSimilarityClass"/>
</fieldType>

<!-- TYPE Int-->
<fieldType name="no_term_frequency_int" class="solr.TrieIntField" sortMissingLast="true" >
    <similarity class="com.luxactive.MyNewSimilarityClass"/>
</fieldType>

Here you define your own field types (int, string and date) that use the new Similarity class which will return a boost value like defined in the MyNewSimilarityClass.

*Now edit the fields you want to use your custom Similaritry by setting theyr type to one you created.
From: <field name="last_modified" type="date" indexed="true" stored="true" multiValued="false" />
To: <field name="last_modified" type="no_term_frequency_date" indexed="true" stored="true" multiValued="false" />

*Restart the solr server and enjoy your boosting :)


text:
Q: Creating an accelometer in CSS/Javascript Im working on a project where I need to visualize the G-force on a spaceship. I want to accomplish this with creating an accelometer (something like a seismogram see picture for an example)
Is is possible to create this using CSS/JavaScript?
The accelometer needs to run infinite creating random data for the G-force on the spaceship.

A: It sure is possible with CSS and JS.
The question is wether you want to do it that way.
If I were you I'd choose to use the HTMLCanvasElement to display the data generated by either JavaScript on the client side or the server side language of your choice on the server.


text:
Q: Mockito: mocking an HTTP call with OK HTTP Client I'm using Kotlin's OK HTTP Client to make HTTP calls from my application:
val httpCall = okHttpClient.newCall(myRequest)
val response = httpCall.execute()

The client is created as a bean:
@Bean(name = ["okHttpClient"])
fun produceOkHttpClient(): OkHttpClient? {
    return OkHttpClient()
}

How do I mock this in my unit test using Mockito?
I have a mock bean set up:
@Bean
fun okHttpClient(): OkHttpClient? {
    return mock(OkHttpClient::class.java)
}

... and I have tried the following in the unit test:
val call : Call = mock(Call::class.java)
`when`(okHttpClient?.newCall(any(Request::class.java))).thenReturn(call)

... but get this (confusing to me) message when I try and run the test:
java.lang.IllegalStateException: any(Request::class.java) must not be null

A: I have moved to using Mockk (https://mockk.io/) instead.


text:
Q: SpringBoot Junit5 fails when renaming package of class holding @SpringBootApplication annotation I'm struggling with JUnit 5 when moving the @SpringBootApplication to a different package.
I have setup a new SpringBoot-project (2.2.1.RELEASE) with Maven and Eclipse (had to upgrade this from "Eclipse Photon" to support the SpringBoot-Release
My package layout looks like this:
/src/main/java
   com.package.sample.appl1
     StartSamples.java
   com.package.sample.appl1.start
   com.package.sample.appl1.dbaccess
   com.package.sample.appl1.run
   com.package.sample.appl1.utils
   com.package.sample.appl2.run
   com.package.sample.appl2.run

/src/test/java
   com.package.sample.appl1.dbaccess
     SimpleTest.java

The class holding the @SpringBootApplication is:
@ComponentScan({
    "com.package.sample"
    })
@SpringBootApplication
public class StartSamples {
   public static void main(String[] args) {
        System.out.println("Start");
        try {
            SpringApplication.run(StartSamples.class, args);
        } catch (Exception e) {
            LOGGER.error("", e);
            System.exit(-1);
        }
    }

And the test is this:
import static org.junit.Assert.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit.jupiter.SpringExtension;

/**
 * Test the Query-statements and the DAO methods
 *
 * @author U005078
 *
 */
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ComponentScan({
    "com.package.sample"})
@EnableAutoConfiguration
public class SimpleTest {

    @SuppressWarnings("unused")
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTest.class);

    @Test
    @DisplayName("SimpleTest")
    public void testTotalRows() {

With this configuration all is fine, "StartSamples" works as expected and aqlso the SimpleTest.
But when moving "StartSamples" to a different package (e.g. "com.package.sample.start" would make more sense to me - "StartSamples" is still ok but "SimpleTest" does not fail nor succeed - test seems not to become executed.
I see a message:
class path resource [com/package/sapmle/appl1/dbaccess/SimpleTest-context.xml] does not exist
class path resource [com/package/sapmle/appl1/dbaccess/SimpleTestContext.groovy] does not exist
.SimpleTest]: SimpleTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
I also found:
Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.package.sample.appl1.dbaccess.SimpleTest], using SpringBootContextLoader
So I defined the @ContextConfiguration to the "SimpleTest", then it worked. But I do not understand at all why the move of the @SpringBootApplication did change this behaviour.
With another try of setting up this project I ended up with "No tests found with test runner 'JUnit 5'" and could also not find any reason. I started over again with the current approach and get to here. And do do nat any clue what gives me the error - for either of the problems.
Any explanation witld be appreciated. I tried for lots of hours now to find something in the internet - but I only found recommendations like "try this", "try that" but no help in understanding.
So any help is appreciated.

A: Define your SpringBoot Main class like below
@SpringBootTest(classes = {StartSamples.class})
public class SimpleTest {
   ...
}


text:
Q: Adding and filtering layer with map canvas extent using PyQGIS I'm creating a small QGIS3.16 plugin with PyQGIS.
I'd want to add a vector (PostGIS) layer to QGIS, and immediately filter it with the QGIS canvas extent.
I found the QgsFeatureRequest(rectangle:QgsRectangle) class. I want to use it with "self.iface.canvas.extent()".
How do I use this class to filter the layer I just added to QGIS?
This is my code :
# Collect the canvas extent
extent = self.iface.mapCanvas().extent()
request = QgsFeatureRequest()
request.setFilterRect(extent)

# Add the vector layer to QGIS
self.uri = QgsDataSourceUri()
self.uri.setConnection("adress", "port", "database", '', '', False,'idauth')
self.uri.setDataSource("schema", tablename, "geomfield", None , pkey)
self.ctrs_cibles=QgsVectorLayer(self.uri.uri(), "layername", "postgres")
root = QgsProject.instance().layerTreeRoot()
if self.ctrs_cibles.featureCount()>0:
   QgsProject.instance().addMapLayer(self.ctrs_cibles, False)
   root.insertLayer(0, self.ctrs_cibles)

*

*I tried to insert "request" as the 4th parameter of the setDataSource method :
self.uri.setDataSource("schema", tablename, "geomfield", request , pkey)
But pyQgis waits for a string, not a qgsFeatureRequest.

*I've got the same result trying to use setSubsetString. The following command won't work : it needs "request" to be a plain text query.
    self.ctrs_cibles.setSubsetString(request)

*

*I tried to use a getFeatures() method :

for feature in self.ctrs_cibles.getFeatures(request):
    do something...

This method needs a qgsFeatureRequest but it just creates an iterator, it doesn't filter the layer.
I could use the iterator to create another layer and add the filtered features inside, but I am looking for a more straightforward way to filter a layer with the canvas extent.

A: This might not be what you need, but do you know of
PostgreSQL execute and load SQL?

This algorithm performs a SQL database query on a PostGIS database
connected to QGIS and loads the query results as a new layer.

e = iface.mapCanvas().extent()

xmin = e.xMinimum()
xmax = e.xMaximum()
ymin = e.yMinimum()
ymax = e.yMaximum()
sqlquery = 'select * from public.ok_bs_riks t1 where st_intersects(t1.wkb_geometry, st_makeenvelope({0}, {1}, {2}, {3}, 3006))'.format(xmin, ymin, xmax, ymax)

processing.runAndLoadResults("qgis:postgisexecuteandloadsql",
    {'DATABASE':'lmv',
    'SQL':sqlquery,'ID_FIELD':'id','GEOMETRY_FIELD':'wkb_geometry'})

A: You can create a temporary layer based on your Postgis layer.
You can either filter features of the layer wich intersect the canvas extent, or filter the features wich are completly within the canvas extent.
On the example below, I have a layer (red), a canvas extent (red line) zoomed on the green feature, features intersecting the extent (pink features) and features within the extent (purple features).

To create those 2 layers I used this code :
import tempfile
tf = tempfile.TemporaryDirectory()

# IMPORT YOUR LAYER

if self.ctrs_cibles.featureCount() > 0:
    # Creation of the layer with the features wich intersect the extent
    self.ctrs_cibles.selectByRect(extent)
    writer = QgsVectorFileWriter.writeAsVectorFormat(self.ctrs_cibles, tf.name +'/'+'filtered_layer_intersect.shp', "utf-8", self.ctrs_cibles.crs(), "ESRI Shapefile", onlySelected=True)
    iface.addVectorLayer( tf.name +'/'+'filtered_layer_intersect.shp', '', 'ogr')
    # Creation of the layer with the features wich are within the extent
    inside_extent_ids = []
    for feature in self.ctrs_cibles.getSelectedFeatures():
        if feature.geometry().within(QgsGeometry().fromRect(extent)):
            inside_extent_ids.append(feature.id())
    self.ctrs_cibles.selectByIds(inside_extent_ids)
    writer = QgsVectorFileWriter.writeAsVectorFormat(self.ctrs_cibles, tf.name +'/'+'filtered_layer_within.shp', "utf-8", self.ctrs_cibles.crs(), "ESRI Shapefile", onlySelected=True)
    iface.addVectorLayer( tf.name +'/'+'filtered_layer_within.shp', '', 'ogr')

A: Finally I found a third way to filter my vector layer, without creating a shapefile : I use the "materialize" method from the "qgsVectorLayer"class, to create a memory layer which contains only the query result (the query  here returns shapes which intersect the map canvas).
self.ctrs_cibles=QgsVectorLayer(self.uri.uri(), "contours", "postgres")
extent = self.iface.mapCanvas().extent()
self.ctrs_cible_canvas = self.ctrs_cibles.materialize(QgsFeatureRequest().setFilterRect(extent))

Then I insert the memory layer "self.ctrs_cible_canvas" at the top of the map legend :
QgsProject.instance().addMapLayer(self.ctrs_cible_canvas, False)
root = QgsProject.instance().layerTreeRoot()
root.insertLayer(0, self.ctrs_cible_canvas)

At last, I use the filtered memory layer, and I destruct it when I don't need it anymore.
Hope this will help...


text:
Q: css grid - shift right column to the left when left column is dynamic I've got the following setup:

section {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-template-rows: 1fr 1fr;
  grid-column-gap: 1em;
}

.a {
  background-color: green;
  grid-column: 1/7;
  griw-row: 1;
}

.b {
  background-color: grey;
  grid-column: 7/-1;
  grid-row: 1;
}

.c {
  background-color: blue;
  grid-column: 1/7;
  grid-row: 2;
}

.d {
  background-color: yellow;
  grid-column: 7/-1;
  grid-row: 2;
}

    Content b

    Content c

    Content d

The element with css class .a is dynamic and not always available. How can I shift right column (.b) to the left when .a column is not available?
Note: I can't use grid-auto-columns as IE11 doesn't support it.

A: Don't explicitly define the column positions. Simply set the number of column and the auto placement will do the job for you:

section {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-template-rows: 1fr 1fr;
  grid-column-gap: 1em;
  margin: 5px;
}

section > * {
  grid-column: span 6; /* all the items should take 6 columns*/
}

.a {
  background-color: green;
}

.b {
  background-color: grey;
}

.c {
  background-color: blue;
  grid-row: 2;
}

.d {
  background-color: yellow;
  grid-row: 2;
}

    Content b

    Content c

    Content d

    Content a

    Content b

    Content c

    Content d


text:
Q: How can we make QTableWidget accessible from multiple threads and placing QPushButtons in a cell from another thread.? I am new in Qt.I have a QTableWidget which is suppose to get continuous data from different threads of RTI DDS subscriber.I was using setUpdatesEnabled() property of the QTableview for updating values from another class.
But it also blocks the QTableWidget for in-between operations like selecting another row  and whenever i try to add QPushButton in a certain column of QTableWidget with the help of setCellWidget(),it is making a separate PushButton instead of placing it inside that cell.

A: As commented, you should do no GUI update from anywhere but the main thread. So use a signal/slot connection to go back from a worker thread to the main thread and then do the GUI update (emit the signal from the worker thread and make sure the slot is being executed from the main thread, this should behave like this with default connection). Be careful to the lifetime of the variables passed to the emited signal if slot is executed through a Qt::QueuedConnection.
Then, for your QPushButton not being in the cell. Make sure its parent is the QTableWidget upon creation (but I doubt this is really mandatory because I expect QTableWidget will make itself parent of the widget when setCellWidget is called).
It's hard to hep more with no code being posted in the OP.


text:
Q: Large File Upload Errors with PHP I have an image upload for a slideshow, and the users are continuously uploading files that are 2MB plus.  Files under this size work fine, but files over the size cause what looks like a browser timeout.
Here are my php ini settings:

*

*Max memory allocation: 12M

*Max file upload size: 10M

*Max HTTP Post size: 10M

*Max execution time: 60

*Max input parsing time: 120

These settings are in the configuration file itself, and I can change them directly.  Changes show up when using phpinfo().
I am running on an apache server and php 4.3.9(client's choice, not mine).  The apache server's request limit is set to default, which I believe is somewhere around 2GB?
When I use the firebug network monitor, it does look like I am not receiving a full response from the server, though I am not too experienced at using this tool.  Things seem to be timing out at around 43 seconds.
All the help I can find on the net points to the above settings as the culprits, but all of those settings are much higher than this 2MB file and the 43 second time out.
Any suggestions at where I can go from here to solve this issue?
Here are relevant php ini settings from phpinfo().  Let me know if I need to post any more.

*

*file_uploads  On  On

*max_execution_time    60  60

*max_input_nesting_level   64  64

*max_input_time    120 120

*memory_limit  12M 12M

*post_max_size 10M 10M

*safe_mode Off Off

*upload_max_filesize   10M 10M

*upload_tmp_dir    no value    no value

A: Make sure you have error reporting activated in php.ini: display_errors = On; this might give you a clue about what's going on. Production servers usually (should) have error reporting disabled.
I recently had a similar problem, and increasing the memory_limit setting worked for me. If you read files content into variables, each variable will take about as much memory as the file size, increasing the scripts memory requirements.

A: Where are those settings? If you're using .htaccess then your Apache configuration might not be allowing you to override those settings.
I'd suggest checking with a phpinfo() call if those settings are indeed being applied or not:
<?php
  phpinfo();
?>

A: If it's a shared host, your host might have set a limit to override yours.
Otherwise, try making the POST limit higher than the file upload size. AFAIK, uploads are POSTED.

A: If the problem is due to the Host overriding your timeout, you can look for a host that still uses Apache 1:  In Apache 1 the local .htaccess overrides the global setting even for the timeout.
Otherwise, there are dozens of Java applett uploaders available for just a few dollars (Google it).  They split the file, upload the parts and put the parts back together transparently.
This is a guaranteed fix for timeout, and has the added advantage of letting users pause and resume their upload, see the progress, et all.
(Flash based uploaders don't have this advantage.)


text:
Q: How to access queue of IntentService? I have an activity which puts several upload processes into the queue of an IntentService. Now i would like to show a list of the pending and started uploads, and a button to stop an upload.
based on this question Asking an IntentService for information about its queue i started to implement an external queue but so far i have no idea how to stop a specific task.
Are there any better ways how to manage the queue of an IntentService?

A: Register a BroadCastReceiver("stopUpload") in your IntentService to stop uploading when this intent is received. Trigger that intent from your activity's sendBroadcast("stopUpload").

A: Aren't you better off with a Service and AsyncTasks ?


text:
Q: xslt issue after converting html to xslt with
A: Well an XSLT stylesheet needs to be a namespace well-formed XML document. The syntax <script type='text/javascript' src="slider/js/jquery-1.4.4.min.js" jquery.mobile, carousel></script> is not XML syntax so you can't use that within an XSLT stylesheet. I am not sure what purpose that syntax would have with HTML either so I can't suggest how to achieve its purpose with proper XML syntax.

A: An XSLT stylesheet must be a well-formed XML document.
The provided text:
<script type='text/javascript' src="slider/js/jquery-1.4.4.min.js" jquery.mobile, carousel></script>
<script type="text/javascript" src="slider/js/jquery-ui-1.8.5.js" jquery.mobile, carousel></script>

isn't a well-formed XML fragment (there is text after the src attribute, which isn't allowed within an XML element), therefore its inclusion into an XSLT stylesheet makes the whole stylesheet non-well-formed XML document.


text:
Q: Class calling with strings I might have been mis-understood, I want to create objects and specify which class the object is by using a string.

A: Yes, you can use reflection for that.
To get a class, use
// if your class is in package com.foo and is named Bar
Class<?> klass = Class.forName("com.foo.Bar");

Read the tutorial for more details.


text:
Q: PHP – Find specific words in $_POST I have made a login that is vulnerable for sql injections. Which is great. But I would like to avoid someone making use of DROP TABLE in the login. Can I, for example, somehow check if the input holds words like drop or table.
Thanks.

A: I recommend that you use my simple, PDO database library which will solve your SQL injection problems.
Read the code, it's not very long (~3kb) and it will teach you how you should be working with database queries using prepared statements. Then, later on you can move to real database library with features like migrations, query builders, and ORM implementations.
$pdo = new PDO(...)

$name = $_POST['name'];
// @todo make sure it's a good name

$statement = $pdo->prepare('INSERT INTO `user` (`name`) VALUES (?)');
$statement->execute(array($name));

$user_id = $pdo->lastInsertId();

Update
Ok, so I just re-read you question and you actually want a SQL injection demo system - you just don't want it to be susceptible to certain kinds of SQL injects? This sounds like a bad idea that isn't worth the trouble. Setup a SQLite database which can be destroyed and re-created each page request and then you don't need to worry.

A: if (false !== stripos($_POST['username'], 'DROP')) will work if you want to know if the word "DROP" has been mentioned in the "username" field posted.


text:
Q: Adding an entity from master entity in Spring JPA I am trying to do ORM and add from a parent entity (Batch) to the child entity (Candidate),
I made the relations as below:
Batch Class:
    @OneToMany(mappedBy = "batch", cascade = CascadeType.ALL)
    private List<Candidate> candidates;

Candidate Class:
    @ManyToOne
    @JoinColumn(name = "BatchID")
    private Batch batch;

I tried to use JPA Repository from the BatchRepository and from the CandidateRepository
Here I tried to add it via the parent entity, but it didn't work:
    public void addCandidateToBatch(int batchId, int candidateId) {
        Batch batch = batchRepository.findById(batchId).get();

        Candidate candidate = candidateRepository.findById(candidateId).get();

        batch.getCandidates().add(candidate);
        batchRepository.save(batch);
    }

Alternatively also tried to add it from the child entity, and it actually worked :
    public void addBatchToCandidate(int batchId, int candidateId) {
        Candidate candidate = candidateRepository.findById(candidateId).get();
        Batch batch = batchRepository.findById(batchId).get();
        candidate.setBatch(batch);
        candidateRepository.save(candidate);
    }

Can someone help enlighten me why did it work on one side, but wont work on the other?
And is there a way to make both of them work?


text:
Q: what's the difference between devMiddleware.publicPath and static.publicPath https://github.com/webpack/webpack-dev-server/blob/master/migration-v4.md
was reading this and noticed that you can use publicPath 2 ways. I'm not sure what the difference is.


text:
Q: hide spinner load after end script I'm trying to show the spinner the moment the AJAX call starts and hide it the moment the AJAX call ends. The problem is that I can't hide the spinner after the script ends.
Does anyone have any ideas?
<form>

Carica directory

          View Details

            Loading...

</form>

$(function() {
  $('a#firstAlimentazione').bind('click', function() {
    spinner = $('#spinnerLoad');
    spinner.show();
    $.getJSON('/firstScript', function(data) {
      spinner.hide()
    });
    return false;
  });
});

A: Use success function in your ajax code.


text:
Q: while element not found load ajax I have a page which contains long paginated content. Now for accessing one single item I want to load pages until I found desired item. Problem is my "while" loops always went into infinite loop. After some research I found that because of async behaviour of ajax it never finds element. here is the code I am working with
While loop for loading content until element not found :
$(document).ready(function(){
    if(document.getElementById('selectedItem')) {
        totalPages = $("#selectedItem").attr("totalPages");
        trgtElementUrl = $("#selectedItem").val();

        var targetElement = $("#" + trgtElementUrl);
        i = 2;

        //getting $('#'+trgtElementUrl).length always 0

        while(!($('#'+trgtElementUrl).length)) {
            $('#page' + i).trigger("click");
            i++;
        }

        target_top = $('#'+trgtElementUrl).offset().top;
        target_top = target_top - 10;

        $('html, body').animate({scrollTop:target_top}, 500);

        $(".summaries li").removeClass();

        $('#'+trgtElementUrl).addClass('active');
    }

});

And ajax call by triggering click event
$('a.loadMore').live("click",function(event){
    $(this).hide();
    $(".loaderImage").show();
    event.preventDefault();
    var link = $(this).attr("href");
    $.ajax({
        url: link,
        dataType: "html",
        success: function(data) {

            if($('a.loadMore').parent().parent().hasClass('advertisingGrid')){
                var items = $(data).find('ul.advertisingGridItems').html();
                $(items).hide().appendTo('ul.advertisingGridItems').show('normal');
            } else {
                var items = $(data).filter('ul.summaries').html();
                var subnav = $(data).filter('nav.subnav');
                var itemLinks = $(subnav).find('ul').html();
                $('div#pagination').remove();
                $(items).appendTo('ul.summaries');
                $(itemLinks).appendTo('.subnav ul');
            }

            $(".loaderImage").hide();
        }
    });
    return false;
});

This always works fine with synchronous ajax call. Is it possible to make it work without synchronous ajax call. Thanks

A: Instead of requesting individual pages change your AJAX request to include the name/ID of the item you are searching for and current page number.
Have the server side code respond to this with a list of pages/items between your current page and the target page (the page containing the target item).
Once the response is received animate the received pages as per client request (the same way you are doing it now).
The difference here is that you are making one asynchronous request and you receive all the data you need. From there on you can animate in any way you want using CSS and JS.
Another benefit of this approach is that you can properly handle connection errors, request exceptions and other exceptions that might result when the target item is not found.


text:
Q: How to properly call ajax from jquery to Servlet? I have a problem with calling ajax requests.the Servlet returns whole page as response
HTML Code
<form action="userlogin" method="POST">
            User name : <input type="text" name="username" id="username"/>

            Password : <input type="text" name="password" id="password"/>

            <input type="submit" value="Login" name="submitbtn" id="submitbtn"/>

</form>

JQuery Code
$(document).ready(function () {
$("input[name='submitbtn']").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: 'userlogin',
        type: 'POST',
        data: $("form[action='userlogin']").serializeArray(),
        success: function (responseText) {
            if (responseText != 'failure')
                $("form[action='userlogin']").submit();
            else
                $('#failedText').text('Invalid Username or password');
        }
    });

});
});

Serlet Code
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (username.equals("admin") && password.equals("password")) {
    path = "adminhome.html";
    response.sendRedirect(path);
}else
    response.getWriter().write("failure");

if it is failure it works the way i wanted, if it success i need to navigate to admin home page,but the code responses with the whole page as response text.

A: When you do a response.sendRedirect(path), the browser would again make a call to load the new path. In your case the first request to userlogin
is a AJAX call and $.ajax would follow the redirects and fetch the final html to be rendered and hence you are getting that result.
Instead of doing a sendRedirect, you can return the path as a string and load the content by using JS.
Update the Servlet code for admin user check
if (username.equals("admin") && password.equals("password")) {
    path = "adminhome.html";
    response.getWriter().write(path);
}

and update the JS to
success: function (responseText) {
    if (responseText != 'failure')
        // make sure you provide the correct URL from the server
        window.location = responseText;
    else
        $('#failedText').text('Invalid Username or password');
}


text:
Q: Kotlin for loop not printing in Kotlin Script I'm new to Kotlin and I'm playing with the for loop, in Kotlin Script (*.kts file) I have this in the file:
for (i in 1..5) print("$i, ")

I did think it would print the number 1 through 5 separated by commas in one line like this:
1, 2, 3, 4, 5,

But instead I don't get any output on the command line. I'm running this on a Mac via
kotlin ranges.kts

If I put anything behind this single for loop, like a seperate println() or if I replace the print in the loop with println, it works and gives me output.
I don't get this behaviour. Can anyone explain this to me?
Edit1:
Versions:
kotlin: 1.3.71
MacOS 10.15.4 (Catalina)

A: This has nothing to do with the for loop and everything to do with print. It works if you add System.out.flush() at the end of the script. By default, writes to System.out (which print uses under the hood) don't always flush, and its likely that the Kotlin script runner isn't flushing the standard output stream before exiting.
This is also why using println works, as you noted -- if you look at the implementation of println in PrintStream, you'll see that it does flush its internal text and character output streams.
I created issue https://youtrack.jetbrains.com/issue/KT-38263.