text:
Q: How would I remove borders from all Floating windows in XMonad There are several similar questions but none quite solve it for me, for example this question explains how to remove borders from fullscreen floating windows.
Using XMonad.Layout.NoBorders you can do lots of cool stuff like remove borders from certain windows or if it is the only window or only fullscreen floating windows.
I couldn't find anything for all floating windows, however if someone could just point me to some tool that I could use to check if a window is floating or not, I am sure I could try hack up a solution.
Any suggestions are welcome

A: I'll be using the source code of XMonad.Layout.NoBorders as a reference, since I can't find anything more fitting that already exists. We want to see how it implements "remove borders on fullscreen floating windows", to see if it can be easily relaxed to "remove borders on floating windows" (without the fullscreen constraint).
According to the answer on the question you linked:
layoutHook = lessBorders OnlyFloat $ avoidStruts $ myLayout

OnlyFloat seems to be the specifier for "remove borders on fullscreen floating windows", so let's check the definition of that:
data Ambiguity = Combine With Ambiguity Ambiguity
               | OnlyFloat
               | Never
               | EmptyScreen
               | OtherIndicated
               | Screen
    deriving (Read, Show)

Not too helpful on its own. We should look elsewhere to see how the code treats these values.

It's a pretty safe bet that the first function to check is lessBorders:
lessBorders :: (SetsAmbiguous p, Read p, Show p, LayoutClass l a) =>
        p -> l a -> ModifiedLayout (ConfigurableBorder p) l a
lessBorders amb = ModifiedLayout (ConfigurableBorder amb [])

From the type signature of lessBorders, we can see that:
OnlyFloat :: (SetsAmbiguous p, Read p, Show p) => p

This is a good sign, as it means lessBorders doesn't explicitly expect an Ambiguity: we can extend the functionality here by implementing our own SetsAmbiguous and passing it to the existing lessBorders. Let's now look at SetsAmbiguous, and Ambiguity's implementation of it:
class SetsAmbiguous p where
    hiddens :: p -> WindowSet -> Maybe (W.Stack Window) -> [(Window, Rectangle)] -> [Window]

instance SetsAmbiguous Ambiguity where
    hiddens amb wset mst wrs
      | Combine Union a b <- amb = on union next a b
      | Combine Difference a b <- amb = on (\\) next a b
      | Combine Intersection a b <- amb = on intersect next a b
      | otherwise = tiled ms ++ floating
      where next p = hiddens p wset mst wrs
            nonzerorect (Rectangle _ _ 0 0) = False
            nonzerorect _ = True
            screens =
              [ scr | scr <- W.screens wset,
                      case amb of
                            Never -> True
                            _ -> not $ null $ integrate scr,
                      nonzerorect . screenRect $ W.screenDetail scr]
            floating = [ w |
                        (w, W.RationalRect px py wx wy) <- M.toList . W.floating $ wset,
                        px <= 0, py <= 0,
                        wx + px >= 1, wy + py >= 1]
            ms = filter (`elem` W.integrate' mst) $ map fst wrs
            tiled [w]
              | Screen <- amb = [w]
              | OnlyFloat <- amb = []
              | OtherIndicated <- amb
              , let nonF = map integrate $ W.current wset : W.visible wset
              , length (concat nonF) > length wrs
              , singleton $ filter (1==) $ map length nonF = [w]
              | singleton screens = [w]
            tiled _ = []
            integrate y = W.integrate' . W.stack $ W.workspace y

hiddens is the only method here that we need to implement. Its arguments are our SetsAmbiguous value, a WindowSet, and some other things, and it returns a list of windows that should not show borders. There's a lot of logic for the combining operations and other Ambiguity values, but those don't matter to us right now. What we care about is this snippet:
            floating = [ w |
                        (w, W.RationalRect px py wx wy) <- M.toList . W.floating $ wset,
                        px <= 0, py <= 0,
                        wx + px >= 1, wy + py >= 1]

This is very promising. It defines a set of floating windows by extracting all windows from the floating section of the WindowSet, converting it to a list (initially it's a Data.Map), and filtering out all the windows that don't cover the entire screen. All we need to do is remove the filter.

After making that change, and removing all unnecessary code pertaining to tiled windows and set operations (which is most of the implementation), we end up with simply:
import XMonad.Layout.NoBorders
import qualified XMonad.StackSet as W
import qualified Data.Map as M

data AllFloats = AllFloats deriving (Read, Show)

instance SetsAmbiguous AllFloats where
    hiddens _ wset _ _ = M.keys $ W.floating wset

We can then say:
layoutHook = lessBorders AllFloats $ myLayout...


text:
Q: baasbox on openshift error 503 I have a small problem, i'am trying to install the mbaas "baasbox" on openshift and i'am getting 503 page, what does it could be??
here is the tutorial that i followed here
the rhc tail give me
[2014-04-11 01:13:50] INFO WEBrick 1.3.1
[2014-04-11 01:13:50] INFO ruby 1.8.7 (2011-06-30) [x86_64-linux]
[2014-04-11 01:13:50] INFO WEBrick::HTTPServer#start: pid=398035 port=8080
127.8.255.129 - - [11/Apr/2014:01:14:27 EDT] "GET / HTTP/1.1" 200 39915

-> / 127.8.255.129 - - [11/Apr/2014:01:54:06 EDT] "GET / HTTP/1.1" 304 0
-> / [2014-04-11 01:57:39] INFO going to shutdown ... [2014-04-11 01:57:39] INFO WEBrick::HTTPServer#start done.

and here is the content of the start file
BASEDIR=$(dirname $0)
$BASEDIR/stop
rm $OPENSHIFT_REPO_DIR/bin/RUNNING_PID

nohup java -Dorient.baasbox.path=$OPENSHIFT_DATA_DIR/baasbox -Dorient.baasbox.admin_password=admin -Dapplication.code=1234567890 -Dhttp.port=$OPENSHIFT_DIY_PORT -Dhttp.address=$OPENSHIFT_DIY_IP $* -cp "$OPENSHIFT_REPO_DIR/bin/lib/*" play.core.server.NettyServer $OPENSHIFT_REPO_DIR/bin $OPENSHIFT_DIY_LOG_DIR/baasbox.log  > $OPENSHIFT_DIY_LOG_DIR/nohup.log 2>&1 &

A: there was a problem in the baasbox start file.
here is the complete issue https://github.com/baasbox/baasbox/issues/303
the start file was updated in the baasbox repo, this is the new one.
BASEDIR=$(dirname $0)
$BASEDIR/stop
rm $OPENSHIFT_REPO_DIR/bin/RUNNING_PID

nohup java -Dorient.baasbox.path=$OPENSHIFT_DATA_DIR/baasbox -Dorient.baasbox.admin_password=admin -Dapplication.code=1234567890 -Dhttp.port=$OPENSHIFT_DIY_PORT -Dhttp.address=$OPENSHIFT_DIY_IP $* -cp "$OPENSHIFT_REPO_DIR/bin/lib/*" play.core.server.NettyServer $OPENSHIFT_REPO_DIR/bin $OPENSHIFT_DIY_LOG_DIR/baasbox.log   &

redpajama_set_name: RedPajamaStackExchange


text:
Q: htlatex doesn't notice font change after tikz picture Even a minimal tikz picture in my causes htlatex not translating commands like \emph or \textbf if they come after a tikz picture.
Here is a minimal example
\documentclass{article}
\usepackage{tikz}

\begin{document}

\emph{Emphasize}, \textbf{bold},\texttt{typewriter},\textit{italics}
\tikz \draw (0,0) -- (0,1);
\emph{Emphasize}, \textbf{bold},\texttt{typewriter},\textit{italics}

\end{document}

Can anybody else verify this bug? I have texlive 2014 as it comes with Fedora 22.
After posting I did some searching and I figured out how to fix the bug:
Create a file called, say, bugfix.conf with
\Preamble{html}

% Translate \textbf, \textit and \texttt directives into ,  and
\Configure{emph}{\ifvmode\ShowPar\fi\HCode{}}{\HCode{}}
\Configure{textbf}{\ifvmode\ShowPar\fi\HCode{}}{\HCode{}}
\Configure{textit}{\ifvmode\ShowPar\fi\HCode{}}{\HCode{}}
\Configure{texttt}{\ifvmode\ShowPar\fi\HCode{}}{\HCode{}}

\begin{document}
\EndPreamble

in it.  Then run htlatex as
htlatex file.tex "bugfix.conf"


text:
Q: he method executequery() cannot take arguments on callablestatement I'm writing a program in which I want to delete selected rows from jtable which must necessarily be done through stored procedure using java .
Ι create the following stored procedure (mssql):
USE [Lab]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[usp_member_delete]
    -- Add the parameters for the stored procedure here
    @members_id int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
delete from members where Members_id=@members_id
END

And the java code to call the procedure
 private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {
        if(!jTable2.getSelectionModel().isSelectionEmpty()){
        int click=JOptionPane.showConfirmDialog(this,"Are you sure","Confirm",JOptionPane.YES_NO_OPTION);
        if(click==JOptionPane.YES_OPTION)

        try {
       Connect c=new Connect();
       Connection con=c.start();
       //Statement ps=con.createStatement();
       CallableStatement ps=con.prepareCall ("{call usp_member_delete(?,?)}");
       int index []=jTable2.getSelectedRows();
       for (int i=0;i<index.length;i++)
       {String id=""+jTable2.getValueAt(index[i], 0);
       //ps.execute("delete from members where member_id="+id);
       ps.executeUpdate(id);
         c.stop();
       }

     DefaultTableModel mod=(DefaultTableModel)jTable2.getModel();
     for (int i=0;i<index.length;i++)
     mod.removeRow(index [i]-i);

     }catch (Exception e){JOptionPane.showMessageDialog(this, e);}
    }
    }

Iam getting error the method executequery() cannot take arguments on preparestatement or callablestatement.Could you please advice?
Thank you in advance for your answer
Elpiniki

A: I've read it and I've already created connections for other purposes like insert.T (as examples following codes)    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
 String name=jTextField2.getText();
 String email =jTextField3.getText();
 String site=jTextField4.getText();
 String cv=jTextArea2.getText();
 String category =jComboBox2.getSelectedItem().toString();
  try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

     try (Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1\\ELPINIKI-TOSH\\SQLEXPRESS:1433;databaseName=Lab","sa","fir3w@ll")) {

         CallableStatement ps=con.prepareCall ("{call usp_member_insert(?,?,?,?,?,?,?)}");
         ps.registerOutParameter("Members_id", java.sql.Types.INTEGER);
         ps.setString(2,name);
         ps.setString(3,email);
         ps.setString(4,site);
         ps.setString(5,cv);
         ps.setString(6,category);
         ps.registerOutParameter("MemberCategory_id",java.sql.Types.INTEGER);

         int x=0; x=ps.executeUpdate();
         if (x!=0);
         JOptionPane.showMessageDialog(this, "Data inserted");

         jTextField2.setText("");
         jTextField3.setText("");
         jTextField4.setText("");
         jComboBox2.setSelectedIndex(0);
         jTextArea2.setText("");
       con.close();
     }
}catch(ClassNotFoundException | SQLException e)
{
System.out.println(e);
}
}

