text:
Q: is there a wait parameter in PowerShell to allow the script to wait until a command is completed I trying to install a software using Start-Process in PowerShell, I would like for the script to wait until a command is completed before proceeding to the next one. I'm not experienced I tired the script below but it did not work.
Start-Process -Wait -FilePath "C:\Temp\Latitude_5X10_Precision_3550_1.15.0.exe" -ArgumentList "/S" -PassThru

A: Your Start-Process call is correct, but -Wait invariably only tracks the lifetime of the directly launched process (C:\Temp\Latitude_5X10_Precision_3550_1.15.0.exe in your case).
That is, you're out of luck if the target process itself spawns yet another process in order to perform its task and then returns before that child process has terminated.
Additional work is then needed, if even feasible:

*

*If you know the name of the child process, you can try to find and track it via Get-Process.

*Alternatively, if you know of an indirect sign that the task has completed, such as the existence of a directory or a registry entry, look for that.

As an aside: console(-subsystem) applications can be invoked directly for synchronous (blocking) execution (e.g., foo.exe bar baz or & $fooExePath bar baz), which is the preferred method, because it connects the application's output streams to PowerShell's streams.


text:
Q: SQL Server: find top 5 elements in a table and all their occurrence in another I have a SQL Server 2008 R2 database with two tables: hystreal and alarm.
In alarm, I have a dictonaries of alarms and an occurrence which increases under some conditions. Since there are some threads that time to time register these alarms, in hystreal I register an alarm and the timestamp in which the thread registers it.
Thus, the hystreal looks like this:
dataregvalue                                        timestamp
--------------------------------------------------------------------------
ST8 err. cons.                                      1506352039
ST8 err. cons.                                      1506352049
ST8 err. cons.                                      1506352060
ST8 err. cons.                                      1506352070
ST8 err. cons.                                      1506352081
ST8 err. cons.                                      1506352091
ST8 err. cons.                                      1506352102
ST8 err. cons.                                      1506352112
ST8 err. cons.                                      1506352123
ST8 err. cons.                                      1506352133
ST8 err. cons.                                      1506352144
ST8 err. cons.                                      1506352154
ST8 err. cons.                                      1506352165
ST7 timeout                                         1506352448
ST7 timeout                                         1506352458
ST7 timeout                                         1506352469
ST7 timeout                                         1506352479
ST7 timeout                                         1506352490
ST7 timeout                                         1506352500
ST7 timeout                                         1506352511
ST7 timeout                                         1506352532
ST7 timeout                                         1506352543
ST7 timeout                                         1506352553
ST7 timeout                                         1506352564
ST7 timeout                                         1506352585
ST7 timeout                                         1506352595
ST7 timeout                                         1506353273
ST7 timeout                                         1506353283
ST7 timeout                                         1506353293
mac. stop                                           1506353367
mac. stop                                           1506353399
mac. stop                                           1506353420
mac. stop                                           1506353441
ST3 timeout                                         1506353714
ST3 timeout                                         1506353724
ST3 timeout                                         1506353735
ST3 timeout                                         1506353788
ST13 timeout                                        1506353809
ST13 timeout                                        1506353819
ST23 err. Z42                                       1506353893
ST23 err. Z42                                       1506353904
ST23 err. Z42                                       1506353914
ST23 err. Z42                                       1506353925
ST23 err. Z42                                       1506353935
ST23 err. Z42                                       1506353945
ST23 err. Z42                                       1506353956
ST23 err. Z42                                       1506353966
ST23 err. Z42                                       1506353977
ST23 err. Z42                                       1506353988
ST23 err. Z42                                       1506353998
ST23 err. Z42                                       1506354009
ST23 err. Z42                                       1506354019
ST23 err. Z42                                       1506354030
ST23 err. Z42                                       1506354041
ST7 timeout                                         1506354157
ST7 timeout                                         1506354167
ST7 timeout                                         1506354178
ST7 timeout                                         1506354188
ST7 timeout                                         1506354757
ST7 timeout                                         1506354767
ST7 timeout                                         1506354778
ST7 timeout                                         1506354789

While, the alarm looks like this:
communication                                       occur
------------------------------------------------------------
ST8 err. cons.                                      75
ST7 timeout                                         15
mac. stop                                           43
ST3 timeout                                         7
ST13 timeout                                        33
ST23 err. Z42                                       1

I would like to find the top 5 communication (top 5 based on the value of occur) in alarms with all their relative timestamp in hystreal. How can be done that? Thanks in advance!
N.B.: The number of timestamp IS NOT related to the value of occur. There can be many more timestamp.

A: It can be as simple as this :
Select * from hystreal
where dataregvalue in
(
Select top 5 communication
from alarm
order by occur
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dialog Box of jquery ui How can i use the dialog box to show some php content.
I am using jquery ui dialog box, I have a html table, in which i m getting values from database using a while loop: The loop code is:
    <?php
     $i=0;
    while ($i < $num) {

    $f1=mysql_result($result,$i,"FullName");
    $Name = $f1;
    $f2=mysql_result($result,$i,"EmailAddr");
    $string=mysql_result($result,$i,"Message");
    $limit=10;
    $string1 = myTruncate($string,$limit);

    ?>

    <?php echo $f1; ?>
    <?php echo $f2; ?>
    <?php echo $string1; ?>
    <div id="dialog" title="<?php echo $f1; ?>">
    View Complete

    <?php
      $i++;
     }
    ?>

The showStringOutput Function is

I want the dialog box to show The FullName of user, in title, and the complete message when click on View Complete in the dialogbox body. Please help anybody

A: onclick="string" won't do anything.  I'm not familiar with LightBox but the code below should at least hookup to the event and alert the text.
Try this:
 $(function) () {
       $( "#dialog-modal" ).dialog({
      height: 140,
      modal: true
       });
    });

    function showStringOutput() {
       var stringToOutput = <?php echo $string ?> + '';
       $('#stringText').text(stringToOutput);
    }

onclick="showStringOutput()"


text:
Q: How to show Grid with detail form in Master detail form in acumatica? I have master child relationship form.
In child form, I have a Grid, I want my own "Insert" functionality so i just disabled "AddNew" Grid action button and Add new Custom button,
Now what i  want

*

*In custom Add button, I am calling child.Insert() method to add row,

*Now i can see added row in Grid,

*I want to update added row using Detail form, not using Grid row so i added a Formview, below of Grid

*In formview i  want to show inserted row detail, it is showing the current added row.

*On selection of Grid row, I want to show detail in detail Grid

If user edit the detail then i wanted to show all edit detail in the Grid,
so similarly user can add/edit multiple rows using detail form, How may i achieve this?
After adding a row, If i want to add another row then on click add button getting unsaved data error, How may i achieve above functionality?

 <px:PXFormView ID="rootCauseanaDataTab" runat="server" Width="100%" DataMember="MyData"
                        DataSourceID="ds" SkinID="Transparent">
                        <Template>
                            <px:PXLayoutRule runat="server" StartRow="true" StartColumn="True" LabelsWidth="SM" ControlSize="XM"></px:PXLayoutRule>
                            <px:PXButton ID="pxAddNew" runat="server" CommandName="AddNewData" CommandSourceID="ds" Text="Add Rootcause"></px:PXButton>
                            <px:PXLayoutRule runat="server" StartRow="true" StartColumn="True" LabelsWidth="SM" ControlSize="XM"></px:PXLayoutRule>
                            <px:PXSelector ID="edRootId" runat="server" AlreadyLocalized="False" DataField="CauseId" AutoRefresh="true">
                            </px:PXSelector>
                            <px:PXRichTextEdit ID="edRootCauseDesc" runat="server" AlreadyLocalized="False" DataField="Description">
                            </px:PXRichTextEdit>

                        </Template>
                    </px:PXFormView>
                    <px:PXGrid ID="PXGridNCTranRootCauseanaData" RepaintColumns="true" runat="server" Caption="Root Cause anaData" DataSourceID="ds" Height="150px" Width="100%" SkinID="Details" SyncPosition="true">
                        <ActionBar>
                            <Actions>
                                <AddNew Enabled="false" />
                            </Actions>
                        </ActionBar>
                        <Levels>
                            <px:PXGridLevel DataKeyNames="CauseId" DataMember="MyData">
                                <RowTemplate>
                                    <px:PXLayoutRule runat="server" ControlSize="XM" LabelsWidth="M" StartColumn="True" />
                                    <px:PXSelector ID="gdRootcauseId" runat="server" AllowEdit="true" AlreadyLocalized="False" DataField="RootCauseId" AutoRefresh="true">
                                    </px:PXSelector>
                                    <px:PXSelector ID="gdanaDataPerformedBy" AllowEdit="true" runat="server" AlreadyLocalized="False" DataField="anaDataPerformedBy" AutoRefresh="true">
                                    </px:PXSelector>
                                </RowTemplate>
                                <Columns>
                                    <px:PXGridColumn DataField="CauseId" TextAlign="Left" Width="135px" />
                                    <px:PXGridColumn DataField="Description" Width="80px" />

                                </Columns>
                            </px:PXGridLevel>
                        </Levels>
                        <AutoCallBack Target="tree" Command="Refresh" ActiveBehavior="True">
                            <Behavior RepaintControlsIDs="rootCauseanaDataTab"></Behavior>
                        </AutoCallBack>
                    </px:PXGrid>

A: Regarding your issue that the form is not being refreshed I noticed that your  Target is set as Tree, can you try changing that to rootCauseanaDataTab as well? And also try adding  BlockPage="True" CommitChanges="True"
Sample Code:
  <AutoCallBack Target="rootCauseanaDataTab" Command="Refresh" ActiveBehavior="True">
        <Behavior RepaintControlsIDs="rootCauseanaDataTab"  BlockPage="True" CommitChanges="True"></Behavior>
    </AutoCallBack>


text:
Q: rlang - create string with curly curly to be evaluated later I am trying to create a string that includes the "curly curly" brackets and the object based by the user.  I will then parse and evaluate this expression inside of ggplot command.
test_func <- function(df, x_var, y_var, color_by){

  color_aes <- ifelse(!missing(color_by),
                      glue::glue("aes(color = {{{color_by}}})"),  "") %>%
     rlang::expr()

  df %>%
    ggplot(aes(x = {{x_var}}, y = {{y_var}})) +
    geom_point(rlang::eval_tidy(rlang::parse_expr(color_aes)))
}

test_func(mtcars, cyl, disp)
test_func(mtcars, cyl, disp, carb)

Two questions:

*

*Is it possible to create a string with the curly curly without evaluating it when the curly curly is first called?

*How can I pass an empty string to rlang::parse_expr() ?

Thank you

A: I woudn't recommend using strings in this case. You should be able to work with aes() objects more easily. For example
test_func <- function(df, x_var, y_var, color_by){

  color_aes <- if(!missing(color_by))
    aes(color = {{color_by}}) else aes()

  df %>%
    ggplot(aes(x = {{x_var}}, y = {{y_var}})) +
    geom_point(color_aes)
}