The problem is with the previous code i attached.Iam using row select and i want to delete the row using the procedure.
Thank you


text:
Q: INSERT IGNORE vs IN list() I have about 20,000 operations I have to do. I need to make sure the 'name' that I have is in the database. Which of the following patterns would be more efficient and why?
(1) in list()
cursor.execute('select * from names')
existing_names = [item[0 for item in cursor.fetchall()] # len = 2,000
for item in items:
    if item.name not in existing_names:
        cursor.execute('INSERT INTO names VALUES (%s,)', item.name)

(2) INSERT IGNORE
for item in items:
    cursor.execute('INSERT IGNORE INTO names VALUES (%s,)', item.name)

A: The obvious answer here is: test, don't guess.
But I'm pretty sure I can guess, because you've got an algorithmic complexity problem here.
Checking in against a list requires scanning the whole list and comparing every entry. If you do that for 20000 items vs. 2000 list entries, that's 40000000 comparisons. Unless you're skipping almost all 20000 of the SQL statements by doing so, it's almost certainly a pessimization.
However, with one slight change, it might be a useful optimization:
Checking in against a set is near-instant. If you do that for 20000 items vs. 2000 set entries, that's 20000 hashes and lookups. That could easily be worth saving even just a few thousand SQL queries. If you're on Python 2.7 or later, that's just a matter of existing_names = { … } instead of [ … ].
In case you're wondering, inside the database (assuming you have an index on the column), it's using a tree structure, so each look up takes logarithmic time. Even for a binary tree (which is over-estimating the real cost), that's under 11 comparisons for each lookup, which isn't quite as good as 1, but it's a lot better than 2000. (Plus, of course, that search is going to be optimized, because it's one of the core things that databases have to do well.)
And finally, at least with some database libraries, you can get a much bigger speedup by batching the inserts—maybe using executemany, or maybe preparing and loading bulk SQL—so you may be optimizing the wrong place anyway.

A: I would use method 2.  However, If you do not have a unique index on names your second method would definitely not insure that your names are unique.
If you need more info on creating a unique index, you can find it Here.
Your first method would appear to be less efficient then the second due to the fact that you have to first get the list of unique names, then test if it does not match any of them in the loop.
whereas in the second method, maintaining a a unique index may take overall more overhead than the first method, but would probably be more efficient than doing the processing outside the DB. Additional in second method you are only hitting the DB once too.


text:
Q: Should I not pass a pointer by reference if I don't modify it? In the following code, should I not pass newNode by reference, since I am not modifying it?
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
    if (nodePtr == 0)
        nodePtr = newNode;
    else if (newNode->value < nodePtr->value)
        insert(nodePtr->left, newNode);
    else
        insert(nodePtr->right, newNode);
}

A: Passing a pointer by reference introduces an additional level of indirection.
Essentially it correspond to passing a pointer to pointer, although the compiler can choose to optimize that.
So it can have a cost, in stack space or register usage, and in addition time on dereferencing, on a par with and in addition to the basic cost of passing a pointer by value.
There is no reason to potentially incur that cost if you don't modify the pointer.
At higher level, the reference indicates to a reader that the pointer will potentially be modified, when it's not.
And that's ungood.
So the answer is "no", both for performance reasons and for clarity you should better not pass the newNode pointer by reference when it's guaranteed not modified.

The given code
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
    if (nodePtr == 0)
        nodePtr = newNode;
    else if (newNode->value < nodePtr->value)
        insert(nodePtr->left, newNode);
    else
        insert(nodePtr->right, newNode);
}

… could be better expressed as
void IntBinaryTree::insert(TreeNode*& nodePtr, TreeNode* const newNode)
{
    if (nodePtr == nullptr)
        nodePtr = newNode;
    else if (newNode->value < nodePtr->value)
        insert(nodePtr->left, newNode);
    else
        insert(nodePtr->right, newNode);
}

The const communicates to a reader that that pointer value will remain the same throughout the function body.
I think the if-else is fine even if strict application of the Don't Repeat Yourself principle would indicate a conditional expression. That's because the if-else structure here helps to reduce local complexity of the code. With a pure expression it would look more complicated.

A: I think that passing it as a const pointer is ideal, since it helps show that it's not being modified.


text:
Q: Force user to reply to the "Authorize Geolocation" input each time he try to use it I'm currently working on an application which use the html5 geolocation api.
I've got a button meaning 'Locate me', how try to run - or rerun - the geolocation. If the user grant the access, there is no problem, but, if he refuse it, is there a way to display the authorisation prompt again?
Thanks for your replies!

A: It is not possible to display permissions prompt again but you can use error callback to handle PERMISSION_DENIED code (e.g., display further instructions for the user):
navigator.geolocation.getCurrentPosition(
  function(position) {
    // Success.
  },
  function(error) {
    if (error.code === error.PERMISSION_DENIED) {
      // Do Something.
    }
  }
);


text:
Q: Is "object.EnumConstant" instead of "Class::EnumConstant" a code smell? I have code like this
void disconnect(control::lib::DisconnectReason reason) {
   if(reason.getCode() == reason.C_Abnormal) {
     ...
   }
}