text:
Q: I can't put a table inside a tcolorbox I'm writing a book and I cannot put a table inside a tcolorbox I previously defined as follows:
\newcommand{\ejemplo}[1]{
\begin{tcolorbox}[colback=turquesaclar2, colframe=turquesaclar, title=EJEMPLO, lefttitle=4cm, breakable, enhanced]
    #1
\end{tcolorbox}}

This is what I wrote inside the tcolorbox after
\ejemplo{Se tiene el trinomio $x^2-3x-10$.

Sabemos que tanto p como m son negativos, por lo que uno de los números a y b debe ser negativo, y que el negativo debe tener un valor absoluto mayor que el del positivo, pues la suma de a y b es negativa.

Para encontrar todas las posibles soluciones descomponemos -10 y sumamos ambos factores hasta encontrar aquellos factores cuyos resultados coincidan con lo que buscamos (que su suma sea -3 y su producto sea -10):

\begin{table}[h]
\centering
\begin{tabular}{|c|c|}
\hline
$a\cdot b$           & $a+b$        \\ \hline
$(-1)\cdot 10 = -10$ & $-1+10=9$    \\ \hline
$1\cdot (-10) = -10$ & $1+(-10)=-9$ \\ \hline
$(-2)\cdot 5 = -10$  & $-2+5=3$     \\ \hline
$2\cdot (-5)=-10$    & $2+(-5)=3$   \\ \hline
\end{tabular}
\end{table}}

Then it appears like this:

As you can see the table is not there, what can I do? I don't know what to try. Thanks.

A: Package float.sty and the option H, will helps you, as you are not providing proper MWE, I assumed that you are using standard class file, and the MWE is:
\documentclass{book}
\usepackage{xcolor}
\usepackage[skins,many,breakable]{tcolorbox}
\usepackage{float}
\begin{document}

\newcommand{\ejemplo}[1]{
\begin{tcolorbox}[colback=cyan!10, colframe=cyan!20, title=EJEMPLO, lefttitle=4cm, breakable, enhanced]
    #1
\end{tcolorbox}}

\ejemplo{Se tiene el trinomio $x^2-3x-10$.

Sabemos que tanto p como m son negativos, por lo que uno de los números a y b debe ser negativo, y que el negativo debe tener un valor absoluto mayor que el del positivo, pues la suma de a y b es negativa.

Para encontrar todas las posibles soluciones descomponemos -10 y sumamos ambos factores hasta encontrar aquellos factores cuyos resultados coincidan con lo que buscamos (que su suma sea -3 y su producto sea -10):

\begin{table}[H]
\centering
\begin{tabular}{|c|c|}
\hline
$a\cdot b$           & $a+b$        \\ \hline
$(-1)\cdot 10 = -10$ & $-1+10=9$    \\ \hline
$1\cdot (-10) = -10$ & $1+(-10)=-9$ \\ \hline
$(-2)\cdot 5 = -10$  & $-2+5=3$     \\ \hline
$2\cdot (-5)=-10$    & $2+(-5)=3$   \\ \hline
\end{tabular}
\end{table}}

\end{document}

A: If you don't want to put a caption, you don't need a table environment and float, a tabular (which is not a floating environment) is enough.
\documentclass{book}
%\usepackage{xcolor}
%\usepackage[skins,many,breakable]{tcolorbox}
\usepackage[many]{tcolorbox}
%\usepackage{float}
\begin{document}

\newcommand{\ejemplo}[1]{
\begin{tcolorbox}[colback=cyan!10, colframe=cyan!20, title=EJEMPLO, lefttitle=4cm, breakable, enhanced]
    #1
\end{tcolorbox}}

\ejemplo{Se tiene el trinomio $x^2-3x-10$.

Sabemos que tanto p como m son negativos, por lo que uno de los números a y b debe ser negativo, y que el negativo debe tener un valor absoluto mayor que el del positivo, pues la suma de a y b es negativa.

Para encontrar todas las posibles soluciones descomponemos -10 y sumamos ambos factores hasta encontrar aquellos factores cuyos resultados coincidan con lo que buscamos (que su suma sea -3 y su producto sea -10):

{\par\centering
\begin{tabular}{|c|c|}
\hline
$a\cdot b$           & $a+b$        \\ \hline
$(-1)\cdot 10 = -10$ & $-1+10=9$    \\ \hline
$1\cdot (-10) = -10$ & $1+(-10)=-9$ \\ \hline
$(-2)\cdot 5 = -10$  & $-2+5=3$     \\ \hline
$2\cdot (-5)=-10$    & $2+(-5)=3$   \\ \hline
\end{tabular}\par}
}

\end{document}


text:
Q: Java Buttons not working as intended the buttons only seem to multiply and not divide in my program. I do not know what is causing this, but any advice would be highly appreciated.
//View the buttom to be pushed
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MultDivide extends JFrame
{

    private static final int FRAME_WIDTH = 300;
    private static final int FRAME_HEIGHT = 100;
    private double value;
    private JButton multbutton;
    private JButton divbutton;
    private JLabel label;

    public MultDivide()
    {
        super("I Multiply and Divide");

        //get content pane and sets its layout
        Color background = new Color(100,100,0);
        Container contain = getContentPane();
        contain.setLayout(new FlowLayout());
        contain.setBackground(background);

        //create multiple button
        multbutton = new JButton("x5 ");
        contain.add(multbutton);

        //create divide button
        divbutton = new JButton("/5");
        contain.add(divbutton);

        //initialize the value to 50
        value = 50;

        // create a label to display value
        label = new JLabel("Value: " + Double.toString(value));
        contain.add(label);

        //creates listener and executes desired result
        ButtonListener listener = new ButtonListener();
        multbutton.addActionListener(listener);
        divbutton.addActionListener(listener);

        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setVisible(true);

    }
    privateclass ButtonListener implements ActionListener
    {
        //handle button event
        public void actionPerformed(ActionEvent mult)
        {
            //updates counter when the button is pushed
            if(divbutton.isSelected())
            {
                value = value / 5.0;
                label.setText("Value: " + Double.toString(value));
            }
            else
            {

                    value = value* 5.0;
                    label.setText("Value: " + Double.toString(value));

            }

        }

    }
}

A: You're checking isSelected() and that only works with JToggleButtons and its children including JRadioButton and JCheckBox. Instead of this, get the ActionEvent's source and check which button was pushed. Call getSource() on the ActionEvent parameter to do this.
e.g.,
private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent mult) {
        JButton sourceBtn = (JButton) mult.getSource();
        if(sourceBtn == divbutton) {
            value = value / 5.0;
            label.setText("Value: " + Double.toString(value));
        } else {
            value = value* 5.0;
            label.setText("Value: " + Double.toString(value));
        }
    }
}


text:
Q: Using MATLAB to write to Arduino serial monitor to control stepper motor I am currently building a positioner that will move a probe in the x and y direction through the use of three stepper motors and a RAMBo 1.1b board. I have written code through the Arduino IDE that allows me to do so through inputting options in the serial monitor. My goal is to use MATLAB to build a GUI, and write user inputs from MATLAB to the serial monitor. However, I have not figured out how to write to the serial monitor.
Here is my code that I have uploaded to the board (important code is in the loop):
// These define all the pin outs for the Rambo board
#define ELECTRONICS "RAMBo11b"

#define stepPinX1                37//function D37  , port PD7
#define dirPinX1                 48//function D48  , port PL1
#define X_MIN_PIN                12//function PWM12, port PB6
#define X_MAX_PIN                24//function D24  , port PA2
#define enPinX1                  29//function D29  , port PA7
#define X_MS1_PIN                40//function D40  , port PG1
#define X_MS2_PIN                41//function D41  , port PG0

#define stepPinY                 36//function D36  , port PC1
#define dirPinY                  49//function D49  , port PL0
#define Y_MIN_PIN                11//function PWM11, port PB5
#define Y_MAX_PIN                -1
#define enPinY                   28//function D28  , port PA6
#define Y_MS1_PIN                69//function A15  , port PK7
#define Y_MS2_PIN                39//function D39  , port PG2

//These step pin X2 take place of the Z pinout. The Z pin actually goes from the board to the second x axis motor
#define stepPinX2                35//function D35  , port PC2
#define dirPinX2                 47//function D47  , port PL2
#define enPinX2                  27//function D27  , port PA5

#define stepPinE0                34//function D34  , port PC3
#define dirPinE0                 43//function D43  , port PL6
#define enPinE0                  26//function D26  , port PA4
#define E0_MS1_PIN               65//function A11  , port PK3
#define E0_MS2_PIN               66//function D12  , port PK4

#define MOTOR_CURRENT_PWM_XY_PIN 46//function D46  , port PL3
#define MOTOR_CURRENT_PWM_Z_PIN  45//function D45  , port PL4
#define MOTOR_CURRENT_PWM_E_PIN  44//function D44  , port PL5
#define LED_PIN                  13//function PWM13, port PB7

//These are as named. These focus on how fast, far, and long the motors move, respectively.
float speedMove = 40; //mm/s
float speedHome = 70; //mm/s
float steps = .15; //mm/step (distance of one step)
int tMove = (steps / (speedMove*2))*1000000;// microsec
int tHome = (steps / (speedHome*2))*1000000;// microsec

//Below we will be defining the buffer size for the probe that will be navigating around the field attached to the end of the positioner. Also
//will be defining the 0,0 point in the x and y plane.  CENTER PROBE FOR THIS ITERATION OF CODE!
float buf = 10; //mm
float xloc = 0; //mm
float yloc = 0; //mm

//Setup function initializes all the outputs and inputs of the system
void setup() {
  pinMode(stepPinY, OUTPUT);      //function D36  , port PC1
  pinMode(dirPinY, OUTPUT);       //function D49  , port PL0
  pinMode(enPinY, OUTPUT);        //function D28  , port PA6

  pinMode(stepPinX1, OUTPUT);     //function D37  , port PD7
  pinMode(dirPinX1, OUTPUT);      //function D48  , port PL1
  pinMode(enPinX1, OUTPUT);       //function D29  , port PA7

  pinMode(stepPinX2, OUTPUT);     //function D35  , port PC2
  pinMode(dirPinX2, OUTPUT);      //function D47  , port PL2
  pinMode(enPinX2, OUTPUT);       //function D27  , port PA5

  pinMode(stepPinE0, OUTPUT);     //function D34  , port PC3
  pinMode(dirPinE0, OUTPUT);      //function D43  , port PL6
  pinMode(enPinE0, OUTPUT);       //function D26  , port PA4

  //Starts the serial monitor in order to give commands to the motors.
  Serial.begin(38400);

}

////Direction functions
//Sets direction of x-axis motors to negative (left)
void moveNegX(){
  digitalWrite(dirPinX2,HIGH);
  digitalWrite(dirPinX1, LOW);
}
//Sets direction of x-axis motors to positive (right)
void movePosX(){
  digitalWrite(dirPinX2,LOW);
  digitalWrite(dirPinX1, HIGH);
}
//Sets direction of y-axis motor to negative (left)
void moveNegY(){
  digitalWrite(dirPinY, LOW);
}
//Sets direction of y-axis motor to positive (right)
void movePosY(){
  digitalWrite(dirPinY, HIGH);
}

//This function will move in the x direction a specified amount (int X) in mm, in the specified direction (int dir)
float moveX(int X, int dir){
  if (dir == 2){
    movePosX();
  }else{
    moveNegX();
  }
  int numxSteps = X/steps;
  for (int i = 0; i < numxSteps; i++) {
    digitalWrite(stepPinX2,HIGH);
    digitalWrite(stepPinX1, HIGH);
    delayMicroseconds(tMove);
    digitalWrite(stepPinX2,LOW);
    digitalWrite(stepPinX1, LOW);
    delayMicroseconds(tMove);
  }
}

//Same but for y
float moveY(int Y, int dir){
  if (dir == 2){
    movePosY();
  }else{
    moveNegY();
  }
  int numySteps = Y/steps;
  for (int i = 0; i < numySteps; i++) {
    digitalWrite(stepPinY,HIGH);
    delayMicroseconds(tMove);
    digitalWrite(stepPinY, LOW);
    delayMicroseconds(tMove);
  }
}

void loop() {
////TAKE USER INPUT FOR X OR Y////
  while (!Serial.available()){
  }
  int ans = Serial.read();
  if (ans == 1 or ans == 2){//move along x- or y-axis
////TAKE USER INPUT FOR NEGATIVE OR POSITIVE////
    while (!Serial.available()){
    }
    int dir = Serial.parseInt();
////TAKE USER INPUT FOR DISTANCE////
    while (!Serial.available()){
    }
    int dist = Serial.parseInt();
    delay(500);
    if (ans == 1){//move along x-axis
      moveX(dist, dir);
    }else if (ans == 2){//move along y-axis
      moveY(dist, dir);
    }
    delay(1000);
  }
}

And here is my MATLAB code:
s = serialport("COM5",38400);
write(s,2,"uint8")
write(s,2,"uint8")
write(s,10,"uint8")

I tried using Serial.read() instead of Serial.parseint() in Arduino IDE, but it did not work. I also tried different data types for write(), as well as writeline() in MATLAB, again no luck.
Earlier, I used Serial.print() in Arduino IDE to print to the serial monitor and was able to read it in MATLAB using read(), so I know the connections are good. I appreciate any advice!


text:
Q: Run ts-node via cron job I use a script written in TypeScript in order to redetermine item statuses in my app. I usually run this line:
npx ts-node statuscheck.ts

I wanted this to run everyday at midnight, and for that I tried to schedule a cron job as below:
0 0 * * * npx ts-node statuscheck.ts

It doesn't really work, I believe because $PATH is different in cron. Does anyone know the correct way of scheduling this script preferrably with ts-node as in the orinal npx line?

A: You need to specify the path to the folder where your ts file.
0 0 * * * /path/to/the/folder/node_modules/.bin/ts-node statuscheck.ts

A: I finally got it figured out. It seems adding "cd" to the command completely resolved it. This is how my crontab looked like in the end, with no errors and no need to install anything:
PATH=/root/.nvm/versions/node/v12.18.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

0 0 * * * cd /root/app/server/ && npx ts-node ./src/scripts/statuscheck.ts > /root/app/logs/statuscheck.ts.log 2>&1

A: I have updated to:
PATH=/root/.nvm/versions/node/v12.18.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

30 20 * * * npx ts-node /root/app/server/src/scripts/statuscheck.ts > /root/app/logs/statuscheck.ts.log 2>&1

The log now says the following:

 npx: installed 9 in 2.19s Cannot find module 'typescript' Require stack:

/root/.npm/_npx/80229/lib/node_modules/ts-node/dist/index.js
/root/.npm/_npx/80229/lib/node_modules/ts-node/dist/repl.js
/root/.npm/_npx/80229/lib/node_modules/ts-node/dist/bin.js

I kind of didn't get it because Path now equals what I have in terminal...  and I'm not asked this in terminal...  It Just works with no issues...


text:
Q: LaTeX Typesetting Service If this is off topic or not allowed please let me know and I will remove it immediately.
I have two sets of documents that I need typeset into LaTeX and graphics computerized (math drawings, graphs, etc).  I don't need them for about another month or so.  Is there anyone on this forum / does anyone know of a typesetter that could do these documents?
Thanks!


text:
Q: pronunciations: copy
The copy machine is broken. (related audios are linked)

The linked audios have three persons' pronunciation for 'copy.' Which are the materials for TOEIC test that is consisted of three national pronunciations: American, British, and Australian. But I don't acknowledge which is which. Can you write their IPA symbols down and say how they pronounce 'o' each?

A: This is probably not the answer you want, but having taught English in Korea for nearly 6 years and learned a bit about the publishing industry there, I'm going to take a vote that there isn't actually an example of three different English accents represented.
Both recording 1 and 2 can pass for standard North American English. 그리고 재생각에는, it's quite possible that the third one is an Aussie who is trying to use a North American-like accent (since that is what is typically expected when teaching English in Asia).
P.S. I used to grade TOEIC. There aren't any questions about accents on there. You simply need to be able to understand Aussie, British, and American/Canadian accents.


text:
Q: java: data element change affects "unrelated" data structure I have a problem where I retrieve and element from a list (list1), and modify one of the parameters in the element and then add it to another list (list2). When I do this to the final item in list1, it will sometimes modify the parameters of the elements in list2.
This function is called once per generation, but it is not until about the 8th generation when I start to see this happen.  It has affect anywhere from 2 to 16 elements in list2.
Any ideas where my screw up might be? Here's a block of code I wrote to illustrate the problem.  The problem occurs in the section where I check count==0.
    public void sampleCode (List list) {
    List differentList = new ArrayList();
    Individual element;
    Individual differentelement;
    int i = 0;
    int count = 0;
    for(i = 0; i < list.size(); i++) {

        element = (Individual) list.get(i)  ;

        // does some checking to see if this meets criteria
        // this is sorta pseudo code
        if(probability == true) {
            element.setDoMutation(true);
            count++;
        }
        //always add this element to differentList
                    //even if no changes are made to the element
        differentList.add(i,element);
    }
        //need to make sure one elements has mutation=true;
    if(count == 0) {
        differentelement = (Individual) list.get((list.size()-1));

        //setting this element field changes the contents of
        //different list.
        differentelement.setDoMutation(true);
        differentList.set((list.size()-1), differentelement);
    }
}

A: In Java, a variable doesn't hold an object. It holds an object reference (i.e. a pointer to an object). Getting an object fom a list and putting it in another list doesn't make a copy of the object. Both lists simply have a pointer to the same object. So, of course, if you modify the contents of the object, both lists will have the object modified.
Side note: You should use parameterized types (i.e. List<Individual> rather than List), and avoid declaring variables at the beginning of your methods as you would do in C. Only declare a variable when you need it. This will make the code much clearer, and reduce the scope of your variables.

A: Are you sure that the block
    //need to make sure one elements has mutation=true;
    if(count == 0) {
        differentelement = (Individual) list.get((list.size()-1));

        //setting this element field changes the contents of
        //different list.
        differentelement.setDoMutation(true);
        differentList.set((list.size()-1), differentelement);
    }

has to be inside the loop
for(i = 0; i < list.size(); i++) {
    ...
}

I suspect it has to be moved after the loop in order to work correctly.


text:
Q: AutoCompleteBox Strange Popup Position Behavior I'm adding auto complete to a new app using AutoCompleteBox. I noticed some strange behavior of the popup positon. Sometimes (about 70%) it'll popup slightly higher and blocks half of the textbox, while sometimes it just works fine. There're two AutoCompleteBoxes in my app and both of them have this behavior. Have anyone experienced this before?
I'm using the November 2011 toolkit.


text:
Q: One column is wider than the rest using multicolumn I want the  all the 3 columns under метод  Ньютона and метод секущих to have the same width. Right now, the third coulumn is wider than the first and second columns

It is funny because the table was generated from a excel table using https://www.tablesgenerator.com/
\begin{table}[H]
    \centering
    \begin{tabular}{|c|c|c|cccccc|}
    \hline
    \multirow{3}{*}{WQEQWEQQW}        & \multirow{3}{*}{$k$} & \multirow{3}{*}{$m$} & \multicolumn{6}{c|}{число итерации}                                                                                \\ \cline{4-9}
                                      &                      &                      & \multicolumn{3}{c|}{метод Ньютона}                                       & \multicolumn{3}{c|}{метод секущих}                  \\ \cline{4-9}
                                      &                      &                      & \multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{3} & \multicolumn{1}{c|}{1} & \multicolumn{1}{c|}{2} & 3 \\ \hline
    \multirow{5}{*}{$x^3-x^2-kx+m=0$} & 2                    & 1                    & \multicolumn{1}{c|}{5} & \multicolumn{1}{c|}{3} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{2} & 2 \\ \cline{2-9}
                                      & 2                    & 1.2                  & \multicolumn{1}{c|}{5} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{2} & 2 \\ \cline{2-9}
                                      & 3                    & 1.2                  & \multicolumn{1}{c|}{5} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{2} & 2 \\ \cline{2-9}
                                      & 4                    & 1                    & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{5} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{2} & 2 \\ \cline{2-9}
                                      & 4                    & 1.3                  & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{4} & \multicolumn{1}{c|}{5} & \multicolumn{1}{c|}{2} & \multicolumn{1}{c|}{2} & 2 \\ \hline
    \end{tabular}
    \caption{}
    \label{tab:my-table}
    \end{table}

A: As is sadly frequently the case, the code produced by https://www.tablesgenerator.com/ is virtually unmaintainable by hand. I suggest you start by getting rid of all 30 [!] instances of the pointless \multicolumn{1}{c|}{...} "wrappers".
To address your main question: If the width of the 3-column header exceeds the sum of the natural widths of the 3 underlying columns, LaTeX has no choice but to widen at least one of the columns in order to make the header fit. To work around this problem, I suggest calculating the desired column width explicitly, along the lines shown in the code below.
I would also like to suggest that you get rid of all vertical lines and use fewer, but well-spaced, horizontal lines. One way to do so is illustrated in the second table shown in the following screenshot.

\documentclass{article}
\usepackage{fontspec} % requires XeLaTeX or LuaLaTeX
\setmainfont{EB Garamond}[Numbers=Lining] % or some other suitable font
\usepackage{array} % for 'w' column type
\usepackage{calc}
\usepackage{booktabs} % for \toprule, \midrule, \bottomrule, \cmidrule macros
\newlength\mylenA
\newlength\mylenB

\begin{document}

\begin{table}
\centering
\setlength\extrarowheight{2pt} % for a less-cramped "look"

\settowidth\mylenA{метод Ньютона} % choose the wider of the two sub-headers
%% calculate usable width of underlying columns:
\setlength\mylenB{(\mylenA-4\tabcolsep-2\arrayrulewidth)/3}

\begin{tabular}{| c | c | c | *{6}{w{c}{\mylenB}|} }
\hline
 & & & \multicolumn{6}{c|}{число итерации} \\ \cline{4-9}