Is this a code-smell? I have never seen people doing that, but instead enum constants are accessed by the class name, usually. But this leads to long names, in my case
if(reason.getCode() == control::lib::DisconnectReason::C_Abnormal) {

What's the better thing to do here?

A: It's not a problem. Just like you can access class static variable with . or ->, you can access enumeration names the same way, it just shouldn't be used becuase . (or ->) suggests that this variable/name is caller-object's member, which is not true in these cases.


text:
Q: Balls in $\mathbb{R}^n$ and diameter Problem:
Let $A$ $\subseteq \mathbb{R}^n$ be a non-empty set with finite diameter. Show that there exists $x\in \mathbb{R}^n$ such that $A\subseteq B(x,2\operatorname{diam})$
May I have some hints?

A: Let $D = \operatorname{diam}(A) < \infty$. Let $x \in A$, then
$$\forall a \in A: d(x,a) \le \sup\{d(u,v): u,v \in A\} = D < 2D, \text{ or equivalently } a \in B(x,2D)$$
Hence $A \subseteq B(x,2D)$.


text:
Q: example of inverse limit and direct limit Does a direct limit of projective need to be projective? And is the inverse limit of injectives injective? I guess they need not, but I can't find an example.
Can you help please?

A: In his paper "Finitistic dimension...", Bass proved that a ring $R$ has the property that every direct limit of projective modules is projective $\Leftrightarrow R$ is perfect (meaning that every module has a projective cover) $\Leftrightarrow R$ satisfies the descending chain condition on principal ideals $\Leftrightarrow R/J(R)$ is semisimple and $J(R)$ is T-nilpotent (meaning that for any sequence $\{x_n\}_{n=1}^\infty \subseteq J(R)$ there is some $n$ with $x_1\cdots x_n = 0$).  To be more concrete (although I am not sure how useful this part is), he implicitly shows that $R$ is perfect $\Leftrightarrow$ certain direct limits of countably generated free modules are projective, namely ones of the form $\lim_{n \to \infty} F/G_n$, where $F$ is the free module spanned by $\{e_n\}_{n=1}^\infty$, $\{x_n\}_{n=1}^\infty \subseteq R$, and $G_n = \{e_i - x_ie_{i+1}\}_{i=1}^n$.

A: Neither.
The $\mathbb{Z}$-module $\mathbb{Q}$ is the direct limit of its finitely generated submodules. A finitely generated submodule of $\mathbb{Q}$ is actually infinite cyclic and so free. However $\mathbb{Q}$ is not projective.
So the claim is false even for filtered direct limits.
For inverse limits of injective modules, see this paper by Bergman on arXiv where it is proved that every module is the inverse limit of injective modules.


text:
Q: check status of ZFS pool on Linux host with Icinga monitoring system I have a server which is used for backup storage. It's running ZFS on Linux, configured with a RAID z2 data pool and shared via Samba.
I need to monitor the ZFS filesystem to at least be able to see how much space is available.
I thought a simple check_disk plugin will do this job.
I'm able to execute the command from the icinga server cli:
sudo -u nagios /usr/lib/nagios/plugins/check_nrpe -H <hostname> -c check_disk -a 10% 20% /data/backups
DISK OK - free space: /data/backups 4596722 MB (30% inode=99%);| /data/backups=10355313MB;13456832;11961628;0;14952036

But the GUI shows the following error:
DISK CRITICAL - /data/backups is not accessible: No such file or directory

It works under the check_mk monitoring system, but we are migrating from check_mk right now.
I don't have any problems with checking other filesystems (root, boot) in Icinga on this machine.
I would appreciate any advice.
Thanks

A: Line is in /etc/icinga/objects/linux.cfg on the server:
check_command               check_nrpe_1arg!check_backup

Line is in /etc/nagios/nrpe.cfg on the client
command[check_backup]=/usr/lib64/nagios/plugins/check_disk -w $ARG1$ -c $ARG2$ -p  $ARG3$


text:
Q: Command contains unrecognized phrase/keyword in visual fox pro9 I am trying to join a 5 tables, using left outer join from ms sql server server using visual fox pro 9.
but I am getting this error "Command contains unrecognized phrase/keyword."
Here is my code.
SQLEXEC(lnConn4,"SELECT [TIARA$Sales Invoice Header].No_,;
        [TIARA$Sales Invoice Header].[Sell-to Customer No_],;
        [TIARA$Sales Invoice Header].[Bill-to Name],;
        [TIARA$Sales Invoice Header].[Bill-to Address],;
        [TIARA$Sales Invoice Header].[Posting Date],;
        [TIARA$Sales Invoice Header].[VAT Registration No_],;
        [TIARA$Sales Invoice Header].[External Document No_],;
        [TIARA$Sales Invoice Header].[Shortcut Dimension 1 Code],;
        [TIARA$Sales Invoice Header].[Bill-to City],;
        [TIARA$Sales Invoice Line].No_,;
        [TIARA$Sales Invoice Line].Description,;
        [TIARA$Sales Invoice Line].[Unit of Measure],;
        [TIARA$Sales Invoice Line].Quantity,;
        [TIARA$Sales Invoice Line].[Unit Price],;
        [TIARA$Sales Invoice Line].[VAT %],;
        [TIARA$Sales Invoice Line].[Line Discount %],;
        [TIARA$Sales Invoice Line].[Amount Including VAT],;
        [TIARA$Sales Invoice Line].[Invoice Price],;
        [TIARA$Sales Invoice Line].Amount,;
        TIARA$Item.[Manufacturer Code],;
        TIARA$Customer.[Territory Code],;
        [TIARA$Sales Shipment Header].Note,;
        [TIARA$Sales Shipment Header].[Order No_],;
        [TIARA$Sales Shipment Header].No_;
    FROM    [TIARA$Sales Invoice Header];
    LEFT OUTER JOIN [TIARA$Sales Invoice Line];
    ON   [TIARA$Sales Invoice Header].No_ = [TIARA$Sales Invoice Line].[Document No_];
    LEFT OUTER JOIN TIARA$Item;
    ON  [TIARA$Sales Invoice Line].No_ = TIARA$Item.No_;
    LEFT OUTER JOIN TIARA$Customer;
    ON  [TIARA$Sales Invoice Line].[Sell-to Customer No_] = TIARA$Customer.No_;
    LEFT OUTER JOIN [TIARA$Sales Shipment Header];
    ON  [TIARA$Sales Invoice Header].[Order No_]     = [TIARA$Sales Shipment Header].[Order No_];
    WHERE   [TIARA$Sales Invoice Header].No_ = THISFORM.TEXT1.TEXT;
    ORDER BY [TIARA$Sales Invoice Header].[Posting Date] DESC;
    INTO TABLE  c:\tiarasys\temp\invoice")

A: If you want to create a multi-line string in Vfp, you can for example use Text/Endtext, e.g.
LOCAL lcSql
TEXT TO lcSql
    SELECT col1,
        col2,
        col4
    From ...
    Left Join....
    Where ...;
EndText
SQLEXEC(lnConn4,m.lcSql,...)

But if you want to send that string via ODBC, you would need to talk the Server slang, e.g. T-SQL for MS Sql Server, i.e. remove the FoxPro line-continuation ";" characters, and the Into Table part, everything the server would not understand.
And if the server does not understand, the SqlExec() function would return -1, and you can use Vfp's AError() function to get the ODBC error message.

A: Stefan is right that putting the whole query right into SQLExec() isn't a good idea.
That said, one problem here is the INTO TABLE clause at the end. That's not going to work in SQL Server and it isn't helpful. You want SQLExec() to give you back a cursor, which is what it does by default. If you really want to create a table from that cursor, you can with COPY TO, but usually you just work with the cursor.
Another problem is the reference to a textbox inside the quotes where you're building the query. That's going to just put that exact string in your query, not the textbox value.
Anyway, take Stefan's advice and then you can look at the query you've built and if the problem hasn't gone away, you'll be able to see what might be causing trouble.

A: Here your real problem, causing the error is the literal strings are limited to 255 characters in length. Your SQL command string literal is over 255.

*

*Either divide that into pieces where each literal is 255 characters at most

*Or write it within TEXT ... ENDTEXT block as Stefan suggested.

To expand on it:
clear
x = "12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890"

? m.x, LEN(m.x)

Would fail with the error you get. However, if you divide it into smaller pieces then you can concatenate to build up a string variable (up to 16 Mb according to documentation):
x = "12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890"+;
"12345678901234567890123456789012345678901234567890;
12345678901234567890123456789012345678901234567890"

? m.x, LEN(m.x)

Of course especially for SQL commands it is preferable to use TEXT...ENDTEXT. It has a big advantage of that you can copy paste the text content into SSMS and test your code there.
Then, the hidden error is INTO TABLE ... as Tamar pointed out. You can't create an on disk table like that using SQLExec(). Instead you would use the 3rd parameter to get the result into a cursor and then you can write to a table as you did from that cursor. ie:
SQLExec(m.myHandle, "select * from myTable", "crsResult")

Select * from crsResult into table ('c:\MyFolder\myTable')

Tamar also mentioned about referring text objects on form, for them you would use parameters in your code. ie:
myValue = thisfrom.txtSomething.Value
SQLExec(m.handle, "select * from myTable where myField = ?m.myValue", "crsResult")

And then to last probable error, your code sounds to be querying Excel tables? If so then that might be the wrong SQL for Excel (MSAccess engine doesn't really understand good ANSI SQL). If that happens to be the case, try using a pair of parentheses around each of your joins.

A: SQLEXEC(lnConn4,"Select [Posting Date],;
        [Bill-to Name],;
        [VAT Registration No_],;
        [Bill-to City],;
        No_,;
        [Order No_],;
        [Bill-to Address],;
        [Shortcut Dimension 1 Code];
         from [TIARA$Sales Invoice Header];
         where No_ = ?inv;
         order by [Posting Date] desc")

        COPY TO C:\Tiarasys\Temp\invoice_header
        SELECT 1
        USE C:\Tiarasys\Temp\invoice_header EXCLUSIVE ALIAS invoice_header
        orno = Order_no_

SQLEXEC(lnConn4, "Select [Unit of Measure],;
        Quantity,;
        No_,;
        [Document No_],;
        [Unit Price],;
        [Sell-to Customer No_],;
        Amount,;
        [Amount Including VAT] from [TIARA$Sales Invoice Line];
        where [Document No_] = ?inv")

        COPY TO C:\Tiarasys\Temp\invoice_line
        SELECT 2
        USE C:\Tiarasys\Temp\invoice_line SHARED ALIAS invoice_line
        sellno = Sell_to_cu
        num = No_

SQLEXEC(lnConn4, "Select No_,;
        [Manufacturer Code] from TIARA$Item;
        where No_ = ?num")

        COPY TO C:\Tiarasys\Temp\items
        SELECT 3
        USE C:\Tiarasys\Temp\items EXCLUSIVE ALIAS items

SQLEXEC(lnConn4, "Select No_,;
        [Territory Code] from TIARA$Customer;
        where No_ = ?sellno")

        COPY TO C:\Tiarasys\Temp\customer
        SELECT 4
        USE C:\Tiarasys\Temp\customer EXCLUSIVE ALIAS customer

SQLEXEC(lnConn4, "Select No_,;
        [Order No_],;
        Note,;
        [Sell-to Customer No_] from [TIARA$Sales Shipment Header];
        where[Order No_] = ?orno")

        COPY TO C:\Tiarasys\Temp\shipment_header
        SELECT 5
        USE C:\Tiarasys\Temp\shipment_header EXCLUSIVE ALIAS shipment_header


text:
Q: cURL command failed to delete pull-request from bit bucket with 400 error I am trying to delete a pull-request from bitbucket. I am using the following command,
curl -v -u {username}:{password} -X DELETE -H "Content-Type:application/json" https://{bitbucket.com}/rest/api/1.0/projects/{project_name}/repos/{repo_name}/pull-requests/{pull-request_id}
but the command fails with an error code 400. Please find the error:
{"errors":[{"context":null,"message":"No content to map to Object due to end of input","exceptionName":"java.io.EOFException"}]}.
I think I am missing something in the rest url. Please help me to resolve the issue. Thanks in advance

A: You need to pass the "version" of the pull-request (remember that the pull-request version starts in 0). Add the "-d @-" option to send the version in a here-document.
curl -v -u {username}:{password} -d @- -X DELETE -H "Content-Type:application/json" https://{bitbucket.com}/rest/api/1.0/projects/{project_name}/repos/{repo_name}/pull-requests/{pull-request_id} <<EOF
{
    "version": {version}
}
EOF


text:
Q: Is there a reason JavaScript developers don't use Array.push()? I commonly see developers use an expression like the following in JavaScript:
arr = []
arr[arr.length] = "Something"
arr[arr.length] = "Another thing"

Wouldn't push be more appropriate?
arr = []
arr.push("Something")
arr.push("Another thing")

A: I actually asked myself the same question at the start of this year. UPDATED with new test cases http://jsperf.com/array-push-vs-unshift-vs-direct-assignment/2
It appears that push is much faster in chrome, and about equal in FF. Also direct is faster in IE9, but I would be interested to see how it performs in IE10.
I would say that most developers would assume setting the length of the array, and then using direct assignment is faster, as is the case with most programming languages. But JavaScript is different. Javascript arrays aren't really arrays, they're just key/value maps just like all other JavaScript objects. So the pre-allocation is essentially falling on deaf ears.
Personally I prefer push (:

A: I believe that it's mostly habit.
Some developers use it simply because it's the way they are used to do it, and haven't considered that push would be an alternative.
Some developers have learned once upon a time that one method is much faster than another, and haven't reviewed this in light of the recent performance improvements of the Javascript engines.
Personally I use push frequently. Most of the time readability and maintainability is more important than performance, at least when the performance impact is small enough. The performance tests posted in the answers here show that the performance difference between various methods isn't very big.

A: Very often when I'm pushing an object into an array, I want the reference to that object to be returned to me. For example:
// Returns object
function createAndAdd(arr) {
  return arr[arr.length] = { id: 1 };
}
var obj = createAndAdd(arr);

Now I have the new object and I've added it to an array. If I'd used push then I would have been returned the length of the array. It would look like the following:
function createAndAdd(arr) {
  var obj = { id: 1 };
  arr.push(obj);
  return obj;
}

or even uglier, especially if the object gets big:
function createAndAdd(arr) {
  return arr[arr.push({ id: 1 }) -1];
}

Personally, I love functions with immediate return statements. Keeps it simple and easy to look at. Love the question. Thanks for asking it.

A: It's a way to limit nested braclets. If you have enough of them you cant see howmany there are or howmany you need (when later looking at the code). I would use a var, one should only have to count things one time.
bar = foo.length;
foo[ bar++ ] = "new item 0";
foo[ bar++ ] = "new item 1";
foo[ bar++ ] = "new item 2";
foo[ bar++ ] = "new item 3";

http://jsfiddle.net/vEUU3/

A: I think its not about performance, or at least is not such a big deal... what really matters here is declarative way vs imperative way.

A: Array.prototype.push method returns the updated array's length while the direct declaration returns the value that is being assigned. That's the only difference I see, but I usually read some best-practices recommendations about the push method being a better way to assign new values to an array.

A: Some coders don't recommend to use array.push() cause it modify the principal object. Instead of push(), you could use the spread operator:

let arrayOne = [1, 2, 3, 4];

let arrayTwo = arrayOne;

arrayTwo.push(5);

console.log(arrayOne);
console.log(arrayTwo);

// equals to arrayOne before the push()
let arrayOneAux = [1, 2, 3, 4];

// spread operator
let arrayThree = [...arrayOneAux, 5];

console.log(arrayOneAux);
console.log(arrayThree);


text:
Q: How to split Strings in Java including blanks (like in Python) I'm reading a comma-delimited list into Java where the elements may include blanks and single spaces. Here's a few sample lines:
 ,achieve,achievement,achievable,,,    (note the space before the first comma)
agree,agreement,, ,agreeable,agreeably (note the space between commas)
,apartment,,                           (no spaces)

In Java, the resulting String[] from using line.split(",") changes all blank elements to spaces except trailing ones, which it omits, like this:
" ", "achieve", "achievement", "achievable"
"agree", "agreement", " ", " ", "agreeable", "agreeably"
" ", "apartment"

I need all blank elements to be rendered as empty strings and single space elements to be rendered as single spaces, like this:
" ", "achieve", "achievement", "achievable", "", "", ""
"agree", "agreement", "", " ", "agreeable", "agreeably"
"", "apartment", "", ""

How to do this in Java?

A: To avoid removing trailing empty elements use split(delimiter, limit) with negative limit value like
split(",", -1).
DEMO:
String[] tests = {
        " ,achieve,achievement,achievable,,,",
        "agree,agreement,, ,agreeable,agreeably",
        ",apartment,,"
};
for (String line : tests){
    String[] elements = line.split(",", -1);
    StringJoiner sj = new StringJoiner(  "\", \"",  "\"",   "\"");
                                       //delimiter, prefix, suffix
    for (String element : elements){
        sj.add(element);
    }
    System.out.println(sj);
}

Output:
" ", "achieve", "achievement", "achievable", "", "", ""
"agree", "agreement", "", " ", "agreeable", "agreeably"
"", "apartment", "", ""

A: If you want to split on commas AND any surrounding whitespace, you can use this
str.trim().split("\\s+,\\s+")

A: If you want to replicate the exact behaviour of Python's str.split(), you need to trim for spaces and then use the overload that accepts a regular expression to match on white spaces like this:
str.trim().split("\\s+")

A: Here's a simple test program which I think illustrates what you are looking for:
public class s1 {
    public static void main( String[] args ) {
//      String si = " ,achieve,achievement,achievable,,,";
//      String si = "agree,agreement,, ,agreeable,agreeably";
        String si = ",apartment,,";
        String[] so = si.split(" *, *", -1);   /* split on comma and any space(s) next to it */
        for (String s : so) {
            System.out.println('"' + s + '"');
        }
    }

}

A: line.split(",") works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Instead if you use public String[] split(String regex, int limit) and call it with line.split(",", <any negative int>) then the pattern will be applied as many times as possible and the array can have any length.

So you can call it like line.split(",", -9).

The following is what happens with different limit values:

*

*limit = 0 : the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

*limit > 0 : the pattern will be applied at most limit - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter

*limit < 0 : the pattern will be applied as many times as possible and the array can have any length
Check the doc for more clarification.


text:
Q: Using Variable in JSON object Name I've been searching for a solution for this but I can't seem to come up with an answer, so hoping someone on here can help.
I have this JSON string stored in a cookie like so:
$.cookie('serviceTrip', JSON.stringify(serviceTrip));

I need to extract a value from this cookie based on a certain variable "n" that changes based on user input.
What I have is:
var n = 3;
var serviceTripValues = JSON.parse($.cookie('serviceTrip'));
var serviceTripStartValue = 'serviceTrip'+n+'start';
alert(serviceTripStartValue); //this produces serviceTrip3start
alert(JSON.parse($.cookie('serviceTrip')).serviceTrip3start); // this produces 12:00 as expected
alert(JSON.parse($.cookie('serviceTrip')).serviceTripStartValue); // this produces 'undefined'

I cant figure this out... I think it has something to do with the fact that serviceTripStartValue is a string and not an object but I don't know how to resolve it.

A: Try this -
alert(JSON.parse($.cookie('serviceTrip'))[serviceTripStartValue]);

A: You're already parsing the cookie contents, no need to do it twice:
alert(serviceTripValues[serviceTripStartValue]);

The reason your attempt didn't work is because you're treating serviceTripValues as if it were this:
serviceTripValues = {
    serviceTripStartValue:'12:00'
}

...when in fact, it's this:
serviceTripValues = {
    serviceTrip3start:'12:00'
}

Using array notation allows JavaScript to interpret the String stored in serviceTripStartValue instead of treating it as a literal object key.
Cheers


text:
Q: CSS Selector for the first drop down on website In the HTML page while inspecting a drop-down I press Ctrl + F to find the drop-down css selector and it is like that
div .wrapperDropdown

But I found two drop-down lists with the same css selector . the first has tab index = 1 and the second has tab index = 2
How to refer to the first one whose tab index = 1

السعودية

مصر

السعودية

الإمارات

المغرب

تونس

العراق

البحرين

الكويت

الجزائر

سلطنةعمان

قطر

لبنان

الأردن

الرياض

جدة

الرياض

مكة

الجبيل

الدمام

الظهران

الخبر

المدينه

I could solve the point of selecting the first drop-down but I can't select an option from it and I got error at the last line
Dim ie          As New InternetExplorer
Dim html        As HTMLDocument
Dim drp         As HTMLFormElement
Dim x           As Long
Dim e, r As Long

ie.Visible = True
ie.Navigate "https://www.masrawy.com/Islameyat/Prayer-Times"
Do While ie.readyState <> READYSTATE_COMPLETE: DoEvents: Loop
Set html = ie.document

Set drp = html.querySelector("div .wrapperDropdown[tabindex='1']")

drp.selectedIndex = 2

A: Assuming default is first active then use faster class selector of
.wrapperDropdown.active

Otherwise, shorten your existing to
.wrapperDropdown[tabindex='1']

being sure to use single quotes round number or double up on ".
To select an item, as they are anchor tags you need to click and can use nth-of-type to index into li nodes
html.querySelector(".wrapperDropdown[tabindex='1'] li:nth-of-type(2) a").Click


text:
Q: removing phpbb tag using regex javascript I'm trying to remove a rectangular brackets(bbcode style) using javascript, this is for removing unwanted bbcode.
I try with this.
theString .replace(/\[quote[^\/]+\]*\[\/quote\]/, "")

it works with this string sample:
theString = "[quote=MyName;225]Test 123[/quote]";

it will fail within this sample:
theString = "[quote=MyName;225]Test [quote]inside quotes[/quote]123[/quote]";

if there any solution beside regex no problem

A: The other 2 solutions simply do not work (see my comments). To solve this problem you first need to craft a regex which matches the innermost matching quote elements (which contain neither [QUOTE..] nor [/QUOTE]). Next, you need to iterate, applying this regex over and over until there are no more QUOTE elements left. This tested function does what you want:
function filterQuotes(text)
{ // Regex matches inner [QUOTE]non-quote-stuff[/quote] tag.
    var re = /\[quote[^\[]+(?:(?!\[\/?quote\b)\[[^\[]*)*\[\/quote\]/ig;
    while (text.search(re) !== -1)
    { // Need to iterate removing QUOTEs from inside out.
        text = text.replace(re, "");
    }
    return text;
}

Note that this regex employs Jeffrey Friedl's "Unrolling the loop" efficiency technique and is not only accurate, but is quite fast to boot.
See: Mastering Regular Expressions (3rd Edition) (highly recommended).

A: Try this one:
/\[quote[^\/]+\].*\[\/quote\]$/

The $ sign indicates that only the closing quote element at the end of the string should be used to determine the ending of the quote you're trying to remove.
And i added a "." before the asterisk so that this will match any sign in between. I tested this with your two strings and it worked.
edit: I don't exactly know how you are using that. But just as an addition. If you want the pattern also to match to a string where no attributes are added for example:
[quote]Hello[/quote]

You should change the "+" sign into an asterisk as well like this:
/\[quote[^\/]*\].*\[\/quote\]$/

A: This answer has flaws, see Ridgerunner's answer for a more correct one.
Here's my crack at it.
function filterQuotes(text)
{
    return text.replace(/\[(\/)?quote([^\/]*)?\]/g,"");
}


text:
Q: Return data only into an array I am performing a Mongodb collection.find using node.js, how do I return only the data without the column name into an array.
var cursor = collection.find( { title: title }, { title: 1, _id: 0 });
cursor.sort( { title: 1 });
cursor.toArray(function (err, all_documents) { .... });

{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}

A: collection.find(...).toArray().map( function(u) { return u.title; } )

or
var result = []
collection.find().forEach(function(u) { result.push(u.title) })


text:
Q: How to Read two XML files and return List(of object)? I have two xml files. I have to read them and return as a List( Of object).
Here is my function.
 Public Function GetData(ByVal name As String, ByVal city As String) As List(Of Object)
        'Return Nothing
 End Function

Thanks,
NJ

A: You may change return type into "Object" and then make it type cast to "List (Of Object)" , though it's ugly


text:
Q: How to determine the expected type of SQLAlchemy column from an instance? I have an instance of a SQLAlchemy model and am trying to determine the types that the columns accept. Some of the columns attributes are None at the time I need to determine
class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    login = Column(String())

Here is an pseudo code example of what I am trying to do.
user = User()
if type(inspect(user).get_property(id)) == Integer:
   print "The id column expects Integers"

How do I turn this pseudo code into real code?
Thanks!

A: isinstance(type(user).id.property.columns[0].type, Integer)


text:
Q: Canvas createPattern() and fill() with an offset I'm using the canvas to draw simple rectangles and fill them with a flooring pattern (PNG). But if I utilize a "Camera" script to handle transform offsets for the HTML5 canvas, the rectangle shape moves appropriately, but the fill pattern seems to always draw from a fixed point on the screen (I'm assuming the top left). Is there a way to "nail down" the fill pattern so it always lines up with the rectangle, no matter the canvas transform, or a way to add an offset on fill() that can be calculated elsewhere in the code? I could just use drawImage() of course, but drawing the rectangles is more versatile for my purposes.
        sampleDrawFunction(fillTexture, x1, y1, x2, y2) {
        // This is oversimplified, but best I can do with a ~10k lines of code
        x1 -= Camera.posX;
        x2 -= Camera.posX;
        y1 = -1 * y1 - Camera.posY;
        y2 = -1 * y2 - Camera.posY;

        // Coordinates need to be adjusted for where the camera is positioned

        var img = new Image();
        img.src = fillTexture;
        var pattern = this.ctx.createPattern(img, "repeat");
        this.ctx.fillStyle = pattern;

        // Translate canvas's coordinate pattern to match what the camera sees
        this.ctx.save();
        this.ctx.translate(Camera.posX - Camera.topLeftX, Camera.posY - Camera.topLeftY);
        this.ctx.fillStyle = pattern;
        this.ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
        this.ctx.restore();
}

Thank you.

A: Canvas fills (CanvasPatterns and CanvasGradients) are always relative to the context's transformation matrix, so they do indeed default at top left corner of the canvas, and don't really care about where the path using them will be be.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = begin; //!\ ALWAYS WAIT FOR YOUR IMAGE TO LOAD BEFORE DOING ANYTHING WITH IT!
img.crossOrigin = "anonymous";
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";

function begin() {
  const rect_size = 20;
  ctx.fillStyle = ctx.createPattern( img, 'no-repeat' );
  // drawing a checkerboard of several rects shows that the pattern doesn't move
  for ( let y = 0; y < canvas.height; y += rect_size ) {
    for ( let x = (y / rect_size % 2) ? rect_size : 0 ; x < canvas.width; x += rect_size * 2 ) {
      ctx.fillRect( x, y, rect_size, rect_size );
    }
  }

}
<canvas id="canvas" width="500" height="500"></canvas>

Now, because they are relative to the context transform matrix, this means we can also move them by changing that transformation matrix:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = begin; //!\ ALWAYS WAIT FOR YOUR IMAGE TO LOAD BEFORE DOING ANYTHING WITH IT!
img.crossOrigin = "anonymous";
img.src = "https://upload.wikimedia.org/wikipedia/commons/f/f7/Cool_bunny_sprite.png";

function begin() {
  const rect_size = 244;
  const max_speed = 5;
  let x_speed = Math.random() * max_speed;
  let y_speed = Math.random() * max_speed;

  ctx.fillStyle = ctx.createPattern( img, 'repeat' );

  let x = 0;
  let y = 0;
  requestAnimationFrame( anim );

  function anim( now ) {

    clear();

    x = (x + x_speed);
    y = (y + y_speed);

    if( x > canvas.width || x < -rect_size ) {
      x_speed = Math.random() * max_speed * -Math.sign( x_speed );
      x = Math.min( Math.max( x, -rect_size ), canvas.width );
    }
    if( y > canvas.height || y < -rect_size ) {
      y_speed = Math.random() * max_speed * -Math.sign( y_speed )
      y = Math.min( Math.max( y, -rect_size ), canvas.height );
    }

    // we change the transformation matrix of our context
    ctx.setTransform( 1, 0, 0, 1, x, y );
    // we thus always draw at coords 0,0
    ctx.fillRect( 0, 0, rect_size, rect_size );
    ctx.strokeRect( 0, 0, rect_size, rect_size );

    requestAnimationFrame( anim );

  }
  function clear() {
    // since we changed the tranform matrix we need to reset it to identity
    ctx.setTransform( 1, 0, 0, 1, 0, 0 );
    ctx.clearRect( 0, 0, canvas.width, canvas.height );

  }
}
<canvas id="canvas" width="300" height="300"></canvas>

We can even detach the path declaration from the filling by changing the transformation matrix after we declared the sub-path and of course by replacing the shorthand fillRect() with beginPath(); rect(); fill()

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = begin; //!\ ALWAYS WAIT FOR YOUR IMAGE TO LOAD BEFORE DOING ANYTHING WITH IT!
img.crossOrigin = "anonymous";
img.src = "https://upload.wikimedia.org/wikipedia/commons/f/f7/Cool_bunny_sprite.png";

function begin() {
  const rect_size = 244;
  const max_speed = 5;
  let x_speed = Math.random() * max_speed;
  let y_speed = Math.random() * max_speed;

  ctx.fillStyle = ctx.createPattern( img, 'repeat' );

  let x = 0;
  let y = 0;
  requestAnimationFrame( anim );

  function anim( now ) {

    clear();

    x = (x + x_speed);
    y = (y + y_speed);

    if( x > canvas.width || x < -rect_size ) {
      x_speed = Math.random() * max_speed * -Math.sign( x_speed );
      x = Math.min( Math.max( x, -rect_size ), canvas.width );
    }
    if( y > canvas.height || y < -rect_size ) {
      y_speed = Math.random() * max_speed * -Math.sign( y_speed )
      y = Math.min( Math.max( y, -rect_size ), canvas.height );
    }

    // we declare the sub-path first, with identity matrix applied
    ctx.beginPath();
    ctx.rect( 50, 50, rect_size, rect_size );
    // we change the transformation matrix of our context
    ctx.setTransform( 1, 0, 0, 1, x, y );
    // and now we fill
    ctx.fill();
    ctx.stroke();

    requestAnimationFrame( anim );

  }
  function clear() {
    // since we changed the tranform matrix we need to reset it to identity
    ctx.setTransform( 1, 0, 0, 1, 0, 0 );
    ctx.clearRect( 0, 0, canvas.width, canvas.height );

  }
}
<canvas id="canvas" width="300" height="300"></canvas>

But in your case, it sounds that transforming the whole drawing is the easiest and most idiomatic way to follow. Not too sure why you are modifying your x and y coordinates in relation to the camera. Generally, if we use a camera object it's for the objects in the scene don't have to care about it, and stay relative to the world.


text:
Q: Postgres stream replication master large diff between pg_current_xlog_location and sent_location I have postgres master/slave stream replication setup, after performing heavy write operations into master using COPY, pg_xlogs folder starts piling up WAL segment files. After checking pg_current_xlog_location and sent_location on master, and pg_last_xlog_receive_location on slave, I found out that there's a huge difference between pg_current_xlog_location and sent_location, while pg_last_xlog_receive_location on slave indicating it's catching up with sent_location.
According to postgres documentation (https://www.postgresql.org/docs/9.5/static/warm-standby.html#STREAMING-REPLICATION-MONITORING), situation like this indicates master is under heavy load. while in my case I don't have anything else running after the COPY statement is done. How should I debug this?
Another thing worth mentioning is I'm running postgres 9.5 inside docker. Network between two host machines is 2Gbit/s.

A: I am thinking the the archive_timeout is not set optimally. You can adjust this on how often you need to push this to slave.
WAL settings documentation:
https://www.postgresql.org/docs/current/static/continuous-archiving.html
Documentation home.
https://www.postgresql.org/


text:
Q: Custom ToC for appendices I would like to create a table of content for the Appendices that produce this result

Appendices
   A   First Appendix
   B   Second Appendix
   C   Third Appendix

So far I've tried with
\appendix
\addcontentsline{toc}{chapter}{Appendices}
\setcounter{section}{0}
\section{First Appendix}
\section{Second Appendix}
\section{Third Appendix}

which returns

Appendices
   .1   First Appendix
   .2   Second Appendix
   .3   Third Appendix

I know it's possible to change the numbering of sections to be alphabetical, but that will also affect all the sections in normal chapters.
Can you find a solution to this?

A: A change in the counter representation of section (i.e., \thesection) only works from the point at which you declare it. So, if the Appendix is the last chapter in your document, then you can adjust \thesection at that point with no ill effect to earlier sections:
\appendix
\chapter*{Appendices}% If \appendix doesn't insert a \chapter
\addcontentsline{toc}{chapter}{Appendices}% Print Appendix in ToC
\setcounter{section}{0}% Reset numbering for sections
\renewcommand{\thesection}{\Alph{section}}% Adjust section printing (from here onward)
\section{First Appendix}
\section{Second Appendix}
\section{Third Appendix}

Here is a complete minimal example highlighting the ToC output:

\documentclass{report}
\begin{document}

\tableofcontents

\chapter{A chapter}
\section{First section}
\section{Second section}
\section{Third section}

\appendix
\chapter*{Appendices}% If \appendix doesn't insert a \chapter
\addcontentsline{toc}{chapter}{Appendices}% Print Appendix in ToC
\setcounter{section}{0}% Reset numbering for sections
\renewcommand{\thesection}{\Alph{section}}% Adjust section printing (from here onward)
\section{First Appendix}
\section{Second Appendix}
\section{Third Appendix}

\end{document}


text:
Q: Case of using filtered statistics I was going through filtered stats in below link.
http://blogs.msdn.com/b/psssql/archive/2010/09/28/case-of-using-filtered-statistics.aspx
Data is Skewed heavily,one region is having 0 rows,rest all are from diferent regions.
Below is the entire code to reproduce the issue
create table Region(id int, name nvarchar(100))
go
create table Sales(id int, detail int)
go
create clustered index d1 on Region(id)
go
create index ix_Region_name on Region(name)
go
create statistics ix_Region_id_name on Region(id, name)
go
create clustered index ix_Sales_id_detail on Sales(id, detail)
go

-- only two values in this table as lookup or dim table
insert Region values(0, 'Dallas')
insert Region values(1, 'New York')
go

set nocount on
-- Sales is skewed
insert Sales values(0, 0)
declare @i int
set @i = 1
while @i <= 1000 begin
insert Sales  values (1, @i)
set @i = @i + 1
end
go

update statistics Region with fullscan
update statistics Sales with fullscan
go

set statistics profile on
go
--note that this query will over estimate
-- it estimate there will be 500.5 rows
select detail from Region join Sales on Region.id = Sales.id where name='Dallas' option (recompile)
--this query will under estimate
-- this query will also estimate 500.5 rows in fact 1000 rows returned
select detail from Region join Sales on Region.id = Sales.id where name='New York' option (recompile)
go

set statistics profile off
go

create statistics Region_stats_id on Region (id)
where name = 'Dallas'
go
create statistics  Region_stats_id2 on Region (id)
where name = 'New York'
go

set statistics profile on
go
--now the estimate becomes accurate (1 row) because
select detail from Region join Sales on Region.id = Sales.id where name='Dallas' option (recompile)

--the estimate becomes accurate (1000 rows) because stats Region_stats_id2 is used to evaluate
select detail from Region join Sales on Region.id = Sales.id where name='New York' option (recompile)
go

set statistics profile off

My question is we have below  stats available on both tables
sp_helpstats 'region','all'
sp_helpstats 'sales','all'

Table region:
statistics_name   statistics_keys
d1                    id
ix_Region_id_name     id, name
ix_Region_name        name

Table sales:
statistics_name    statistics_keys
ix_Sales_id_detail     id, detail

1.Why the estimation went wrong for thse below queries
select detail from Region join Sales on Region.id = Sales.id where name='Dallas' option (recompile)

--the estimate becomes accurate (1000 rows) because stats Region_stats_id2 is used to evaluate
select detail from Region join Sales on Region.id = Sales.id where name='New York' option (recompile)

2.When i created filtered stat as per author,i could see estimates correctly,but why we need to create filtered stats,how can i say i need filtered stats for my queries since  even when i created simple stats,i got same result .
Best i came across so far
1.Kimberely tripp skewed stats video
2.Technet stats whitepaper
But still not able to understand why filtered stats made a difference  here
thanks in advance.
Update :7/4
Rephrasing the question after martin and james answers:
1.Is there any way to avoid data skewness
  other than kimberely script ,one more way to estimate is to count number of rows for a value.
2.Have you faced any issues with data skewness in your experience.I assume it depends on large tables.But i am looking for some detailed answer
3.We have to take the IO cost for the sql to scan the table  and along with some blockings sometimes for a query which falls at the time of triggering update stats.do you see any overhead other than this in maintaining stats.
Reason being i am thinking to create filetered stats based on several conditions based on DTA input too.
thanks again

A: I would assume this is why it happens. You get the same estimate (500.5) rows because that SQL Server doesn't have statistics that would tell which IDs are the one that are related to which region. The statistics ix_Region_id_name have both fields, but since histogram exists for the first column only, it really doesn't help in estimations regarding how many rows will be in Sales table.
If you run dbcc show_statistics ('Region','ix_Region_id_name'), the result will be:
RANGE_HI_KEY   RANGE_ROWS   EQ_ROWS   DISTINCT_RANGE_ROWS   AVG_RANGE_ROWS
0              0            1         0                     1
1              0            1         0                     1

So this tells that there is 1 row for each ID, but there's no link to the names.
But when you create the statistics Region_stats_id (for Dallas) dbcc show_statistics ('Region','Region_stats_id') will show:
RANGE_HI_KEY   RANGE_ROWS   EQ_ROWS   DISTINCT_RANGE_ROWS   AVG_RANGE_ROWS
0              0            1         0                     1

So SQL Server knows that there is only 1 row, and it's ID 0.
Similarly Region_stats_id2:
RANGE_HI_KEY   RANGE_ROWS   EQ_ROWS   DISTINCT_RANGE_ROWS   AVG_RANGE_ROWS
1              0            1         0                     1

And the amount of rows in sales is in ix_Sales_id_detail will help to determine rows per ID:
RANGE_HI_KEY   RANGE_ROWS   EQ_ROWS   DISTINCT_RANGE_ROWS   AVG_RANGE_ROWS
0              0            1         0                     1
1              0            1000      0                     1

Info: This is now copy of the answer deleted by @MartijnPieters because this is the question I intended to answer for -- and I can't seem to do anything to the deleted answer. I accidentally wrote this first to TheGameiswar's other statistics question from today but I deleted myself already.


text:
Q: Getting the value inside the inner class How will I get the value inside the inner class in Android Studio 4.0.1. I tried to declare a global variable but still it doesn't work. I also tried this one declaring a final array but I still cannot get the value
public class FetchData {
    private Context con;

    public FetchData(Context con){
        this.con = con;
    }

    public String getPatientIDFromDatabase(){
        final String[] id = {""};
        StringRequest strRequest = new StringRequest(Request.Method.POST, "http://192.168.254.199/projects/AndroidServers/TheMedicalGCs/GetPatientID.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            id[0] = jsonObject.getString("PatientID");
                        }
                        catch (Exception e){
                            Toast.makeText(con, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(con, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
        );
        Volley.newRequestQueue(con).add(strRequest);

        return id[0];
    }
}

I just want that method to return the value comes from the JSON.

A: You can declare that as a static variable,
static final String[] id = {""};

A: I have removed constructor for your classFetchData and moved it as parameter to method getPatientIDFromDatabase(Context context). So the looks like this.
public class FetchData {

    public static String getPatientIDFromDatabase(Context context) {

        final String[] id = {""};

        StringRequest strRequest = new StringRequest(Request.Method.POST,
                "http://192.168.254.199/projects/AndroidServers/TheMedicalGCs/GetPatientID.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            id[0] = jsonObject.getString("PatientID");
                        } catch (Exception e) {
                            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
        );
        Volley.newRequestQueue(context).add(strRequest);

        return id[0];
    }
}

Now let's the value it is returning from FetchData class, but if you want other classes to get access to the return value, you need to method as static. Which i already added above.
Now let's get string value from other class named HomeActivity:
String value = FetchData.getPatientIDFromDatabase(context)

A: I already fixed the problem by declaring the final String[] id = {""} into a member variable and declare it as private String id only. I remembered that you cannot access the variable that is not declared as final inside the inner class.
public class FetchData {
    private Context con;
    private String id;

    public FetchData(Context con){
        this.con = con;
    }

    public String getPatientIDFromDatabase(){
        StringRequest strRequest = new StringRequest(Request.Method.POST, "http://192.168.254.199/projects/AndroidServers/TheMedicalGCs/GetPatientID.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            id = jsonObject.getString("PatientID");
                        }
                        catch (Exception e){
                            Toast.makeText(con, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(con, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
        );
        Volley.newRequestQueue(con).add(strRequest);

        return id;
    }
}


text:
Q: WooCommerce removing wrapping tags from products/categories Is it possible to remove tags, such as the <li> tags from around the products/categories in WooCommerce? I have tried searching for hooks, and more. Also, I successfully removed the <ul> tags from around the product set as well. I would like to spit out all product data in my cell since I am using foundation framework. Is this possible, or do I have to take an alternative route?

A:
To change the html structure in Woocommerce
You should need, most of the time, to make changes in the available Woocommerce templates.

First you should read how to override woocommerce templates via your active theme
Now to change (or remove) the <li> tags on products and product category archives, you need to override content-product.php and content-product_cat.php templates file.


text:
Q: Unable to translate morse to english I have a school project where I need to make a morse to english transaltor. I'm a newbie when it comes to Java so I was wondering if you could assist me. The problem is that I'm unsure on what I'm supposed to put on the while loop to turn the morse code to english. Any help would be appreciated. Thanks^^
public static void main(String[]args){
    HashMap<Character,String> translations=new HashMap<Character,String>();
    translations.put('A', ".-");
    translations.put('B', "-...");
    translations.put('C', "-.-.");
    translations.put('D', "-..");
    translations.put('E', ".");
    translations.put('F', "..-.");
    translations.put('G', "--.");
    translations.put('H', "....");
    translations.put('I', "..");
    translations.put('J', ".---");
    translations.put('K', "-.-");
    translations.put('L', ".-..");
    translations.put('M', "--");
    translations.put('N', "-.");
    translations.put('O', "---");
    translations.put('P', ".--.");
    translations.put('Q', "--.-");
    translations.put('R', ".-.");
    translations.put('S', "...");
    translations.put('T', "-");
    translations.put('U', "..-");
    translations.put('V', "...-");
    translations.put('W', ".--");
    translations.put('X', "-..-");
    translations.put('Y', "-.--");
    translations.put('Z', "--..");
    translations.put('0', "-----");
    translations.put('1', ".----");
    translations.put('2', "..---");
    translations.put('3', "...--");
    translations.put('4', "....-");
    translations.put('5', ".....");
    translations.put('6', "-....");
    translations.put('7', "--...");
    translations.put('8', "---..");
    translations.put('9', "----.");
    translations.put(' ', "   ");

    HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
    for (char key : translations.keySet()){
        reversedHashMap.put(translations.get(key), key);
    }Scanner scan=new Scanner(System.in);
    System.out.println("Welcome to the translator. Type 1 for English to Morse or type 2 for Morse to English: ");
    int choice=scan.nextInt();
    if(choice==1)
       engToMorse(translations);
    else if(choice==2)
        morseToEng(reversedHashMap);
    else{
        System.out.println("Invalid Input!");
    }
}
public static void engToMorse(HashMap<Character,String> translations){

    Scanner scan=new Scanner(System.in);
    System.out.println("Please enter the sentence that you want to translate to Morse here: ");
    String sentence=scan.nextLine().toUpperCase();
    int i=0;
    while(i<sentence.length()){
        System.out.printf(translations.get(sentence.charAt(i)));
        i++;
    }

    }
    public static void morseToEng(HashMap<String,Character> reversedHashMap){

    Scanner scan=new Scanner(System.in);
    System.out.println("Please enter the morse code that you want to translate to english: ");
    String morse=scan.nextLine().toUpperCase();
    int i=0;
    while(i<morse.length()){
        System.out.print();
        i++;
    }

    }

A: After you've read the input, split the input string by space. For each element, look up the morse code (key) to character (value) map and print the value.
    for (String singleCode : morse.split(" ")) {
        System.out.print(reversedHashMap.get(singleCode));
    }

Sample input output
Welcome to the translator. Type 1 for English to Morse or type 2 for Morse to English:
2
Please enter the morse code that you want to translate to english:
... -- ...
SMS

A: You can simply get morse code one by one, get one morse code in each line, process it and concat it to result string, and if you want get several morse code in one line, use a seperator between them and then split string based on that spliter for examplea #.
so you will get --#.--#..--
then split it by:
for (String singleMorse : morse.split("#")) {
        System.out.print(reversedHashMap.get(singleCode));
    }

Caution: Becouse you have SPACE in you morse code its simpler that use an splitter other than SPACE


text:
Q: jQuery ajaxError() handler fires if user leaves page before page finishes loading We use jQuery's global ajaxError() handler to alert the user of any AJAX failures:
$(document).ajaxError(function() {
    $("There was a network or server error. Please try again later.").dialog({
        title: "Error",
        modal: true,
        resizable: false,
        buttons: { 'Ok': function() { (this).dialog("close"); } }
    });
});

Unfortunately, this global error handler also fires if the user leaves the page before it finishes loading. Here are the steps to reproduce the error:

*

*User visits Page A, which includes elements that load via AJAX.

*AJAX elements on Page A begin loading.

*User clicks link to visit Page B before AJAX elements on Page A have finished loading.

*The error dialog box appears briefly before the browser redirects to Page B.

Any idea how we can get ajaxError() not to trigger when the error is directly caused by the user visiting a new page?
UPDATE: Here's my code now, after incorporating the suggestions in the comments:
// I added a 3 second delay to our error dialog, enough time
// for the user to leave for a new page:
$(document).ajaxError(function() {
    setTimeout(my_error_handler, 3000);
});

// Warn user before leaving page if AJAX is still loading.
// Not sure I'll keep this:
$(document).ajaxStart(function() {
    ajaxing = true;
});

$(document).ajaxStop(function() {
    ajaxing = false;
});

window.onbeforeunload = function() {
    if (typeof(ajaxing) != 'undefined' && ajaxing) {
        return "Page elements are still loading!";
    }
};

A: Well yes, if the user navigates to another page, the xhr will abort, which is, in effect, an unsuccessful communication. A solution would be to register a listener for the onbeforeunload event, and unbind ajaxError there, basically saying: the user is about to leave the page, so i do not wish to be informed of the ajax errors that might follow.
Some sites, though, like GMail, do the other way around: if you try to navigate away from the page while there are still some ajax requests pending, it gives you an prompt that says you've got some processes still running, and lets the user decide whether to stay on the site until the request has finished, or to go ahead and navigate away.

A: Based on David Hedlund's response above here's the code that works for me:
//enable global ajax error handling
$(document).ajaxError(function (event, request, settings) {
    //your error handling code here
});

//user leaving page so ignore any unfinished ajax loads
$(window).bind('beforeunload', function () {
    $(document).unbind('ajaxError');
});

I got the 'ajaxError' spec from the comments section of jquery ajaxError documentation.  I had to bind beforeunload to $(window) in order to support chrome (IE was working fine with document).  .ajaxError didn't fire when I was binding to $(window) so this is why I have this window/document solution.


text:
Q: Access the $form_state and get data from it I am working on a Drupal troubleshooting session while I went through the code I found the following code:
$rpms = $form_state->get(['storage', 'rpms']);

Then I found
$rpm_selected = $form_state->getValue('rpms');

And I do not have experience with Drupal, so is there a difference between the 2, or the 2 are similar, and this is a clerical error or a verbose code

A: To get the form values, you must use:
$rpm_selected = $form_state->getValue('rpms');

Storage is usefull to save custom variables to recover in the future, example:
// set data
$form_state->setStorage(['my_custom_var' => 'test']);

// get data.
$vals = $form_state->getStorage();


text:
Q: Opt in checkbox is not visible for tv app I created a TV app and uploaded to play store with following code in manifest, still the opt-in checkbox is not visible in pricing tab.
<application
        android:allowBackup="true"
        android:banner="@drawable/logo"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Leanback">
        <activity
            android:name="com.tv.activities.SplashScreenActivity"
            android:banner="@drawable/logo"
            android:icon="@drawable/logo"
            android:label="@string/title_activity_splash"
            android:logo="@drawable/logo"
            android:screenOrientation="landscape"
            android:theme="@style/Theme.Leanback">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <categoryandroid:name="android.intent.category.LEANBACK_LAUNCHER" /> </intent-filter>
        </activity>

A: Based from this documentation, if the opt-in checkbox is not enabled, check your APK to make sure it meets the initial criteria.

*

*Applications must include a list of categories for the CATEGORY_LEANBACK_LAUNCHER of ACTION_MAIN the Intent type. For more information, click here.

*Your application must state that it does not require a touch screen. List must android:required="false"declare android.hardware.touchscreenhardware. For more information, click here.


text:
Q: Help with Proof of Borel-Lebesgue theorem The theorem, as seen in Analysis 1 textbook by Vladimir A. Zorich:
Every family of open intervals, that covers a closed interval, contains a finite subfamily, that covers the closed interval.
Proof. Let $S=\{U\}$ be a family of open intervals $U$ which cover the closed interval $[a,b]=I_1$. If $I_1$ cannot be covered by a finite set of intervals of the family $S$, then we divide $I_1$ in two halves. At least one of the halves, we denote with $I_2$, allows no finite coverage. We repeat this process with the interval $I_2$ and so on.
In doing so, we create a nested sequence $I_1\supset I_2 \supset \dots \supset I_n \supset \dots$ of closed intervals, amongst which none allow a coverage of a finite subfamily of S. Since the length of $I_n$ is equal to $|I_n|=|I_1|\cdot 2^{-n}$, the sequence $\{I_n\}$ contains intervals of arbitrarily small length. According to the Nested Interval Property, there exists a point $c$, which is in all of these intervals $I_n, n\in \mathbb{N}$. Since $c \in I_1 = [a,b]$, there exists an open interval $ (\alpha, \beta)=U \in S$, that contains $c$, i.e., $\alpha < c < \beta$. Let $\epsilon=min\{c-\alpha, \beta - c\}$. In the previously created sequence of intervals, we can find an interval $I_n$, such that $|I_n|< \epsilon$. Since $c \in I_n$ and $|I_n|<\epsilon$, it follows that $I_n \subset U=(\alpha, \beta)$. This is in contradiction with the fact that the interval $I_n$ cannot be covered with a finite set of intervals of the family. And therefore the initial statement is true.
End of proof.

Two things I fail to grasp:

*

*Why is the choice of $\epsilon=min\{c-\alpha, \beta - c\}$ a good one, and how are you supposed to come up with it yourself? Or what piece of information we had before the choice of $\epsilon$, is supposed to indicate what the choice should be?

*Why is from $c\in I_n$ and $|I_n|<\epsilon $ following that $I_n\subset U=(\alpha, \beta)$ ?

I translated the text from german, I hope there are no discrepancies between the terms.

A: $c-\alpha$ is the distance between $c$ and the lower end of the interval $(\alpha,\beta)$. Similarly, $\beta-c$ is the distance from $c$ to the upper end of the interval. Normally we would write $\vert \alpha-c\vert$ and $\vert \beta-c\vert$, but since we know that $\alpha<c<\beta$, we can leave out the absolute values and just choose the correct order for the subtraction: $c-\alpha$ because $\alpha<c$, and $\beta-c$ because $c<\beta$. And then the minimum $\epsilon$ of the two is just the minimum distance of $c$ to the interval boundaries. Meaning that anything that's closer than $\epsilon$ to $c$ is both larger than $\alpha$ and smaller than $\beta$, so everything that's within the distance $\epsilon$ of $c$ is also inside the interval $(\alpha,\beta)$. And that's the case for $I_n$: since it contains $c$ and has length smaller than $\epsilon$, all points in $I_n$ are closer than $\epsilon$ to $c$, and are thus contained in $(\alpha,\beta)$. And then so is $I_n$.


text:
Q: Why does a CoreRT-compiled program fail to work with ZIP files? I wrote the following simple program to test:
using System;
using System.IO;
using System.IO.Compression;

namespace HelloZip
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = Path.Combine(AppContext.BaseDirectory, "test.zip");

            using (ZipArchive z = ZipFile.Open(path, ZipArchiveMode.Create))
            {
                var f = z.CreateEntry("hello.txt");
                using (StreamWriter writer = new StreamWriter(f.Open()))
                {
                    writer.Write("Hello World!");
                }
            }
        }
    }
}

Per this page, I ran dotnet new nuget from the HelloZip project directory, added the recommended package sources in nuget.config, then ran the following commands:
dotnet add package Microsoft.DotNet.ILCompiler -v 1.0.0-alpha-*
dotnet publish -r win-x64 -c release -o out
out\HelloZip.exe

I got the following error:
Unhandled Exception: System.IO.Compression.ZLibException: The underlying compression routine could not be loaded correctly. ---> System.DllNotFoundException: Unable to load DLL 'clrcompression.dll': The specified module could not be found.
   at HelloZip!<BaseAddress>+0x1199e7
   at HelloZip!<BaseAddress>+0x119904
   at Interop.zlib.DeflateInit2_(ZLibNative.ZStream&, ZLibNative.CompressionLevel, ZLibNative.CompressionMethod, Int32, Int32, ZLibNative.CompressionStrategy) + 0x48
   at System.IO.Compression.ZLibNative.ZLibStreamHandle.DeflateInit2_(ZLibNative.CompressionLevel, Int32, Int32, ZLibNative.CompressionStrategy) + 0x4f
   at System.IO.Compression.Deflater.DeflateInit(ZLibNative.CompressionLevel, Int32, Int32, ZLibNative.CompressionStrategy) + 0x59

   --- End of inner exception stack trace ---
   at System.IO.Compression.Deflater.DeflateInit(ZLibNative.CompressionLevel, Int32, Int32, ZLibNative.CompressionStrategy) + 0x1db
   at System.IO.Compression.Deflater..ctor(CompressionLevel, Int32) + 0x50
   at System.IO.Compression.DeflateStream.InitializeDeflater(Stream, Boolean, Int32, CompressionLevel) + 0x39
   at System.IO.Compression.ZipArchiveEntry.GetDataCompressor(Stream, Boolean, EventHandler) + 0x4b
   at System.IO.Compression.ZipArchiveEntry.OpenInWriteMode() + 0x65
   at HelloZip.Program.Main(String[]) + 0x75
   at HelloZip!<BaseAddress>+0x1716a2

Am I making a mistake, or does the AOT compiler just not properly support System.IO.Compression yet?

A: You're hitting a known unimplemented functionality. The workaround is to copy clrcompression.dll next to the compiled executable manually for now. See details here: https://github.com/dotnet/corert/issues/5496


text:
Q: Calculating the appropriate inset value for legends automatically Is it possible to obtain the appropriate value of inset automatically so that the left corner of legend will always be just outside of the top right corner of plot?
In the plot below I had to try several values for inset manually. It would be nice to not have to do it manually since I have to make multiple plots.
graphics.off()
windows(width = 5, height = 5)
set.seed(42)
par(mar = c(5,5,1,10))
plot(rnorm(50,15,5), rnorm(50,15,3),
                xlim = c(0,30), ylim = c(5,25),
                pch = 19, col = c("red","blue"))

par(xpd = TRUE)
legend("topright", inset = c(-.80, 0),
                pch = 19, col = c("red","blue"),
                legend = c("LEGEND 1","Second Legend"))

A: After the plot call, before adding the legend, use par("usr")* to extract the coordinates of the plotting region.
Then, instead of positioning the legend using a 'keyword' and inset, use x and y with the top-right coordinates of the plotting region obtained from par("usr"). Adjust x with a suitable coefficient.
coord <- par("usr")
legend(x = coord[2] * 1.05, y = coord[4],
       pch = 19, col = c("red", "blue"),
       legend = c("LEGEND 1", "Second Legend"))

And just for fun, a more convoluted alternative.
After plotting, call legend with position topright, but without plotting it to the device (plot = FALSE), and assign it to an object.
Extract the left x and the top y coordinate of the legend box, and its width (see Value section in ?legend), to be used in x and y in legend:
leg <- legend("topright", pch = 19, col = c("red", "blue"),
              legend = c("LEGEND 1", "Second Legend"),
              plot = FALSE)

legend(x = (leg$rect$left + leg$rect$w) * 1.05, y = leg$rect$top,
       pch = 19, col = c("red", "blue"),
       legend = c("LEGEND 1", "Second Legend"))

*From ?par

usr A vector of the form c(x1, x2, y1, y2) giving the extremes of the user coordinates of the plotting region.

The position calculations that are made when inset parameter(s) have been specified, are in fact based on par("usr") (see line 188-199 in the legend code).


text:
Q: How do i use 3/4 username in laravel 6.* or later version? I stored data in user table like "id, name, username, phone_no, employee_no, email, password and many more columns.
I want to log in as Username & Password, email & Password, phone_no & Password, employee_no & Password.
what is the methodology need for this?
currently, I'm using a username & Password as laravel default.

A: Depending on your authentication method, you might need to override the function that looks for the user. But if you're asking for the query, typically you would do something like this:
User::where(function($query) {
   $query->where('username', $accountIdentifier)
   ->orWhere('email', $accountIdentifier)
   ->orWhere('phone_number', $accountIdentifier)
   ->orWhere('employee_number', $accountIdentifier);
});

$accountIdentifier would correspond to the input of the user, which could be any of those parameters. It's also worth noting that I put it inside a sub-query because you might need to check for accounts that are active, or accounts that are verified.


text:
Q: nginx ssl handshke failed: peer closed connection in SSL handshake while SSL handshaking I'm having issue with some client failed to connect to server through HTTPS.
Our setup is like this:
[client (JVM)] --(https)--> [NGINX] --proxy_pass(http)--> [AppServer (jvm)]
I can connect to AppServer from my java client (runtime:jre1.8.0_65), browser and openssl without any issue.
Here is my openssl log with successful connection:
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384

Here is my print out from JAVA with successful connection:
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1493949464 bytes = { xxx, xxx, ... }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
***
main, WRITE: TLSv1.2 Handshake, length = 195
main, READ: TLSv1.2 Handshake, length = 89
*** ServerHello, TLSv1.2
RandomCookie:  GMT: 1493949462 bytes = { XXX, XXX, ... }
Session ID:  {XXX, XXX, ...}
Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Compression Method: 0
Extension renegotiation_info, renegotiated_connection: <empty>
Extension ec_point_formats, formats: [uncompressed, ansiX962_compressed_prime, ansiX962_compressed_char2]
***

However, one of our client failed at handshake and get
java.net.SocketException: Connection reset by peer: socket write error

ClientHello print out are the same but cannot receive ServerHello...
Here is the error print out:
Manual Logon Thread, WRITE: TLSv1.2 Handshake, length = 195
Manual Logon Thread, waiting for close_notify or alert: state 1
Manual Logon Thread, Exception while waiting for close java.net.SocketException: Connection reset
Manual Logon Thread, handling exception: java.net.SocketException: Connection reset
Manual Logon Thread, SEND TLSv1.2 ALERT:  fatal, description = unexpected_message
Manual Logon Thread, WRITE: TLSv1.2 Alert, length = 2
Manual Logon Thread, Exception sending alert: java.net.SocketException: Connection reset by peer: socket write error
Manual Logon Thread, called closeSocket()
Manual Logon Thread, called close()
Manual Logon Thread, called closeInternal(true)
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.waitForClose(Unknown Source)
    at sun.security.ssl.HandshakeOutStream.flush(Unknown Source)
    at sun.security.ssl.Handshaker.kickstart(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.kickstartHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)

I looked into the Nginx server log and find the error message kind of random...
2017/05/05 12:02:06 [info] 21996#21996: *126588 SSL_do_handshake() failed (SSL: error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol) while SSL handshaking, client: client.ip.address, server: 0.0.0.0:443
2017/05/05 12:02:07 [info] 21991#21991: *126591 peer closed connection in SSL handshake while SSL handshaking, client: client.ip.address, server: 0.0.0.0:443
2017/05/05 12:02:08 [info] 21997#21997: *126592 SSL_do_handshake() failed (SSL: error:1408A10B:SSL routines:SSL3_GET_CLIENT_HELLO:wrong version number) while SSL handshaking, client: client.ip.address, server: 0.0.0.0:443
2017/05/05 12:02:08 [info] 21998#21998: *126593 peer closed connection in SSL handshake while SSL handshaking, client: client.ip.address, server: 0.0.0.0:443
... many peer closed connection print out ...
2017/05/05 12:02:13 [info] 21995#21995: *126603 SSL_do_handshake() failed (SSL: error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher) while SSL handshaking, client: client.ip.address, server: 0.0.0.0:443

Anybody has suggestion on these error?

A: It turns out the client side has some program will scan and block HTTPS request if not permitted, however, don't scan the http connection...
After asking them to permit our host, the issue has been resolved.


text:
Q: curl -XPUT -H "content-type: application/json" -d '{"path":"/models/testALS.zip"}' http://localhost:65327/model has error when calling
curl -XPUT -H "content-type: application/json" -d
'{"path":"/models/testALS.zip"}' http://localhost:65327/model

get error.
I use spark-mllib trained an als model and save the model as testALS.zip
when calling this
curl -XPUT -H "content-type: application/json" -d
'{"path":"/models/testALS.zip"}' http://localhost:65327/model

has error;
the error message is pasted below.

[ERROR] [05/10/2019 04:10:57.815] [MleapServing-akka.actor.default-dispatcher-3] [MleapResource] error with request java.util.NoSuchElementException: key not found: als at scala.collection.MapLike$class.default(MapLike.scala:228) at scala.collection.AbstractMap.default(Map.scala:59) at scala.collection.MapLike$class.apply(MapLike.scala:141) at scala.collection.AbstractMap.apply(Map.scala:59) at ml.combust.bundle.BundleRegistry.model(BundleRegistry.scala:93) at ml.combust.bundle.serializer.ModelSerializer$$anonfun$readWithModel$2.apply(ModelSerializer.scala:105)

A: I believe the endpoint you are using is for updating an existing, loaded model. I'm not sure which version of MLeap you are using, so here is how I would load a model:

*

*I recommend using at least version 0.13.1.

*I recommend using the spring boot server, which is on port 8080

*Then, you need to load a model using POST:

curl -X POST http://localhost:8080/models \
  -H 'Content-Type: application/json' \
  -d '{"modelName":"airbnb", "uri":"file:/models/airbnb.model.lr.zip", "config": {"memoryTimeout": 10000, "diskTimeout": 10000}, "force": false}'


text:
Q: Inserting variable values in GraphQL query I have a basic graphql query as a string which executes as expected before I try to modify it and add input variables (the query is long so I will only include the beginning of the query which is where the variable needs to be inserted)
query {
  vessels {
    pageInfo {
      hasNextPage
      endCursor
    }
    nodes {
...

This works and returns the expected response:
try:
    response = client.execute(gql(query))
except BaseException as e:
    logger.error(e)
    raise

The schema allows for specific vessels to be queried, so I followed the example in the gql documentation here to input a list of variables
query {
  vessels (mmsi: $code ) {
    pageInfo {
      hasNextPage
      endCursor
    }
    nodes {
...

However, this does not work and raises an error:
params = {"code": [775903449, 775982824]}

try:
    response = client.execute(gql(query), variable_values=params)
except BaseException as e:
    logger.error(e)
    raise

graphql.error.base.GraphQLError: Variable "$code" is not defined.

What am I doing wrong here with the variable insertion/replacment into the query string? Any help would be appreciated!

A: Can answer my own question - one needs to define the variable in the first part of the query!
query ($code: [MMSI!]) {
  vessels (mmsi: $code ){
    pageInfo {
      hasNextPage
      endCursor
    }
    nodes {


text:
Q: How do you use the Bootstrap Grid? I used the bootstrap grid and it doesn't seem to be styling the html code using css. I put down the code below and this is my result. column column cloumn

<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">

        Column

        Column

        Column

Here's a version with remote CDNs:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">

        Column

        Column

        Column


text:
Q: media query for vertical scroll Is there a way to detect vertical scroll distance with a media query?
It seems that media queries are designed around detecting the medium (shocking right :P) so things like browser height are testable, but not specifically how far down the page is scrolled.
If is not possible, but you know a way in JS (not jQuery) feel free to post!

A: First off, the accepted answer doesn't work.
The correct name is
window.onscroll

and not
window.onScroll

https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll
Second, this is horribly inefficient as the function is called way more than it needs to and can make the page laggy when scrolled. From John Resig:
http://ejohn.org/blog/learning-from-twitter/
Much better to use a timer that runs every 150 ms or so - something like:
var scrolled = false;

window.onscroll = function() {
  scrolled = true;
}

setInterval(function(){
  if (scrolled) {
    scrolled = false;
    // scrollFunction()
  }
}, 150);

A: I don't believe it's possible with a CSS media query, but I do know that the scroll height can be found in JavaScript using window.pageYOffset. If you wanted to run this value through a function every time the users scrolled up or down on a page, you could do something like
window.onscroll = function() {
    scrollFunctionHere(window.pageYOffset);
};

Or just:
window.onscroll = scrollFunctionHere;

If the function itself checked the value of window.pageYOffset.
For more advice on how to do use window.onscroll efficiently in JavaScript, refer to mynameistechno's answer.
Important note on efficiency: running a function every single time a scroll event is emitted can tear through CPU cycles if anything non-trivial is performed in the callback. Instead, it is good practice to only allow a callback to run so many times per second. This has been termed "debouncing".
Simple debounced scroll event handler code below. Notice how the text toggles between "HELLO" and "WORLD" every 250ms, rather than every single frame:

var outputTo = document.querySelector(".output");
var timeout_debounce;

window.addEventListener("scroll", debounce);

function debounce(event) {
    if(timeout_debounce) {
        return;
    }

    timeout_debounce = setTimeout(clearDebounce, 250);
// Pass the event to the actual callback.
    actualCallback(event);
}

function clearDebounce() {
    timeout_debounce = null;
}

function actualCallback(event) {
// Perform your logic here with no CPU hogging.
  outputTo.innerText = outputTo.innerText === "HELLO"
    ? "WORLD"
    : "HELLO";
}
p {
  padding: 40vh;
  margin: 20vh;
  background: blue;
  color: white;
}

Test!

A: In Jquery you have the method .scrollTop()
http://api.jquery.com/scrolltop/
This example make a div scroll with the window scroll.
$(window).scroll(function(){
        $("div").css("margin-top", $(window).scrollTop())
});

A: Here is one way to solution.f https://jsfiddle.net/oravckzx/1/

$(window).scroll(function(){
    $('.post-sidebar').each(function(){
var ScrollTopVar = $(window).scrollTop();

    var OffsetTopVar = $(this).offset().top;
        var OuterHeightVar = $(this).outerHeight();
         var PositionVar = OffsetTopVar-(OuterHeightVar*1.1);
        if (ScrollTopVar >= PositionVar) {
            $('.hide') .css('background','green').css('font-size','12px')
            $('.post-sidebar') .css('background','orange').css('font-size','12px')
            $('.hide') .css('background','green').css('font-size','12px')
            $('.post-sidebar') .css('background','gray').css('font-size','12px')
            document.getElementById("demo3").innerHTML = ScrollTopVar;
            document.getElementById("demo2").innerHTML = PositionVar;

        }else {
        $('.hide') .css('background','yellow').css('background','yellow')
        $('.hide') .css('background','yellow')
        $('.hide') .css('background','yellow')
        document.getElementById("demo").innerHTML = ScrollTopVar;
        document.getElementById("demo12").innerHTML = ScrollTopVar;
        document.getElementById("demo13").innerHTML = ScrollTopVar;
        document.getElementById("demo14").innerHTML = ScrollTopVar;
        document.getElementById("demo2").innerHTML = PositionVar;
        }
    });
});
.red {height:100px;
background:red;margin-bottom:20px;}

.hide {height:50px;background:blue;margin-bottom:20px;}

.post-sidebar {
height:50px;
background:yellow;
margin-bottom:20px;
box-sizing: border-box;
display: block;
font: normal 700 34px Lato, sans-serif;
padding-right: 20px;
width: 452px;
}
.p {
  font: normal 700 14px Lato, sans-serif;
}

ok

ok

lizard

If reaches to chosen class in html, saves value of ScrollTopVar (as distance from top) to separate variable as eventually PositionVar (which is the distance from top to the chosen class in html, - and that specific distance depends of device which is doing it), and then does certain action if ScrollTopVar value matches or exceeds PositionVar value. Else sets it back if needed, if not including Else it remains as it once met the value.

ok


text:
Q: changing row values into multi index Considering this sample data:
          mem   Admits  AdmPerK
Month
JAN        1       2    3
FEB        4       5    6

I am attempting, I think, to introduce a multi index and create this result:
          JAN                       FEB
<index>   mem   Admits  AdmPerK     mem Admits  AdmPerK

    0     1      2       3          4     5      6

Tried the following;
df.columns = pd.MultiIndex.from_tuples(df.columns)
df.T

Neither worked nor did a couple of other transformation attempts.  Thanks for taking the time to look at this.

A: You can do the job by chaining stack, to_frame and T (for transpose). To give a specific name to the final index, use the parameter name in to_frame. With an example
#input data
df = pd.DataFrame({'Month': ['JAN', 'FEB'], 'mem': [1, 4],
                   'Admits': [2, 5], 'AdmPerK': [3, 6]})
df = df.set_index('Month')
print(df)
#        mem  Admits  AdmPerK
# Month
# JAN      1       2        3
# FEB      4       5        6

#reshape
res = df.stack().to_frame(name='whatyouwant').T
print(res)
Month       JAN                FEB
            mem Admits AdmPerK mem Admits AdmPerK
whatyouwant   1      2       3   4      5       6