WQEQWEQQW & $k$ & $m$ &
\multicolumn{3}{c|}{метод Ньютона} &
\multicolumn{3}{c|}{метод секущих} \\ \cline{4-9}
 &   &     & 1 & 2 & 3 & 1 & 2 & 3 \\ \hline
 & 2 & 1   & 5 & 3 & 4 & 2 & 2 & 2 \\ \cline{2-9}
 & 2 & 1.2 & 5 & 4 & 4 & 2 & 2 & 2 \\ \cline{2-9}
 $x^3-x^2-kx+m=0$
 & 3 & 1.2 & 5 & 4 & 4 & 2 & 2 & 2 \\ \cline{2-9}
 & 4 & 1   & 4 & 4 & 5 & 2 & 2 & 2 \\ \cline{2-9}
 & 4 & 1.3 & 4 & 4 & 5 & 2 & 2 & 2 \\
\hline
\end{tabular}
\caption{A table with lots and lots of vertical bars}
\label{tab:my-tableA}

\vspace{1cm}
\setlength\extrarowheight{0pt} % back to default

%% re-calculate usable width of underlying columns:
\setlength\mylenB{(\mylenA-4\tabcolsep)/3}

\begin{tabular}{@{} ccc *{6}{w{c}{\mylenB}} @{}}
\toprule
WQEQWEQQW & $k$ & $m$ & \multicolumn{6}{c@{}}{число итерации} \\
\cmidrule(l){4-9}
 & & &
\multicolumn{3}{c}{метод Ньютона} &
\multicolumn{3}{c@{}}{метод секущих} \\
\cmidrule(lr){4-6} \cmidrule(l){7-9}
 &   &     & 1 & 2 & 3 & 1 & 2 & 3 \\ \midrule
 & 2 & 1   & 5 & 3 & 4 & 2 & 2 & 2 \\
 & 2 & 1.2 & 5 & 4 & 4 & 2 & 2 & 2 \\
 $x^3-x^2-kx+m=0$ &
   3 & 1.2 & 5 & 4 & 4 & 2 & 2 & 2 \\
 & 4 & 1   & 4 & 4 & 5 & 2 & 2 & 2 \\
 & 4 & 1.3 & 4 & 4 & 5 & 2 & 2 & 2 \\
\bottomrule
\end{tabular}
\caption{Same table, but without any vertical bars}
\label{tab:my-tableB}

\end{table}
\end{document}


text:
Q: Epigraph of closed convex hull of a function $\newcommand{\co}{\overline{\operatorname{co}}}\newcommand{\epi}{\operatorname{epi}}$
Let $X$ be an n.v.s and $f: X \to \mathbb{R} \cup \{+\infty\}$ and define $$\co f(x) \doteq \sup_{\substack {x^* \in X^* \\ r \in \mathbb{R} \\ \left \langle x^*, \cdot  \right \rangle - r \leq f}} \left \{ \left \langle x^*,x   \right \rangle  - r  \right \}$$
In other words, $\co f $ is the pointwise supremum of the continuous affine functions everywhere less than $f$.
What I  have to prove is: $\epi(\co f) = \co(\epi f)$
Let me show you what I've done.
\begin{align}
 \epi(\co f) &= \left \{ (x, \lambda) \in X\times \overline{\mathbb{R}} \mid \lambda \geq \co f(x) \right \} \\ &= \left \{ (x, \lambda) \in X\times \overline{\mathbb{R}} \mid \forall \psi \ \text{affine minorant of } f:  \lambda \geq \psi(x)  \right \} \\ &= \left \{ (x, \lambda) \in X\times \overline{\mathbb{R}} \mid \forall \psi \ \text{affine minorant of } f:  (x, \lambda) \in \epi(\psi)  \right \} \\ &= \bigcap\limits_{\substack{\psi \text{ affine minorant of }f}} \epi (\psi)
\end{align}
Since every $\epi(\psi)$ is a closed and convex set that contains $\epi f$, it follows that  $\text{epi}(\co f)$, is closed convex that contains $\epi f$. Furthermore, $\co(\epi f)$ is the intersection of every closed convex set that contains $\text{epi} \ f$, we've got the inclusion $\text{epi}(\co f) \supseteq \co(\epi f)$
For the other inclusion. Assume that there exists $(x_0, \lambda_0) \in \epi (\co f)\setminus \co(\epi f)$. Using Hahn-Banach, we can strictly separate $(x_0, \lambda_0)$ from $\co(\epi f)$, i.e there exists $(x^*,r) \in X^*\times \mathbb{R},(x^*,r) \neq (0,0), \exists c \in \mathbb{R} $ such that $$x^*(x_0) + r\lambda_0 < c < x^*(x) + r \lambda \qquad \forall (x, \lambda) \in  \co(\epi f)$$
It's clear that $r\geq 0$. Otherwise, we can take $\lambda$ large enough and contradicts the inequality. Also, $r \neq 0$, in other case, $x^*$ would be a bounded function which leads to the conclusion $x^* \equiv 0$, but that contradicts the fact that $(x^*, r) \neq (0,0)$. Thus, we have that $r>0$. WLOG, let's take $r=1$, what we have is: $$\exists x^* \in X^*, c_1 \in \mathbb{R} : \quad  x^*(x_0) + \lambda_0 < c_1 < x^*(x) +  \lambda \qquad \forall (x, \lambda) \in  \co(\epi f)$$
Here is where I think there should be a contradiction, but I can not realize what it is. I only have noticed that $(x_0, \co f(x_0)) \notin \co(\epi f)$.
Any ideas?
Regards.
Edit:
Finally, I've got the answer.
Since $\epi f \subseteq \co \left (\epi f\right )$, in the last inequality we can choose $\lambda = f(x)$. Hence, we have $$-x^*(x) +x^*(x_0) + \lambda_0 < -x^*(x) + c_1 < f(x) $$
Therefore, both $-x^*(x) +x^*(x_0) + \lambda_0 $  and $-x^*(x) + c_1$ are affine functions everywhere less than $f$. By definition of $\co f$: $$ \co f(x_0) \geq -x(x_0) + c_1 > -x^*(x_0) + x^*(x_0) + \lambda_0 = \lambda_0$$
On the other hand, $(x_0, \lambda_0) \in \epi \left ( \co f \right ) \Longrightarrow \lambda_0 \geq \co f(x_0)  \ \longrightarrow \longleftarrow$


text:
Q: URLClassLoader problems I have a folder full of classes on which I want to load.

My URLClassLoader seems to load every other class just fine, but sometimes it misbehaves for some reason and it is driving me nuts. All the classes listed in the folder are basically empty (No constructors, fields, methods) and belong to their own package.
package death;
public class Death{

}

package death;
public class Awesome{

}

package abc.dfg.hijk;
public class Test {

}

package mesa;
public class ZZ{

}

I have a mechanism that extracts the package on which a class is part of, as printed out on the console.

This is the code Im using to load each class
    String fileName = file.getName();

    if (fileName.contains(".class")) {

        URL[] urls = new URL[]{ classesFolder.toURI().toURL() };
        URLClassLoader loader = URLClassLoader.newInstance(urls);

        String packageName = getPackage(file);

        //substring -6 because of .class
        Class clazz = loader.loadClass(packageName + fileName.substring(0, fileName.length() - 6));

        loader.close();
    }

    System.out.println("Done loading " + file.getName());
    System.out.println("");

I aint exactly sure whats going on here, though I feel like Im definitely missing something, as all the other classes seem to load just fine. The value of packageName is correct for all the classes that were loaded. Any idea of what Im doing wrong?


text:
Q: Slickgrid example5 collapsing is not working This is my first experience with Slickgrid and I have configured slickgrid treeview example5 in my org. Unfortunately could not make collapsing work. After debugging one thing I noticed is onRowCountChanged event is not called.
Can anyone please help me her. Thanks in advance...
I wired the event on page as --
        $(function () {
          Visualforce.remoting.Manager.invokeAction(
              '{!$RemoteAction.QuoteHandler_c.getQuoteItems}','{!quote.id}',
              function(result, event) {
                  quoteItems = result;
                  prepateData();
                  // initialize the model
            dataView = new Slick.Data.DataView({ inlineFilters: true });
                  dataView.beginUpdate();
                  dataView.setItems(data);
                  dataView.setFilter(myFilter);
                  dataView.endUpdate();
                    // initialize the grid
        grid = new Slick.Grid("#myGrid", dataView, columns, options);

                  grid.onClick.subscribe(function (e, args) {
                    if ($(e.target).hasClass("toggle")) {
                      var item = dataView.getItem(args.row);
                      if (item) {
                        if (!item._collapsed) {
                          item._collapsed = true;
                        } else {
                          item._collapsed = false;
                        }

                        dataView.updateItem(item.id, item);
                      }
                      e.stopImmediatePropagation();
                    }
                  });

                  // wire up model events to drive the grid
                  dataView.onRowCountChanged.subscribe(function (e, args) {
                    grid.updateRowCount();
                    grid.render();
                  });

                  dataView.onRowsChanged.subscribe(function (e, args) {
                    grid.invalidateRows(args.rows);
                    grid.render();
                  });

                  var h_runfilters = null;
                  // wire up the slider to apply the filter to the model
                  $("#pcSlider").slider({
                    "range": "min",
                    "slide": function (event, ui) {
                      Slick.GlobalEditorLock.cancelCurrentEdit();
                      if (percentCompleteThreshold != ui.value) {
                        window.clearTimeout(h_runfilters);
                    h_runfilters = window.setTimeout(dataView.refresh, 10);
                        percentCompleteThreshold = ui.value;
                      }
                    }
                  });
             // wire up the search textbox to apply the filter to the model
                  $("#txtSearch").keyup(function (e) {

                    Slick.GlobalEditorLock.cancelCurrentEdit();
                    // clear on Esc
                    if (e.which == 27) {
                      this.value = "";
                    }
                    searchString = this.value;
                    dataView.refresh();
                  })

              }
          );

        })

A: Thanks for your help...
I figured it out. The error was with myFilter function. Because of which the number of rows always returned same hence onRowsCountChanged not called.


text:
Q: Product symbol c on the lower suffix Sorry, this may be very easy question but I didn't get. When I use product symbol, I want to write c(as a cardinal product) in the lower suffix. I am using following command.
\documentclass{12 pt}{article}

\begin{document}

$\prod_{i = 1}^{n}_{c} A_{i}$

\end{document}

A: I'm not sure want exactkly you like to get but you can inlcude the _c part inside the braces of n:
\prod_{i = 1}^{n_c} A_{i}

which will give

Pleas note that the first argument of \documentclass is optional and for that needy square brackets, and the font size option is without a space, i.e. 12pt instead of 12 pt …

A: Can you be more specific about what you want the "c" to be a suffix of? Would either
${\prod_{i = 1}^{n}}_{c} A_{i}$

or
${\prod_c}^n_{i = 1} A_{i}$

suffice?
Also, your first line of code should be: \documentclass[12 pt]{article}.


text:
Q: How can I compile X11 statically? I'm compiling parallel C code on a cluster (HECToR).
Although I won't be running any parallel jobs interactively, my code contains some references to X11 functions which are used when it's run sequentially. The cluster I'm using doesn't support shared libraries, which rules out X11, at least in the way I've been using it so far.
Could you advise me on whether there's anything I can do to compile X11 statically?
Thanks in advance for your help.
Ross

A: There's nothing magic about X11 here - if you don't have libX11.a and other static libraries on your system, you'll need to either find packages for your OS that provide
those, or build whichever set of X11 libraries you need from source with the --enable-static flag passed to the configure script.
If you do have libX11.a, then see your compiler's documentation for it's flag to link with static libraries.
(Really though, anything in 2010 that doesn't support shared libraries is just plain wrong.  They should enter the 1980's already.)


text:
Q: Force a Java Tooltip to Appear Given a JTextField (or any JComponent for that matter), how would one go about forcing that component's designated tooltip to appear, without any direct input event from the user? In other words, why is there no JComponent.setTooltipVisible(boolean)?

A: The only way (besides creating your own Tooltip window) I've found is to emmulate the CTRL+F1 keystroke on focus:
new FocusAdapter()
{
    @Override
    public void focusGained(FocusEvent e)
    {
        try
        {
            KeyEvent ke = new KeyEvent(e.getComponent(), KeyEvent.KEY_PRESSED,
                    System.currentTimeMillis(), InputEvent.CTRL_MASK,
                    KeyEvent.VK_F1, KeyEvent.CHAR_UNDEFINED);
            e.getComponent().dispatchEvent(ke);
        }
        catch (Throwable e1)
        {e1.printStackTrace();}
    }
}

Unfortunately, the tooltip will disappear as soon as you move your mouse (outside of the component) or after a delay (see ToolTipManager.setDismissDelay).

A: You need to invoke the default Action to show the tooltip. For example to show a tooltip when a component gains focus you can add the following FocusListener to the component:
FocusAdapter focusAdapter = new FocusAdapter()
{
    public void focusGained(FocusEvent e)
    {
        JComponent component = (JComponent)e.getSource();
        Action toolTipAction = component.getActionMap().get("postTip");

        if (toolTipAction != null)
        {
            ActionEvent postTip = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
            toolTipAction.actionPerformed( postTip );
        }

    }
};

Edit:
The above code doesn't seem to work anymore. Another approach is dispatch a MouseEvent to the component:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PostTipSSCCE extends JPanel
{
    public PostTipSSCCE()
    {
        FocusAdapter fa = new FocusAdapter()
        {
            public void focusGained(FocusEvent e)
            {
                JComponent component = (JComponent)e.getSource();

                MouseEvent phantom = new MouseEvent(
                    component,
                    MouseEvent.MOUSE_MOVED,
                    System.currentTimeMillis(),
                    0,
                    10,
                    10,
                    0,
                    false);

                ToolTipManager.sharedInstance().mouseMoved(phantom);
            }
        };

        JButton button = new JButton("Button");
        button.setToolTipText("button tool tip");
        button.addFocusListener( fa );
        add( button );

        JTextField textField = new JTextField(10);
        textField.setToolTipText("text field tool tip");
        textField.addFocusListener( fa );
        add( textField );

        JCheckBox checkBox =  new JCheckBox("CheckBox");
        checkBox.setToolTipText("checkbox tool tip");
        checkBox.addFocusListener( fa );
        add( checkBox );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("PostTipSSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new JScrollPane(new PostTipSSCCE()) );
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

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

This approach will result in a slight delay before the tooltip is displayed as it simulated the mouse entering the component. For immediate display of the tooltip you can use pstanton's solution.

A: For me works the similar version stated above (instead of Timer I used SwingUtilities and invokeLater approach):
private void showTooltip(Component component)
{
    final ToolTipManager ttm = ToolTipManager.sharedInstance();
    final int oldDelay = ttm.getInitialDelay();
    ttm.setInitialDelay(0);
    ttm.mouseMoved(new MouseEvent(component, 0, 0, 0,
            0, 0, // X-Y of the mouse for the tool tip
            0, false));
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            ttm.setInitialDelay(oldDelay);
        }
    });
}

A: You can access the ToolTipManager, set the initial delay to 0 and send it an event. Don't forget to restore the values afterwards.
private void displayToolTip()
{
    final ToolTipManager ttm = ToolTipManager.sharedInstance();
    final MouseEvent event = new MouseEvent(this, 0, 0, 0,
                                            0, 0, // X-Y of the mouse for the tool tip
                                            0, false);
    final int oldDelay = ttm.getInitialDelay();
    final String oldText = textPane.getToolTipText(event);
    textPane.setToolTipText("google!");
    ttm.setInitialDelay(0);
    ttm.setDismissDelay(1000);
    ttm.mouseMoved(event);

    new Timer().schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            ttm.setInitialDelay(oldDelay);
            textPane.setToolTipText(oldText);
        }
    }, ttm.getDismissDelay());
}

A: It's not a ToolTip, but you can use a balloon tip:
http://timmolderez.be/balloontip/doku.php
It is showing just on call and feels better in some moments then Default ToolTip


text:
Q: How to see the unique active devices all time per Flurry API? I would like to get the number of (unique) active devices of all time for my apps via Flurry API. With "unique active device" I mean any device which has started the app (at least once - so counted only once) since time being.
The Definition of Flurry of "Active User" is
An active device is defined as a device that has had at least one session with your app during a given time period (hours, days, weeks, months). If a device launches more than one session during a given period, it will only be counted once..
The biggest time period mentioned here is month and so I understand
When the same device starts a session in month 1 but also in month 2 it will be counted twice. Right? And that wouldn't be the correct number.
So is that requested number anywhere available in Flurry and via API?

A: The App Summary dashboard has the option to set the time period to "All Time". One of the metrics is for Active Devices. The number there is the number of unique users across all time.
It is not available via API. The metrics API has a limit of 90 days.


text:
Q: How to connect a folder placed inside Angular assets in a Firebase Cloud Function? I try to achieve the following with Angular and a Node.js cloud function (Firebase):

*

*Placing an entire folder with many files (2MB) to the Angular /assets/ folder.

*Let the user input some data to change specific text content of some files

*Calling the Cloud function with an HTTP Request and send the user data

*Access this folder inside the cloud function

*Cloning the entire folder to a temporary directory and work on the cloned files with Node.JS by replacing some content strings in some files

*Sending the URL from the new manipulated folder back to the user

In general I have problems to understand how I could I create a connection between the cloud function and the folder I want to work with. Both, the Angular application and also the Cloud Functions, are hosted on Firebase. When I understand how I can connect with the folder, the other points would be no problem.
Is there a way to achieve what I want to?


text:
Q: How to access iCloud Documents files in an asynchronous manner I am trying to add support for iCloud Documents in my existing app, but I am struggling  badly with how to do that.
Apple seems to prefer that you use the UIDocument class for that. But UIDocument does not give direct access to the file in the file system, it expects to maintain a copy of the contents of the file in an NSData object instead. That is simply not doable in my case. All my current code and half of the 3rd party libraries that I use, work directly with the file on the file system, not with NSData. Rewriting all that code is simply not doable.
When not using the UIDocument class, Apple expects you to use the NSFileCoordinator to coordinate access to the file's contents. I am trying to do that with my code, but the methods on the NSFileCoordinator seem to expect that all reading and writing will be done in one synchronous sequence. All the methods of NSFileCoordinator take a block as argument, and expect all the reading/writing to be performed inside that block. When the block returns, you are not allowed to make any file access anymore, as far as I understand.
That is not doable in my case as well. Some of my code, and the 3rd party libraries, do the reading / writing in an asynchronous manner on background threads. I can identify the start and end of the period that the code needs access to the file contents, so if there was a separate requireAccess method, and separate relinquishAccess on the NSFileCoordinator, that would enable me to achieve the goal. But that does not seem to be the case.
It is unclear to me what the role of NSFilePresenter in this is. Some of the documentation, especially that of relinquishPresentedItemToReader() in NSFilePresenter seem to indicate that you can actually acquire / relinquish access separately:

If you want to be notified when the reader has completed its task,
pass your own block to the reader and use that block to reacquire the
file or URL for your own uses.

But it does not explain anywhere how to "reacquire" the file.
So the concrete question: I need to do the following steps in an asynchronous manner:

*

*acquire access to the file, and obtain a file: URL for the file on the local file system

*do multiple, asynchronous,
read/write operations on the file with normal file system
operations on that file: URL

*relinquish access to the file

Does anybody know whether it is possible to do this, and how to do step 1 and step 3 ?


text:
Q: gcc sandboxing tool - AppArmor / CHROOT jail on Ubuntu 12.04 We have a Node application as the front end to a C++ sandboxing tool, which compiles code using gcc and outputs the result to the browser.
e.g.
exec("gcc -o /tmp/test /tmp/test.cpp",
    function (error, stdout, stderr) {
        if(!stderr) {
            execFile('/tmp/test', function(error, stdout, stderr) {});
        }
    }
);

This works fine.
However, as you can imagine this is a security nightmare if it were to be made public - so I was thinking of two options to protect my stack:

*

*A CHROOT jail - but this in itself wouldn't be enough to prevent directory traversal / file access.

*AppArmor ?

So my question is really, how could I protect my stack from any nasties that could come from:
A) Compiling unknown code using gcc
B) Executing the compiled code

A: It entirely depends on how much is at stake and what you are willing to sacrifice for securing it.
The chroot jail is likely to only offer a poor level of protection and would especially leave the potential attacker with access to the network and all computational resources of your host machine as well as the ability of elevating local privilege escalation exploits (which happen to be discovered quite often in all kinds of software packages, even including the Linux Kernel).
A MAC solution (SELinux, AppArmor, TOMOYO) would allow for a finer level of control, especially including network access, but MACs are not all that unbreakable.
Another level of sandboxing would include intercepting all system calls - pretty much what you see with Seccomp. But obviously, creating a useful profile here would be an awful lot of work.
You could go even further and spin off a virtual machine or a container for each instance of your executed code - this is where you are likely to have the highest level of control over resource usage and separation from the host's data - but this is likely to become expensive for anything but a trivial case with just a handful of users.


text:
Q: Windows Phone 8.1 MediaCapture CapturePhotoToStorageFileAsync memory leak I am building a universal app for timelapse that captures a sequence of photos at a specified interval. In my timer tick event, I am capturing an image and saving it to a storage file like this:
StorageFile file = await appFolder.CreateFileAsync(IMAGE_FILE_ROOT, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
await MediaCaptureManager.CapturePhotoToStorageFileAsync(imageProperties, file);
ImageFilePaths.Add(file.Path);
file = null;

After successfully capturing around 30 images at the highest resolution (140 on low res) on my phone, I get an Out of Memory exception on the CapturePhotoToStorageFileAsync method.
I tried just taking the photo to an InMemoryRandomAccessStream so that I could elliminate the StorageFile API for the leak, and it still leaks.
I profiled the memory utilization with the WinPhone Power Tools and it is a constant rise while photos are being taken.
Is there anything I can do to work around this?
Update:
Here is test code that demonstrates the leak:
for (int x = 0; x < 40; x++)
{
    using (IRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
    {
        await MediaCaptureManager.CapturePhotoToStreamAsync(imageProperties, memoryStream);
    }

    await Task.Delay(1000);
}

A: So I figured out how to work around the issue!
Apparently the memory leak has something to do with the audio driver.  If you initialize the MediaCaptureManager like this, the leak disappears.
var mediaSettings = new MediaCaptureInitializationSettings
 {
  PhotoCaptureSource = PhotoCaptureSource.Auto,
  StreamingCaptureMode = StreamingCaptureMode.Video,
  AudioDeviceId = string.Empty
 };


text:
Q: Javascript hiding dropdown menu buttons After Struggling I have installed a multiple layer drop down menu. When all is well I found that all the buttons like present on my website Please Click Here are hiding. I found its the issue with javascript present in my html head. Please solve this issue...
HTML HEAD CODE
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript' src='js/jquery.hoverIntent.minified.js'></script>
<script type='text/javascript' src='js/jquery.dcmegamenu.1.3.3.js'></script>
<script type="text/javascript">
$(document).ready(function($){
    $('#mega-menu-7').dcMegaMenu({
        rowItems: '3',
        speed: 'fast',
        effect: 'slide'
    });
});
</script>

If you want jquery.dcmegamenu.1.3.3.js and jquery.hoverIntent.minified.js files I will sent to you.
Also, there is a splitter on the totally right hand side of my menu about 1mm which goes beyound the page. Can we delete it ????
Thanks for your support.


text:
Q: Golang: "compress/flate" module can't decompress valid deflate compressed HTTP body This question continues the discussion started here. I found out that the HTTP response body can't be unmarshaled into JSON object because of deflate compression of the latter. Now I wonder how can I perform decompression with Golang. I will appreciate anyone who can show the errors in my code.
Input data
I've dumped the HTTP response body into the 'test' file. Here is it:
$ cat test
x��PAN�0�
;��NtJ�FӮdU�|"oVR�C%�f�����Z.�^Hs�dW뮑�'��DH�S�SFVC����r)G,�����<���z}�x_g�+�2��sl�r/�Oy>��J3\�G�9���N���#[5M�^v/�2Ҕ��|�h��[�~7�_崛<D*���/��i

Let's make sure that this file can be decompressed and even contains valid JSON:
$ zlib-flate -uncompress < test
{"timestamp":{"tv_sec":1428488670,"tv_usec":197041},"string_timestamp":"2015-04-08 10:24:30.197041","monitor_status":"enabled","commands":{"REVERSE_LOOKUP":{"cache":{"outside":{"successes":0,"failures":0,"size":0,"time":0},"internal":{"successes":0,"failures":0,"size":0,"time":0}},"disk":{"outside":{"successes":0,"failures":0,"size":0,"time":0},"internal":{"successes":13366,"failures":0,"size":0,"time":501808}},"total":{"storage":{"successes":0,"failures":0},"proxy":{"successes":13366,"failures":0}}},"clients":{}}}
$ zlib-flate -uncompress < test | python -m json.tool
{
    "commands": {
        "REVERSE_LOOKUP": {
            "cache": {
               ....

Source code
package main

import (
    "bytes"
    "compress/flate"
    "fmt"
    "io/ioutil"
)

func main() {
    fname := "./test"
    content, err := ioutil.ReadFile(fname)
    if err != nil {
        panic(err)
    }
    fmt.Println("File content:\n", content)

    enflated, err := ioutil.ReadAll(flate.NewReader(bytes.NewReader(content)))
    if err != nil {
        panic(err)
    }
    fmt.Println("Enflated:\n", enflated)
}

Error
$ go run uncompress.go
File content:
 [120 156 181 80 65 78 195 48 16 252 10 242 57 69 118 226 166 38 247 156 64 42 42 130 107 100 156 165 88 196 118 149 93 35 160 234 223 89 183 61 112 42 226 192 109 118 118 102 103 180 123 65 62 0 146 13 59 209 237 5 189 15 8 78 116 74 215 70 27 211 174 100 85 184 124 34 111 86 82 171 67 37 144 102 31 183 195 15 167 168 165 90 46 164 94 72 115 165 100 87 235 174 145 215 39 189 168 68 72 209 83 154 7 22 83 70 86 67 180 207 19 140 188 114 41 4 27 71 44 225 155 254 169 223 60 244 195 221 122 125 251 120 95 24 103 221 43 20 144 50 161 31 143 16 179 115 128 8 108 225 114 47 214 79 121 62 15 232 191 224 8 74 51 6 92 213 71 130 57 218 233 175 78 182 142 30 223 254 35 91 53 77 219 94 118 47 165 50 210 148 18 148 232 124 128 31 104 183 151 91 176 126 55 167 143 207 95 3 15 229 180 155 60 68 42 159 231 241 27 47 165 167 25]
panic: flate: corrupt input before offset 5

goroutine 1 [running]:
runtime.panic(0x4a7180, 0x5)
    /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
    /home/isaev/side-projects/elliptics-manager/uncompress.go:20 +0x2a3
exit status 2

PS Ubuntu 14.10, Go 1.2.1

A: Your input is not a simple deflated block, it's a zlib stream.
According to the ZLIB Compressed Data Format Specification 3.3 the first 2 bytes are:
-------------
| CMF | FLG |
-------------

The Compression Method and flags. Your input starts with [120, 156] which is 78 9C in hexa. This is the Default Compression. Also no dictionary follows, so the subsequent data is the compressed data.
Bits 0 to 3 are CM Compression Method and bits 4 to 7 are CINFO Compression Info. In this case CINFO=7 indicates a 32K window size, CM=8 denotes the "deflate" compression method. FLG bit 5 tells if a dictionary is preset, which is in this case. Details of the FLG are also in the linked RFC 1950.
So your input basically tells the rest of the data was constructed using default compression, but the go flate package does not decode this.
Change your decompression to omit the first 2 bytes like this and it will work:
enflated, err := ioutil.ReadAll(flate.NewReader(bytes.NewReader(content[2:])))

Try it on the Go Playground. But...
Use Proper ZLib decompression!
We got lucky this time because the compression level is the default and dictionary was preset. If not, you won't be able to decode it using the flate package. Since the input is a zlib stream, you should use the compress/zlib package to properly decode it and not rely on luck:
r, err := zlib.NewReader(bytes.NewReader(content))
if err != nil {
    panic(err)
}
enflated, err := ioutil.ReadAll(r)
if err != nil {
    panic(err)
}
fmt.Println(string(enflated))

Try the zlib variant on the Go Playground.


text:
Q: How to convert the given Before links to the After links using one to two lines of code in java? Before:
           +----+----+    +----+----+
list ----> |  1 |  +----> |  2 |  / |
           +----+----+    +----+----+
           +----+----+    +----+----+
temp ----> |  3 |  +----> |  4 |  / |
           +----+----+    +----+----+
After:
           +----+----+    +----+----+    +----+----+    +----+----+
list ----> |  1 |  +----> |  3 |  +----> |  4 |  +- --> |  2 |  /
           +----+----+    +----+----+    +----+----+    +----+----+

This is what I have so far....
List.next = temp;
Temp.next = list.next.next;

I don't understand the concept of using .next and .next.next.
Any help will be greatly appreciated!

A: In general, the variable (e.g. list) is referring to the first 'node'. So list has a value of 1 and list.next has a value of 2.
When you do list.next = temp; that is correct, however you should first make sure you have a reference to the value of 2, because once you reset the value of list.next to temp, you will lose the reference. You can solve this by creating another variable x and setting it equal to list.next (2).
Then when you call list.next = temp; you will have the following:
           +----+----+
  x  ----> |  2 |  / |
           +----+----+

           +----+----+    +----+----+    +----+----+
list ----> |  1 |  +----> |  3 |  +----> |  4 |  /
           +----+----+    +----+----+    +----+----+

After this, you can use the .next notation to get the reference to the 4 valued node, and set this equal to x (list.next.next.next = x;).
Using .next many times can be a bit clunky, so if it makes more sense to you, you can simply create a new variable and set it to list.next, repeating until you have a reference to the node you desire (e.g. y = list.next; (3), y = y.next; (4)).


text:
Q: back up de base de datos SQL con PHP Necesito realizar un back up de una base de datos, en especifico de una tabla, que es la que guarda todos mis registros. Encontré este código.
<?php
$db_host = 'localhost';
$db_name = 'prueba';
$db_table = 'asesoria';
$db_user = 'root';
$db_pass = '';

$fecha = date("Ymd-His");

$salida_sql = $db_name.'_'.$fecha.'.sql';

$dump = "mysqldump --h$db_host -u$db_user -p$db_pass --opt $db_name > $salida_sql";
system($dump, $output);

$zip = new ZipArchive();
$salida_zip = $db_name.'_'.$fecha.'.zip';

if($zip->open($salida_zip, ZipArchive::CREATE) === True){
    $zip->addFile($salida_sql);
    $zip->close();
    unlink($salida_sql);
    header("location: $salida_zip");
}else{
    echo'error';
}
?>

Y en efecto me crea un archivo.

Pero al importar el archivo no contiene nada.

Para que entren un poco en contexto, el sistema debe cargar en la tabla asesorías, múltiples registros, y el back up es con la finalidad de que cada cierto periodo el administrador pueda borrar únicamente los registros y empezar de cero.

Alguna sugerencia?, alguna forma de solo realizar el back up de la tabla?


text:
Q: akka - get list of ActorRef from ActorSelection ActorSelection support wildcard  and it allows to send a message to all actors that match the selection:
context.actorSelection("../*") ! msg

Is there a way to retrieve the list of ActorRef that match the selection from the ActorSelection?
From the documentation I can see that there is a resolveOne function but not (for example) a resolveList.
Update
The reason why I want the list of ActorRef is that I would like to use the ask operator on all the actors that match the selection.
Just to be clear here is an example of what I would like to do:
object MyActor {
  case object AskAllActors
  case object GetActorInfo
}

class MyActor extends Actor {
  import MyActor._

  def receive = {
    case AskAllActors =>
      val actors: List[ActorRef] = context.actorSelection("../*").resolveList()
      val result: List[Future[String]] = actors.map { a => (a ? GetActorInfo).mapTo[String] }
      Future.sequence(result).map { result =>
        // do something with result: List[String]
      }
  }
}

A: The ability to get a list of the form
val timeout : FiniteDuration = 10 seconds

val actorList = actorSelection.resolveMany(timeout)

does not exist.  I suspect the reason is because once the timeout expires there is a chance that an Iterable, of non-zero length, is returned but it would be impossible to know if the Iterable is comprehensive.  Some Actors may not have had enough time to respond.  With resolveOne the issue does not exist, the first responding ActorRef is the result.
Based on the documentation it looks like you could use the Identify message to have all of the Actors specified in an actorSelection respond with identification:
class Follower extends Actor {
  val identifyId = 1
  context.actorSelection("../*") ! Identify(identifyId)

  def receive = {
    case ActorIdentity(`identifyId`, Some(ref)) => ...
  }
}


text:
Q: how to change colorbar to jet? #fig = plt.figure(facecolor='blue')
plt.figure(figsize = (15,10))
plt.scatter(data[data.predict==3].X, data[data.predict==3].Y, c = data[data.predict==3].proba_final, cmap='jet')
plt.scatter(points['X'], points['Y'], edgecolors='w', facecolors='none', lw=1, cmap='jet')
plt.title('Category 3', size=20)
plt.xlabel('X')
plt.ylabel('Y')
cbar = plt.colorbar()
cbar.ax.set_yticklabels([0,0.2,0.4,0.6,0.8,1.0])
cbar.ax.set_ylim(bottom=0)
plt.rcParams['axes.facecolor']='#03045c'
#plt.fill(150, 150, "b")
ax = plt.gca()
ax.set_xlim([0, 300])
ax.set_ylim([0, 300])
plt.xticks(range(0,350,50))

my output, need to change the cbar1
I need to have a jet colorbar, how to deal with it?


text:
Q: update element of list of Complex object with linq Hi everybody and thanks in advance for solution
I've these objects
    List<AccessModuleInfo> listOfAccessModuleInfo = new List<AccessModuleInfo>();

    public class AccessModuleInfo
    {
       public int AccessModuleId { get; set; }
       public string AccessModuleName { get; set; }
       public List<AccessRoleInfo> ListOfAccessRole { get; set; }

     }

    public class AccessRoleInfo
    {
      public int AccessRoleId { get; set; }
      public string AccessRoleName { get; set; }
      public bool AccessRoleValue { get; set; }
    }

I receive listOfAccessModuleInfo that is already fill and when I try to update AccessRoleValue in specific AccessModuleInfo, all AccessRoleValue with the same AccessRoleId are updated .
I want update only AccessRoleValue of specific AccessModuleInfo (for example with AccessModuleId = 4)
Thanks

A: Normally something like this should work just fine:
// You didn't confuse == vs = did you?
// Single also helps us debug and ensure we're only getting one result
var itemToUpdate = listOfAccessModuleInfo.Where(x => x.AccessModuleId == 4).Single();
itemToUpdate.ListOfAccessRole.ForEach(x => x.AccessRoleValue = newValue);


text:
Q: exert power VS wield power Does exert power over something mean the same as wield power over something?
For example:

*

*For many centuries, this community exerted a lot of power over these
people.

*For many centuries, this community wielded a lot of power over these
people.

Would sentence 1 and 2 mean exactly the same?

A: You can wield power without exerting it.
For instance, a policeman standing on a street corner can reduce crime (or at least relocate it) without actually arresting any criminals. The fact he could arrest people has an effect on their behavior.


text:
Q: What indexes would improve the speed of this query? Select link_id, date_trunc('day', inserted_at),
count(*) from clicks
where
previous_click_id is null
and link_workspace_id = 2
group by
link_id, date_trunc('day', inserted_at)

Output of EXPLAIN ANALYZE:
"GroupAggregate  (cost=153356.84..163584.13 rows=129848 width=24) (actual time=1315.303..1783.331 rows=25234 loops=1)"
"  Group Key: link_id, (date_trunc('day'::text, inserted_at))"
"  ->  Sort  (cost=153356.84..155507.88 rows=860419 width=16) (actual time=1315.280..1645.578 rows=879836 loops=1)"
"        Sort Key: link_id, (date_trunc('day'::text, inserted_at))"
"        Sort Method: external merge  Disk: 22296kB"
"        ->  Seq Scan on clicks  (cost=0.00..53835.41 rows=860419 width=16) (actual time=0.054..741.964 rows=879836 loops=1)"
"              Filter: ((previous_click_id IS NULL) AND (link_workspace_id = 2))"
"              Rows Removed by Filter: 418485"
"Planning time: 0.204 ms"
"Execution time: 1794.119 ms"

A: A regular index scan won't help, since you are retrieving most of the table.
But you should increase work_mem to get a faster in-memory sort.
You could experiment with a covering index:
CREATE INDEX ON clicks (link_workspace_id)
   INCLUDE (link_id, inserted_at)
   WHERE previous_click_id IS NULL;

VACUUM clicks;

You need to keep the table well vacuumed to get an index only scan.


text:
Q: Querying Oracle in Java using JDBC Result Set is Null, Query is fine in SQLDeveloper I'm working on some development in Java touching an Oracle database.  I have been able to successfully connect and pull some data from the database, however, when I try to use a query that will pull a subsection of the data at a time I am getting a null ResultSet.
    HashMap<String, String> tableSchema = getTableSchema(connection, tableName);
    Map.Entry<String, String> entry = tableSchema.entrySet().iterator().next();
    int rows = (getTableRowCount(connection, tableName));
    for(int i = 0; i < rows; i+= 500){
        String query = "SELECT * FROM (SELECT a.*, row_number() OVER (ORDER BY " + entry.getKey() + ") rn FROM " + tableName + " a) WHERE rn > " + i + " and rn < " + (i+500) + ";";
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        if(rs == null){
         // Always the case
        }
     }

If I execute a query that is simply
query = "SELECT * FROM " + tableName;
the resultSet is full of data.  I have also taken the result of the construction of the query string (via println) and pasted it into Oracle SQL Developer, where it has produced results.
So I suppose this brings up a few questions and answering any would likely solve the problem.  Is there a better way to iterate through an Oracle database table in Java (some of these tables are too big so I won't be able to load them wholesale into memory) rather than this query?  Is there a different type of query that I can use?  Is there any known reason why this would be returning null when the same query works in SQL Developer?


text:
Q: how to append a byte array to file without overwriting it using java I trying to make an AES encryption and i am generating a salt . However i had encountered some issue. the below code work fine but whenever i encrypted the second and so on files, the salt in side the file is overwritten. any suggestion on how to append the salt byte [] into the salt fil without overwriting it ?
Guys..i updated my code..thanks for that portion  although it fixed the overwritting issue, it does not make it to next line.
output on my file : ˜V"÷ҲÖ4ô¦ŒT‰mÊî0'Z^'û•šÙK· = this is two salt combined.
any idea how to make it append on next line?
i trying saltoutfile.write("/n") but doesnt work
    public byte[] generateSalt() throws IOException{
            //generate Salt value
            // password, iv and salt should be transferred to the other end
            // in a secure manner
            // salt is used for encoding
            // writing it to a file
            // salt should be transferred to the recipient securely
            // for decryption
    byte[] salt = new byte[8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(salt);
            FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc" , true);
            saltOutFile.write(salt);
        saltOutFile.close();
            return salt;

}

as mentioned in comment: this is my read salt value
    public static byte[] readSalt() throws IOException{
    // reading the salt
            // user should have secure mechanism to transfer the
            // salt, iv and password to the recipient
            FileInputStream saltFis = new FileInputStream("C:\\KryptZIP\\salt.enc");
            byte[] salt = new byte[8];
            saltFis.read(salt);
            saltFis.close();
            return salt;
}

A: You need to use the constructor of FileOutputStream with 2 arguments. The second argument is a boolean flag indicating whether you want to append (true) to the file or write from the beginning (false).
Change your code to:
 FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc", true);

A: Use the Apache FileUtils. Use the methdod
FileUtils.writeByteArrayToFile(java.io.File file,bytes[] content,boolean append)


text:
Q: Why deepcopy doesnt create new references to lambda function? Found this strange in python:
class SomeClass():
    def __init__(self):
        pass

a = [SomeClass()]
b = copy.deepcopy(a)

Output:
>>> a
[<__main__.Some instance at 0x10051b1b8>]
>>> b
[<__main__.Some instance at 0x10051b092>]

This is just as expected- deepcopy created new SomeClass() object for b.
But if,
f = lambda x:x+1
a = [f]
b = copy.deepcopy(a)

I get:
>>> a
[<function <lambda> at 0x10056e410>]
>>> b
[<function <lambda> at 0x10056e410>]

Why deepcopy doesnt create a new lambda instance in the second case? does that mean lambda functions are atomic?

A: This applies not just to lambdas, but to functions without state more generally.
>>> def some_function(word): print word
>>> a = [some_function]
>>> a
[<function some_function at 0x1007026e0>]
>>> copy.deepcopy(a)
[<function some_function at 0x1007026e0>]

Because the functions do not store state, deepcopy does not create a new reference for them. An interesting discussion of topics similar to this issue (though not exactly the same issue) is recorded here: http://bugs.python.org/issue1515

A: As a side note to some people thinking that lambdas are not mutable, observe the following behavior:
>>> a = lambda x: x + 1
>>> a(12)
13
>>> b = lambda x: x - 1
>>> b(12)
11
>>> a.__code__ = b.__code__
>>> a(12)
11
>>>

A: Looking at lines 222 and 223 from the source code:
d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic

The module considers them atomic, and I don't know how you can mutate a lambda.

A: I don't know the complete history of Python, but it's possible that functions used to be as immutable as strings and tuples, and so that originally it was perfectly reasonable for deepcopy to behave as it does.
Also, in practice, most people are more concerned that their data objects are being copied than their functions. The necessity for deepcopy to make a copy of functions is a clear edge case, and expecting people subject to that edge case to roll their own solution seems perfectly fine to me.
A reasonable approach would be to write a decorator @copyablefunc that wraps the function in a callable object (i.e. a class that has a __call__() method) and that also defines __copy__() and __deepcopy__() methods to be used by the deepcopy routine.
copy.deepcopy also doesn't truly copy classes, just by the way.


text:
Q: MVC ActionResult parameter when Page refreshed I have ActionResult that uploads multiple files
[HttpPost]
    public ActionResult Upload(object obj)
    {
        // Loading all files

        var result = new UploadResultProcess(fileUploads);
        UploadCache.CleanAdd(UploadCache.UploadResult, result);
        return RedirectToAction("Details", new { @loadAll =true});
    }

The ActionResult Details has optional parameter
   public ActionResult Details(bool loadAll=false)
   {
       // Load from cache
       var result = (UploadResultProcess)UploadCache.Get(UploadCache.UploadResult);
       result.Process(Uow, loadAll);
       return View(result);
    }

Based on loadAll parameter the function result.Process will process specific files only.
In my Details view when refresh is clicked, loadAll is still true, why is that? how can i rest the value to false if the refresh is clicked


text:
Q: Appending query parameter to Woocommerce category URL I'm trying to force display the list view in my Woocommerce store but I can't seem to get it working.
The theme has support for list view and you can force it by appending "?product_view=list" so a category URL becomes:
http://subliminalscience.com/product-category/icbch-hypnosis-certification/?product_view=list

Instead of the default one:
http://subliminalscience.com/product-category/icbch-hypnosis-certification/

I added this Rewrite Rule to my htaccess but it doesnt:
RewriteRule ^product-category(.*)$ http://subliminalscience.com/product-category$1?product_view=list

It seems Wordpress ignores this Rewrite rule. Any ideas?

A: I'm surprised this answer stands as the only one.
Making changes in .htaccess to force this sort of behaviour seems really unnecessary and obviously isn't useful for others trying to solve this issue, especially those users on nginx servers or on shared hosting without .htaccess access.
You should try to fix this in PHP using an action.
Looking at your question, I can tell that theme you have is checking for GET data in the URL bar, which is the ?key1=value1&key2=value2 part of an URL. GET is an HTTP method that you can read about here if you want to learn more.
You can actually set GET data in PHP, and you can safely put this into your functions.php file.
You will want to create a function that simply checks the current page, and if it's a product category page sets the GET data.
At the bottom of your functions.php, you'd want to add something like this:

<?php
//Force all category pages to list view.
add_action('woocommerce_before_main_content','force_category_list_view', 5);
function force_category_list_view(){
  if(is_product_category()){
    $_GET['product_view'] = 'list';
  }
};
?>

I actually can't test this, but I think it'd work. Essentially, in the woocommerce template archive-product.php, the first action that runs is 'woocommerce_before_main_content'. What we're doing is calling our function, which checks the page is indeed a product category. If it is, it sets the GET variable as list, which is exactly what the URL is telling the page to do already.
Mainly this is just a better practise than altering your .htaccess, but someone determined could also override that GET data by changing the URL to read ?product_view=list&product_view=xyz I can't imagine this would be an issue in this instance, but in other instances it might be.


text:
Q: How to check if bit variable is true or false in sql server? I have a simple query and all I want to do is check if this variable is true or false, and for some reason it always returns false.
DECLARE @CappedIFCheck BIT
SET @CappedIFCheck = (SELECT distinct 1
                      FROM mytable
                      WHERE 1=1);

select @CappedIFCheck
     IF (@CappedIFCheck = 'True')
        BEGIN
           SELECT 'true';
        END
     ELSE
        BEGIN
           SELECT 'false';
        END

A: When comparing BIT values in Sql Server, use literal values 1 and 0 instead of 'True' and 'False'.
IF (@CappedIFCheck = 1) ...

A: A bit variable in SQL Server can have three values. 0, 1 and NULL.
The strings 'true' and 'false' map to 1 and 0 respectively.
Your code does not take account of the third possible value. If mytable is empty then the variable will not be initialised and have the value NULL.
SELECT CASE @CappedIFCheck
         WHEN 'True' THEN 'true'
         WHEN 'False' THEN 'false'
         ELSE 'unknown'
       END

I'm not sure exactly what your code is trying to do but that is a very inefficient way of going about things. You should use EXISTS instead.

A: Try the set clause like this:
SET @CappedIFCheck = ISNULL((select 1 where exists (select 1 from MyTable where 1=0)),0)


text:
Q: Exchange EWS ItemClass values I searched a lot, but I was not able to find the common text values which the ItemClass type can take.
I am aware of the fact that there can be custom values (like IPM.Note.Custom.MyClass), but are common values like IPM.Note, IPM.Contact, etc. documented somewhere?

A: Item Types and Message Classes are documented on MSDN.

A: I was looking for the same thing.  SilverNinjas link doesn't work anymore.
I found it here.


text:
Q: How to make a search in 2 different collection (with pagination) in MongoDB I have two collections, one is Users and the other is Posts. I tried to find() in both collections and concat the result, but I faced a problem in pagination. My question is how can I achieve this in one query so I can paginate.
Example:
Users:

    {
        _id: 1
        username: 'test',
        type: 'users'
        ...
    }

Posts:
    {
      _id: 1,
      name: 'test3',
      type: 'posts',
      ...
    }

And when I search for example 'test' I should get both user data and post data with 'test' in the username/name.
Also, I tried aggregate but there is nothing common in the two tables to join.
And I have a question, will these cause performance issues for many searches ?
Any help is appreciated. Thanks

A: You can use $unionWith aggregation stage. It performs a union of two collections.

*

*$unionWith to perform union of two collections. Note that $unionWith is available starting with MongoDB version 4.2.

*$match with $regex to filter only documents where username or name field contains a specified string. Note that $options: "i" will make the search case-insensitive. If you want case-sensitive search, just remove $options: "i" from the query.

db.users.aggregate([
  {
    "$unionWith": "posts"
  },
  {
    "$match": {
      "$or": [
        {
          "username": {
            "$regex": "test",
            "$options": "i"
          }
        },
        {
          "name": {
            "$regex": "test",
            "$options": "i"
          }
        }
      ]
    }
  }
])

Working example


text:
Q: Iterar em vários arquivos de texto Boa tarde. Tenho o seguinte objetivo: Tenho uma série de arquivos de texto e desejo criar um script para iterar sobre todos eles e contar quantas vezes determinadas strings aparecem neles.
Eu consegui realizar o script para o caso de um único arquivo. Mas estou com dificuldades para realizar o procedimento de contagem no caso de usar uma iteração em múltiplos arquivos.
Segue abaixo a minha tentativa de código:
# Eu organizei as strings que devem ser localizadas por meio de um dicionário. O dicionário abaixo é apenas exemplificativo, na realidade o do meu código é bem mais extenso.
mi = {"key1": value1, "key2": value2}

# Os arquivos que desejo realizar a varredura estão nomeados segundo um determinado padrão, por exemplo, "ABC 01.2015.txt ; ABC 02.2015.txt e etc.

# O teste consiste em 3 arquivos, no qual em cada um deles cada valor do meu dicionário deve aparecer uma única vez. Dessa maneira, o código deve resultar em 3 contagens para cada valor do meu dicionário.

# Em seguida criarei um dicionário ordenado por key, bem como uma lista vazia que desejo adicionar a contagem correspondente a cada string.

import collections
od_mi = collections.OrderedDict(sorted(mi.items()))
count_occur = list()
soma = 0
for i in range(2,5):
    for value in od_mi.values():
        x = "ABC" + " " + str(i) +".2015.txt"
        data = open(x, "r").read()
        contar = data.count(value)
        soma += contar
        count_occur.append(soma)
print count_occur
#O output para a minha lista está incorreto, vejam abaixo:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384]

#Em seguida tentei modificar o meu código e apenas consegui com que o output fosse o registro da contagem apenas do último arquivo lido, na realidade ele sobrescreveu os dados a cada novo arquivo.
count_occur = list()
for i in range(2,5):
for value in od_mi.values():
    x = "ABC" + " " + str(i) +".2015.txt"
    data = open(x, "r").read()
    contar = data.count(value)
    count_occur.append(contar)
print count_occur
output: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Alguém poderia me ajudar ? Sou novo em programação de modo geral, quaisquer informações adicionais necessárias que necessitem podem falar!

A: Se quiser contar quantas vezes as palavras aparece, por arquivo:
import os

strings = ['uma', 'frase']

files = [f for f in os.listdir("/tmp") if f.startswith('arq') and f.endswith('.txt')]

for filename in files:
    with open(filename, 'r') as f:
        data = f.read()
        for s in strings:
            print filename, s, data.count(s)

Se quiser contar quantas vezes as palavras somando todos os arquivos:
counts = {}
for filename in files:
    with open(filename, 'r') as f:
        data = f.read()
        for s in strings:
            if s in counts.keys():
                counts[s] += data.count(s)
            else:
                counts[s] = data.count(s)
print counts

Para esse exemplo eu crie os seguintes arquivos:
/tmp/arq1.txt:
uma frase qualquer

/tmp/arq2.txt:
uma outra frase qualquer

/tmp/arq3.txt:
aqui tem uma frase diferente

/tmp/arq4.txt:
uma frase com a palavra frase


text:
Q: a chocolate vs some chocolate
Would you like a chocolate? (If I offer to taste one chocolate from a box.)
Would you like some chocolate? (If I offer to taste a bar of chocolate.)

Is it correct?

A: Yes, "chocolate" is often used both as a countable and as a mass noun.
"Chocolate" as a mass noun refers to the substance, in the same way as "butter" or "flour," and we can talk about "some chocolate" (a certain quantity of the substance).
"Chocolate" as a countable noun can be thought of as short for "a piece of chocolate." We might have a box of chocolates (individual pieces, e.g. truffles) and we can give someone a chocolate.
This doesn't apply to all substances; we never say "a box of butters" or "would you like a flour."


text:
Q: D3: Click on map and trace the closest path until the coast For the application I would like to build, the user can click on any point of the map, and the nearest river path could be identified and animated until it reaches the coast.  I used D3 to draw a bunch of paths (rivers) from a geojson file, each path is a feature with the geometry type LineString. I figured I could use d3's voronoi to identify the closest path when user clicks on a point. My biggest problem is, I could probably identify to closest river segment, but I am not sure how to automatically trace the rest of the paths until it reaches the coast. For example, you can see in the image I attached, one path is highlighted, but I would also like the paths after it to be highlighted. My only idea is that I could create a new geojson file that with all possible stream paths (as a whole, not individual segments), how would I create this file from a file where each individual segment is a path? I provided 3 features from the my geojson file at the end just to give you an idea of how my current data is organized

{"type": "FeatureCollection","crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },"features": [{ "type": "Feature", "properties": { "arcid": 15, "grid_code": 1, "from_node": 4074, "to_node": 4069, "Shape_Leng": 24.8000011779 }, "geometry": { "type": "LineString", "coordinates": [ [ 128.257362464927638, 26.8747231358752 ], [ 128.257361002021611, 26.874947030137374 ] ] } },{ "type": "Feature", "properties": { "arcid": 16, "grid_code": 1, "from_node": 4075, "to_node": 4070, "Shape_Leng": 24.8000011779 }, "geometry":{ "type": "LineString", "coordinates": [ [ 128.258485955739388, 26.874729034949482 ], [ 128.258484495046019, 26.87495292926857 ] ] } },{ "type": "Feature", "properties": { "arcid": 23, "grid_code": 1, "from_node": 4083, "to_node": 4068, "Shape_Leng": 69.318110594900006 }, "geometry": { "type": "LineString", "coordinates": [ [ 128.256990163500433, 26.874385326154584 ], [ 128.256674423121041, 26.874943420716903 ] ] } }]}


text:
Q: Formatting number as current in word using vba I m using vba codes to generate reports from excel to word and I am getting stuck. The number I am copying seems to not have the format from excel,  I need it to be formatted into currency i.e. $1,000 or $5,212,345 and right now it just showing as 1000 and 5212345.
Here is my codes, I have a method or data member not found error.
.TypeText "Total Written Premium: " & ws4.Range("I" & LR12)
.Format (ws4.Range("I" & LR12) = "$#,##0.00_)")

A: .TypeText "Total Written Premium: " & ws4.Range("I" & LR12)

You're fetching the Range's Value, implicitly. This would be more explicit:
.TypeText "Total Written Premium: " & ws4.Range("I" & LR12).Value

A cell's value doesn't have any formatting. It's not a representation of the underlying value, it's the value itself.
If the cell is already formatted as currency then you need to get its Text instead:
.TypeText "Total Written Premium: " & ws4.Range("I" & LR12).Text


text:
Q: Testing performance of Java project in Eclipse using VisualJVM I aim to do some timing/memory tests on a Java application that is runned via Eclipse.
After browsing the Web, I have found the "Visual JVM" that can be considered as a fine tool for prifiling the application. Isn't?
So, my question is how can I download and use it in Eclipse? are there some tutorials/codes that guide me?
Thnx for Your prompt answers that I really need.
Cheers,
Sana.

A: Here is a tutorial for using VisualVM in various IDEs; including Eclipse.
You can download the VisualVM launcher here. VisualVM is actually in your JDK, and can be run as a stand-alone (separate from Eclipse) program from there.