text:
Q: Quick, simple web farm setup I am using asp.net 3.5 and SQL server 2008 and want to setup a very simple web farm.
I have purchased 2 VIRTUAL servers, I DO NOT use viewstate or sessions on my webpages, just cookies so all I need to do is have 2 versions of the same database, on each virtual server (I assume) and 2 versions of the binaries/webpages on each server (I assume). What I need is some sort of guide to set these up so that when a user makes a request:
a) The servers are load balanced and the request sent to the least loaded server
b) Whenever a SQL database change is made, it is reflected in the other database too
Does this sound possible?

A: You're asking for two things: a web farm and a SQL cluster. SQL Server doesn't support active/active clustering/mirroring. You'll either need to set up DB mirroring (easier for hosted) or a SQL cluster, but regardless, only one SQL Server can be actively serving requests at a time. You can do multi-master replication on SQL Server, but there's usually a significant delay between servers, so if you don't have connection affinity on your web farm, you'll be plagued with stale data problems.
The web farm part is pretty easy since you app is stateless- especially if you're using IIS7. Just use the new ARR (Application Request Routing) extension.


text:
Q: Context - unable to create external files directory I have a very strange problem with my app that appears when you start app on the Nexus 4.
I have following code in Application class:
public class MyApp extends Application {

@Override
public void onCreate() {
    super.onCreate();
    File dir = this.getExternalFilesDir(null);
    if (dir == null) {
        Log.e("App", "Problem with my dir!");
    }
}

In LogCat I saw message:

12-11 14:09:05.402 11739-11739/com.company.app W/ContextImpl: Unable to create external files directory
  12-11 14:09:05.402 11739-11739/com.company.app E/App: Problem with my dir!

I already have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in my AndroidManifest.xml.
Also, this problem appears only when I re-install my application and don't reboot my device. If I reboot my Nexus, problem disappear.
What can be wrong in this simple code snippet?..
Thank you in advance for your reply.

A: you have to do this way
File dir = new File (this.getExternalFilesDir(null) + "/NewDirectory");
if(!dir.exists()){
  f.mkdirs();// if there is no directory then create new
}

when use getExternalFilesDir() no need to add permission. its only needed when use getExternalStorageDirectory()

A: I've finally found cause of this strange behaviour.
In my application, after some initialization in Application class, I've started logging process like this:
String[] cmd = new String[] {
    "logcat", "-f", myFileNameFromExternalDir, "-v", "time"
};
Runtime.getRuntime().exec(cmd);

And I didn't destroy this process anywhere. That's why after re-intalling my app, Android unable to create external files dir or cache dir.
Summary:

*

*If you started some process, don't forget to destroy it, e.g:
Process process = Runtime.getRuntime().exec(cmd);
...
process.destroy();

*To check, if there are some unusual processes running on your device, you can use adb shell. For example:
In Windows cmd
adb shell
In Android shell
ps - it will list all processes on your device.
If you found something interesting, you can check, does this process belong to your application with lsof command:
lsof -p process_name | grep app_package

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compact letter display for kruskal- wallis Dunn post-hoc test I have a dataframe that I am performing kruskal-wallis tests on. I would like to add a compact letter display of the result to:

*

*A table of the mean, sd, Z stat, P value, + letters

*A Graph of the results with the compact letters displayed

There is a wealth of knowledge on how to do this after a TukeyHSD, but I can't figure it out using other models post-hocs i.e. Kruskal-Wallis Dunn test, welch ANOVA pairwise.t.test etc. I have thought about doing it manually, but it is not working.
This is what I have so far:
data <- iris
kruskal <- kruskal.test(Petal.Width ~ Species, data = data)
kruskal_ph <- dunnTest(Petal.Width ~ Species,
                  data=data,
                  method="bonferroni")

#Make CLD here ....

#OR

#First make comparisons table and mannually insert letters. E.g.

pvalue <- kruskal_ph[[2]][, "P.adj"]
    hi <- kruskal_ph[[2]][,"Comparison"] %>%
              as.data.frame()
      hi <- hi %>%
          rename(hi, comps = .) %>%
          separate(comps, c("group1","group2"))
      comparisons <- cbind(hi, pvalue)
    comparisons$Sig <- comparisons$Sig
    comparisons$Sig[comparisons$pvalue > 0.05] <- "ns"
    comparisons$Sig[comparisons$pvalue <= 0.05] <- "*"
    comparisons$Sig[comparisons$pvalue <= 0.01] <- "**"
comparisons

# Make CLD from comparisons here

# Add to a summary table (how?) and graph?

library(ggplot2)
ggplot(data, aes(x = Species, y = Petal.Width, colour = Species, fill = Species)) +
  geom_bar(stat = "summary", fun = "mean")

A: The agricolae package may be useful in this scenario.
Try this:
library(agricolae)
kruskal_cld <- kruskal(iris$Petal.Width, iris$Species, group=TRUE, p.adj="bonferroni")$groups
cld <- as.data.frame(kruskal_cld)
group_df <- iris %>%
  group_by(Species) %>%
  summarise(mean = mean(Petal.Width), sd = sd(Petal.Width))

library(ggplot2)
ggplot(iris, aes(x = Species, y = Petal.Width, colour = Species, fill = Species)) +
  geom_bar(stat = "summary", fun = "mean") +
  geom_text(data = group_df, aes(label = cld$group, y = mean + sd, x = Species), vjust = -0.5, inherit.aes = FALSE)

Others will have to help for the table, I am still learning R myself :)


text:
Q: JNLP Application not running when parameters are passed I've got an application which was converted from an applet to a stand-alone application.
The application consists of a JNLP file which contains a string as an argument and a jar containing a main method (and additional resources). The main method is called through the JNLP.
Working code:
public static void main(String[] args) {
    try {
        xmlParams = new String(
                base64Decoder
                        .decodeBuffer("/*Base 64 encoded XML here*/"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    AppletSignatura applet = new AppletSignatura();
    applet.setLayout(new FlowLayout());
    applet.init();
}

Not working code:
public static void main(String[] args) {
    xmlParams = args[0];
    AppletSignatura applet = new AppletSignatura();
    applet.setLayout(new FlowLayout());
    applet.init();
}

As shown in the code samples, it works only when the string xmlParams (it's static) is set beforehand, but not when it's passed as an argument to the main method. Why is that so?
Here's the JNLP:
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/portafirmes/applets/" href="output.jnlp">
<information>
    <title>NotAnymoreAnApplet</title>
    <vendor>Me</vendor>
</information>
<resources>
    <property name="jnlp.packEnabled" value="true"/>
    <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se" />
    <jar href="signer-applet.jar" main="true" download="eager"/>
    <jar href="jackson-core-asl-1.9.0.jar"  download="eager"/>
    <jar href="jackson-mapper-asl-1.9.0.jar"  download="eager"/>
</resources>
<security>
    <all-permissions/>
</security>
<application-desc main-class="es.gematic.AppletSignatura">
    <argument>*ARGUMENT IN HERE*</argument>
<update check="background"/>
</application-desc>
</jnlp>

I haven't copied any Base64 String because they're long as ****, but they're properly encoded.


text:
Q: Verilog: Cannot Attach Register As Output? I am trying to compile my module and it works fine when I remove the badData register from the testbench. However, the moment I add it, verilog complains "Error loading design".
Module Code:
module hamming_code #( parameter TOTAL_LENGTH = 15,
                               parameter PARITY_BITS = 4
                           )
                (
                    //inputs
                    input [TOTAL_LENGTH-1:0] codeword,

                    //outputs
                    output [TOTAL_LENGTH-1:0] correctedWord,
                output reg badData
                );

Testbench code:
`timescale 1ns/1ps
module tb ();
integer pass_count, fail_count;
reg clock;
reg [14:0] cw;
wire [14:0] ccw;
reg error;
integer i;

hamming_code uut (// Inputs
                            .codeword(cw),
                            // Outputs
                            .correctedWord(ccw),
                            .badData(error)

                         );

initial begin
// initial values
clock <= 0;
pass_count <= 0;
fail_count <= 0;
error <= 0;
wait(0);
end

always@(*)
#5 clock <= ~clock;

endmodule

A: BadData is an output from your uut.
It should be connected to a wire in the TB. Also it shouldn't be assigned any value in TB (you are assigning a 0).
When you remove reg error, Its automatically inferred as  a wire. that's why there is no error.


text:
Q: Javascript caching tools and techniques I have a requirement where in I want to loop through all the DropDown (select) controls on a page. I am picking all the DropDown controls using:
var DropDowns = document.getElementByTagName('select');

I loop through these DropDowns to set an option programatically of few controls:
for (i=0; i<= DropDowns.Length; i++)
{
    var CurrentControl = DropDowns[i];
    CurrentControl.options[CurrentControl.selectedIndex].value = 1;
}

Is there any Javascript framework which supports caching? I want to cache all the DropDown control names and loop through the cached names instead of directly looping through Document object.
Are there any tricks to increase the performance of the loop?

A: I don't think that you're going to see huge improvements in performance for a loop that is only iterating through 30-40 elements, but some browsers will get a huge speed boost from looping through an array instead of a NodeList or HTMLCollection as it is called in some browsers that implement DOM level 1.
So, to answer your question, you can "cache" the objects etc. in an array and it should speed up that loop for future iterations.
Be aware that you need to keep this array up-to-date because it is not "live" like the DOM is.

A: In jquery, it would look something like this:
var $menus = $('select');
$.each($menus, function(index, menu) {
    // Do whatever you want to the menu here
};

A: I am suggesting a different approach -
Save the options in a hidden field with a comma separated values and on page load set the values of control by parsing the , separated values.

A: I think you're already doing this much more efficiently than some of the answers describe. Bear in mind you're not continuously looping through the document, you're looping through your cached NodeList of DropDowns. If you want to change each one of these elements, then you will inevitably need to loop through them to change them individually.


text:
Q: How to use a function's output as another function's input? I have this function to check the formal correctness of the user's email in a webform, in order to send an email to the webmaster using the user's email address.
<?php
function verificarEmails($rte) {
    $_POST['emailRemitente'] = $rte;
    if (!filter_var($rte, FILTER_VALIDATE_EMAIL)) {
        echo "
Oops! el mail debe ser correcto";
    } else {
        return $rte;
    }
}

If I want to use the output of that function within a second function (the one that actually sends the email), should I add (inside the second function), something like this?
$emailRemitente = verificarEmails($_POST['emailRemitente']);

What am I doing wrong here? I'm very sure there's this big fat elephant that I'm missing. This $_POST['emailRemitente'] is the user input, and the problem is that the verificarEmails() function won't work (it allows malformed emails to be sent using the form).
Update:
The second function complete is this:
<?php
function enviarMails($correo) {
    $miEncabezado = "Estimada,
";
    $emailRemitente = verificarEmails($_POST['emailRemitente']);
    $nombreRemitente = $_POST['nombreRemitente'];
    $para   = $correo;
    $asunto = 'Urgente';
    $mensaje = $miEncabezado . $GLOBALS['texto'];
    $headers = 'From: '.$nombreRemitente.' '.'<'.$emailRemitente.'>'."\r\n";
    $headers .= 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    //mando mail a los usuarios
    $envioUsuarios = mail($para, $asunto, $mensaje, $headers);
    if($envioUsuarios) {
        echo '
Mensaje enviado a '.$correo.'
';
    } else {echo'
No se mandó mail a '.$correo.'
';}
}

A: function verificarEmails($rte) {
    //$_POST['emailRemitente'] = $rte;
    if (!filter_var($rte, FILTER_VALIDATE_EMAIL)) {
        echo "
Oops! el mail debe ser correcto";
    } else {
        return $rte;
    }
}
//another function
function func2($value2) {
     return verificarEmails($value2);

}

echo func2('jack@gmail.com');

A: Try this
<?php

function enviarMails($correo) {
    if (filter_var($_POST['emailRemitente'], FILTER_VALIDATE_EMAIL)) {
        $miEncabezado = "Estimada,
";
        $nombreRemitente = $_POST['nombreRemitente'];
        $para   = $correo;
        $asunto = 'Urgente';
        $mensaje = $miEncabezado . $GLOBALS['texto'];
        $headers = 'From: '.$nombreRemitente.' '.'<'.$_POST['emailRemitente'].'>'."\r\n";
        $headers. = 'MIME-Version: 1.0' . "\r\n";
        $headers. = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        //mando mail a los usuarios
        if(mail($para, $asunto, $mensaje, $headers)) {
            echo '
Mensaje enviado a '.$correo.'
';
        } else {
            echo'
No se mandó mail a '.$correo.'
';
        }
    } else {
        // email not validated
    }
}

With 2 functions:
<?php

function verificarEmails($rte) {
    if (!filter_var($rte, FILTER_VALIDATE_EMAIL)) {
        return false;
    } else {
        return true;
    }
}

function enviarMails($correo) {
    if (verificarEmails($_POST['emailRemitente']) {
        $miEncabezado = "Estimada,
";
        $nombreRemitente = $_POST['nombreRemitente'];
        $para   = $correo;
        $asunto = 'Urgente';
        $mensaje = $miEncabezado . $GLOBALS['texto'];
        $headers = 'From: '.$nombreRemitente.' '.'<'.$_POST['emailRemitente'].'>'."\r\n";
        $headers. = 'MIME-Version: 1.0' . "\r\n";
        $headers. = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        //mando mail a los usuarios
        if(mail($para, $asunto, $mensaje, $headers)) {
            echo '
Mensaje enviado a '.$correo.'
';
        } else {
            echo'
No se mandó mail a '.$correo.'
';
        }
    } else {
        // email not validated
    }
}


text:
Q: How to use get_cfg_var() in a cakePHP app ? I have a cakePHP app with my DB servers configured in the app/config/
database.php file. However, I need to use the get_cfg_var ('mysql.default_host') to get the host name because the client does not want the name hardcoded.

A: In the /app/config/bootstrap.php file, add a new constant like so:
<?php
// get the default host name set in php.ini
$defaultHost = get_cfv_var('mysql.default_host');
// might want it to try using localhost if get_cfv_var is not set
if(!$defaultHost) {
  $defaultHost = "localhost";
}
define("DB_HOST_NAME", $defaultHost);
?>

Then in /app/config/database.php, in the default array (or whatever DB array you are using for production) use the constant:
<?php
// set up the database connection
var $default = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => DB_HOST_NAME, // use the default set by get_cfv_var()
        'login' => 'username',
        'password' => 'password',
        'database' => 'database',
        'prefix' => '',
    );
?>

Hope this helps!


text:
Q: Undefined variable во view при создании переменной через middleware (Laravel) Страница состоит из 2-х частей: "шапка" + "контент".
@include('layouts.header')
@yield('content')

В middleware определяется переменная $x, 100% получающая значение true или false и отправляется во вьюхи:
view()->share('x', $x);

Во вьюхе "content" всё работает, а в "header" на боевом сервере нет - Undefined variable!
При этом, на локальном сервере всё хорошо! Пробовал в ENV менять local на production и менял true/false на 1/0. Ничего не помогло.


text:
Q: Windows global shortcut hijacked by Opera I have Chrome 37 installed as my main browser. Recently I needed to test a design in a new, Chromium based Opera version 21.0.1432.67.
This later one hijacked my global shortcuts somehow, so if I press Ctrl+Shift+N to start a new session for testing, even if Chrome is running, and it is the active window, the shortcut starts a new Opera tab - even if the program is not running.
It is highly annoying. Even if I uninstall Opera, I'm unable to use the aforementioned shortcut, because it will not work at all.
Any hints on how to restore the original shortcut?

A: ...with the help of Hotkey commander 2.1 I figured out that Ctrl+Shift+N was handled globally by ClipX (which is by the way a nice app for managing the clipboard) and it started Opera as a default browser for such an action. By disabling ClipX's global shortcuts everything is back on track.


text:
Q: Excel workbook closing but worksheet staying active? So, I have this script that I had running, but modified to sort data into different sheets based on an input box.  It works, and does everything I want it to, but now, every time I run it, a new instance of Excel runs in the background.  As far as I can tell(and I don't really know much about this sort of thing), is that somehow the workbook is closing, but the worksheet is staying active. I've been looking up stuff and reading for hours trying to figure this out, am I at least heading in the right direction??  This is a basic script inserted into a PC DMIS program(outside of Excel).  I have the changes I made to achieve the sorting process(2 paragraphs) marked with "worksheet input":
Sub Main

'xl Declarations
Dim xlApp As Object
Dim xlWorkbooks As Object
Dim xlWorkbook As Object
Dim xlSheet As Object
Dim count As Integer
Dim xlWorksheets As String
Dim xlWorksheet As String

'pcdlrn declarations And Open ppg
Dim App As Object
Set App = CreateObject("PCDLRN.Application")
Dim Part As Object
Set Part = App.ActivePartProgram
Dim Cmds As Object
Set Cmds = Part.Commands
Dim Cmd As Object
Dim DCmd As Object
Dim DcmdID As Object
Dim fs As Object
Dim DimID As String
Dim ReportDim As String
Dim CheckDim As String

Dim Cavity As String                                              'start worksheet input 1
Dim myValue As String
Dim message, title, defaultValue As String
message = "Cavity"
title = "cavity"
defaultValue = "1"
myValue = InputBox(message, title, defaultValue)
If myValue = "" Then myValue = defaultValue       'end worksheet input 1

'Check To see If results file exists
FilePath = "C:\Excel PC DMIS\3K170 B2A\"
Set fs = CreateObject("Scripting.FileSystemObject")
ResFileExists = fs.fileexists(FilePath & Part.partname & ".xls")

'Open Excel And Base form
Set xlApp = CreateObject("Excel.Application")
Set xlWorkbooks = xlapp.Workbooks
If ResFileExists = False Then
    TempFilename = FilePath & "Loop Template.xls"
Else
    TempFilename = FilePath & Part.partname & ".xls"
End If

Set xlApp = CreateObject("Excel.Application")

Set xlWorkbook = xlWorkbooks.Open(TempFilename)
Set xlSheet = xlWorkbook.Worksheets("Sheet1")
Set xlsheets = xlworkbook.worksheets                   'start worksheet input 2

'Set xlWorksheets = xlapp.Worksheet
'Set xlWorksheets = xlapp.Worksheets
Dim sh As Worksheet, flg As Boolean
For Each sh In xlworkbook.worksheets
     If sh.Name = myValue Then flg = True: Exit For
Next

If flg = False Then
   xlsheets.Add.Name = myValue
End If

Set xlSheet = xlWorkbook.Worksheets(myValue)       'end worksheet input 2

If ResFileExists = False Then
    RCount=6
    CCount=3
    xlSheet.Range("B1").Value = Part.PartName
    xlSheet.Range("A6").Value = Date() & " " & Time()
    xlSheet.Range("B6").Value = "Inspector Name"
    For Each Cmd In Cmds
        'Eliminate DATDEF's
        If Cmd.Type <> 1299 Then
            'Do Dimensions
            If Cmd.IsDimension Then
                If Cmd.Type = DIMENSION_START_LOCATION Or Cmd.Type = DIMENSION_TRUE_START_POSITION Then
                    Set DcmdID = Cmd.DimensionCommand
                      DimID = DcmdID.ID
                      ReportDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                End If
                If Cmd.Type <> DIMENSION_START_LOCATION And Cmd.Type <> DIMENSION_END_LOCATION And _
                    Cmd.Type <> DIMENSION_TRUE_START_POSITION And Cmd.Type <> DIMENSION_TRUE_END_POSITION Then
                    Set DCmd = Cmd.DimensionCommand
                    CheckDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                    If CheckDim <> "" Then
                            ReportDim = CheckDim
                    End If
                    If ReportDim = "BOTH" Or ReportDim = "REPORT" Then
                        If DCmd.ID = "" Then
                                xlSheet.Cells(5,CCount).Value = DimID & "."& DCmd.AxisLetter
                        Else
                                xlSheet.Cells(5,CCount).Value = DCmd.ID & "." & "M"
                        End If
                                xlSheet.Cells(2,CCount).Value = DCmd.Nominal
                                xlSheet.Cells(3,CCount).Value = DCmd.Plus
                                xlSheet.Cells(4,CCount).Value = DCmd.Minus
                                'Measured Or Deviation With check For True Position
                    If DCmd.AxisLetter <> "TP" Then
                                  xlSheet.Cells(6,CCount).Value = DCmd.Measured
                Else
                                  xlSheet.Cells(6,CCount).Value = DCmd.Deviation
                End If
                                'Add Min/Max For Profile dimensions
                                If Cmd.Type = 1118 Or Cmd.Type = 1105 Then
                                  CCount=CCount+1
                                  xlSheet.Cells(5,CCount).Value = DCmd.ID & "." & "Max"
                                  xlSheet.Cells(2,CCount).Value = DCmd.Nominal
                                  xlSheet.Cells(3,CCount).Value = DCmd.Plus
                                  xlSheet.Cells(4,CCount).Value = DCmd.Minus
                                  xlSheet.Cells(6,CCount).Value = DCmd.Max
                                  CCount=CCount+1
                                  xlSheet.Cells(5,CCount).Value = DCmd.ID & "." & "Min"
                                  xlSheet.Cells(2,CCount).Value = DCmd.Nominal
                                  xlSheet.Cells(3,CCount).Value = DCmd.Plus
                                  xlSheet.Cells(4,CCount).Value = DCmd.Minus
                                  xlSheet.Cells(6,CCount).Value = DCmd.Min
                                End If
                                CCount=CCount+1
                    End If
                End If
            End If
            'Do GDT
            If Cmd.Type = 184 Then
                  ReportDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                  If ReportDim = "BOTH" Or ReportDim = "REPORT" Then
                        xlSheet.Cells(5,CCount).Value = Cmd.GetText (ID, 0) & "." & "FCF"
                        xlSheet.Cells(2,CCount).Value = "0"
                        xlSheet.Cells(3,CCount).Value = Cmd.GetText (LINE2_PLUSTOL, 1)
                        xlSheet.Cells(4,CCount).Value = "0"
                        xlSheet.Cells(6,CCount).Value = Cmd.GetText (LINE2_DEV, 1)
                        CCount=CCount+1
                  End If
            End If
        End If
    Next Cmd

Else

'Find first Open column.
RCount=6
Found=0
Do Until Found = 1
RCount = RCount + 1
If xlSheet.Cells(RCount,1).Value = "" Then
Found=1
End If
Loop

xlSheet.Cells(RCount,1).Value = Date() & " " & Time()
xlSheet.Cells(RCount,2).Value= "Inspector Name"

'Fill In measured data
CCount = 3
    For Each Cmd In Cmds
        'Eliminate DATDEF's
        If Cmd.Type <> 1299 Then
            'Do Dimensions
            If Cmd.IsDimension Then
                If Cmd.Type = DIMENSION_START_LOCATION Or Cmd.Type = DIMENSION_TRUE_START_POSITION Then
                    Set DcmdID = Cmd.DimensionCommand
                      DimID = DcmdID.ID
                      ReportDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                End If
                If Cmd.Type <> DIMENSION_START_LOCATION And Cmd.Type <> DIMENSION_END_LOCATION And _
                    Cmd.Type <> DIMENSION_TRUE_START_POSITION And Cmd.Type <> DIMENSION_TRUE_END_POSITION Then
                    Set DCmd = Cmd.DimensionCommand
                    CheckDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                    If CheckDim <> "" Then
                            ReportDim = CheckDim
                    End If
                    If ReportDim = "BOTH" Or ReportDim = "REPORT" Then
                                'Measured Or Deviation With check For True Position
                            If DCmd.AxisLetter <> "TP" Then
                                  xlSheet.Cells(RCount,CCount).Value = DCmd.Measured
                Else
                                  xlSheet.Cells(RCount,CCount).Value = DCmd.Deviation
                End If
                                'Add Min/Max For Profile dimensions
                                If Cmd.Type = 1118 Or Cmd.Type = 1105 Then
                                  CCount=CCount+1
                                  xlSheet.Cells(RCount,CCount).Value = DCmd.Max
                                  CCount=CCount+1
                                  xlSheet.Cells(RCount,CCount).Value = DCmd.Min
                                End If
                       Ccount=Ccount+1
                    End If
                End If
            End If
            'Do GDT
            If Cmd.Type = 184 Then
                  ReportDim = Cmd.GetText ( OUTPUT_TYPE, 0)
                  If ReportDim = "BOTH" Or ReportDim = "REPORT" Then
                        xlSheet.Cells(RCount,CCount).Value = Cmd.GetText (ID, 0) & "." & "FCF"
                        xlSheet.Cells(RCount,CCount).Value = "0"
                        xlSheet.Cells(RCount,CCount).Value = Cmd.GetText (LINE2_PLUSTOL, 1)
                        xlSheet.Cells(RCount,CCount).Value = "0"
                        xlSheet.Cells(RCount,CCount).Value = Cmd.GetText (LINE2_DEV, 1)
                        CCount=CCount+1
                  End If
            End If
        End If
    Next Cmd
End If

'Save And Cleanup
Set xlSheet = Nothing
SaveName = FilePath & Part.partname & ".xls"
If ResFileExists = False Then
xlWorkBook.SaveAs SaveName
Else
xlWorkBook.Save
End If
xlWorkbook.Close
Set xlWorkbook = Nothing
xlWorkbooks.Close
Set xlWorkbooks = Nothing
xlApp.Quit
Set xlApp = Nothing

LabelEnd:

End Sub

A: Since ...
Set xlApp = CreateObject("Excel.Application")

will create a new instance of Excel, you can first check to see if an Excel instance has already been established with the following code.
On Error Resume Next
Set xlApp = GetObject("","Excel.Application")
If Err.Number <> 0 Then
    'No instance exists, create one
    Set xlApp = CreateObject("Excel.Application")
End If
Err.Clear


text:
Q: Javascript error :Object doesn't support this property or method in IE Browser I have javascript validation method, its working good in firefox, but its not working in IE browser.
I'm getting error as Object doesn't support this property or method .Please advise..
function validateChunk(s)
{
    return !!s.match(/^[a-z]+(?:\(\d+\))?$/);
}

function filterValid(v)
{
    return !v;
}

function testCases(str)
{
    var chunks = str.split(",");
    var validated = chunks.map(validateChunk);
    return (0 === validated.filter(filterValid).length);

}

jsfiddle

A: IE8 doesn't have .map() or .filter().
You  can find code to fill in for them on the MDN site:

*

*filter — here

*map — here


text:
Q: "But since" before "Now" Is the word "since" needed there before "now"? Does it change the meaning?

*

*I was worried about you but since now that I know that you are okay I'm okay too.

I made up this sentence but I am not sure whether I need to include "since" or omit it.

A: In this sentence, the word "since" can be left out without changing the meaning. This is because the words "now that" are used for the same purpose of giving a reason.
You could keep with word "since", but it sounds verbose.
On a separate point, you can also omit the second "that" in "not that I know that you are okay". It also sounds like there are too many words here, so removing it will remove the repetition without changing the meaning. This will make it sound more natural, like a native's speech.


text:
Q: SQL Complex Summation data,   ID, Value,  Exp1

201101, 1,  2
201202, 1,  3
201303, 1,  4
201101, 2,  2
201202, 2,  3
201303, 2,  4
201304, 2,  5
201305, 2,  6
201306, 2,  7
201307, 2,  8
201308, 2,  9
201309, 2,  10
201310, 2,  11
201311, 2,  12
201312, 2,  13

I have to calculate the value of Exp1 as
for ID=2. Exp1= (sum of value from 201307 to 201312)/6-(sum of value from 201301 to 201306)/6
Some IDs might not have value for all the months, some might have only one value.
Is this  possible in SQL?
for ID 2: Exp1=(13+12+11+10+9+8)/6-(7+6+5+4+3+2)/6
for ID 1: Exp1=(0+0+0+0+0+0+0+0)/6-(2+3+4+0+0+0)/6
This has to be done for all the IDS

A: select
ID,
sum(
    case
      when YRMO between 201307 and 201312 then value
      else 0
    end)/6
- sum(
    case
      when YRMO between 201301 and 201306 then value
      else 0
    end)/6 as EXP1

from TABLE
group by ID;

A: select
  id,
  sum(value) / 6 exp1
from (
  select
    id,
    case when YRMO between '201301' and '201306' then -value else value end value
  from `table`
  where YRMO between '201301' and '201312'

) q
group by id


text:
Q: Cuando pinto en un canvas, no me esta moviendo el rectángulo del contexto JS Por ahora no me da error, sólo me pinta el rectángulo pero no me completa mas nada, tenia otro código en el que si me pintaba, solo que no me rellenaba, voy a ponerlo también.
var button = document.getElementById("button");
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");
 var onMove = false;
 var z = (canvas.width - 15)/2;
 var v = (canvas.height - 15)/2;

class Rectangulo {
constructor(){
 this.x = z;
 this.y = v;
 this.h = 20;
 this.w = 20;
 this.right = this.x + this.w;
 this.left = this.y + this.h;
}

 dibujar(){
     ctx.clearRect(0,0, canvas.width, canvas.height);
     ctx.fillStyle = "black";
     ctx.fillRect(this.x, this.y , this.w, this.h);
 }
 }

 var rect = new Rectangulo();

 rect.dibujar();

 function oMousePos(canvas, evt) {
 var client = canvas.getBoundingClientRect();
 return { // devuelve un objeto
      x: Math.round(evt.clientX - client.left),
      y: Math.round(evt.clientY - client.top)
   };
  }

 canvas.addEventListener("mousedown", function(evt) {
  var mousePos = oMousePos(canvas, evt);
  if (ctx.isPointInPath(mousePos.x, mousePos.y)) {
     onMove = true;
     z = z - mousePos.x;
     v = v - mousePos.y;
     rect.dibujar();
  }
 }, false);

canvas.addEventListener("mousemove", function(evt) {
 var mousePos = oMousePos(canvas, evt);
 if (onMove) {
     z = mousePos.x + rect.x;
     v = mousePos.y + rect.y;
     rect.dibujar();
  }
}, false);

 canvas.addEventListener("mouseup", function(evt) {
 onMove = false;
 }, false);

A: El principal problema del código es que en ningún momento modificas las propiedades x e y del rectángulo, por lo que siempre se dibujan en la misma posición.
En el ejemplo que te pongo a continuación he simplificado también el cálculo de coordenadas. Tomando la posición del cursor como centro del rectángulo a dibujar.

var button = document.getElementById("button");
var canvas = document.getElementById("canvas");
// Establecer dimensiones del canvas
canvas.width=200;
canvas.height=200;
var ctx = canvas.getContext("2d");
var onMove = false;
// Posición del centro del canvas (posición inicial)
var z = canvas.width /2;
var v = canvas.height /2;

class Rectangulo {
  constructor(){
   this.x = z;
   this.y = v;
   this.h = 20;
   this.w = 20;
   this.IsPointInside = function(pos){
      let x = parseInt(this.x - this.w / 2);
      let y = parseInt(this.y - this.h / 2);
      return (pos.x >= x && pos.x < x + this.w
        && pos.y >= y && pos.y < y + this.h);
   };
  }

   dibujar(){
       ctx.clearRect(0,0, canvas.width, canvas.height);
       ctx.fillStyle = "black";
       // El rectángulo se dibuja para que el centro quede en x,y
       let x = parseInt(this.x - this.w / 2);
       let y = parseInt(this.y - this.h / 2);
       ctx.fillRect(x, y, this.w, this.h);
   }
}

var rect = new Rectangulo();

rect.dibujar();

function oMousePos(canvas, evt) {
 var client = canvas.getBoundingClientRect();
 return {
    x: Math.round(evt.clientX - client.left),
    y: Math.round(evt.clientY - client.top)
 };
}

canvas.addEventListener("mousedown", function(evt) {
  var mousePos = oMousePos(canvas, evt);
  if (rect.IsPointInside(mousePos)) {
     onMove = true;
     // Modificamos la posición del rectángulo y dibujamos
     rect.x = mousePos.x;
     rect.y = mousePos.y;
     rect.dibujar();
   }
 }, false);

canvas.addEventListener("mousemove", function(evt) {
 var mousePos = oMousePos(canvas, evt);
 if (onMove) {
   // Modificamos la posición del rectángulo y dibujamos
   rect.x = mousePos.x;
   rect.y = mousePos.y;
   rect.dibujar();
  }
}, false);

canvas.addEventListener("mouseup", function(evt) {
    onMove = false;
  }, false);
#canvas{
  width: 200px;
  height:200px;
  border: solid 1px black;
}
<canvas id="canvas"></canvas>


text:
Q: docker build cannot find file secret file outside home directory I'm building a docker image as follows:
TEMP_FILE="/home/username/any/directory/temp"
touch $TEMP_FILE

<secrets> > $TEMP_FILE

export DOCKER_BUILDKIT=1
pushd $PROJECT_ROOT
  docker build -t $DOCKER_IMAGE_NAME \
               --secret id=netrc,src=$TEMP_FILE \
               --build-arg=<...> \
               -f Dockerfile .
  rm $TEMP_FILE

Currently this works.
I'd now like to use $(mktemp) to create the TEMP_FILE in the /tmp directory. However, when I point TEMP_FILE outside of /home, I get the following error:
could not parse secrets: [id=netrc,src=/tmp/temp-file-name]: failed to stat /tmp/temp-file-name: stat /tmp/temp-file-name: no such file or directory

The script itself has no issue, I can easily find and view the temporary file for example with cat $TEMP_FILE.
How do I give docker build access to /tmp?


text:
Q: How To Configure SonarQube GitHub Plugin With Jenkins We are very interested in leveraging the GitHub integration on my team:
http://docs.sonarqube.org/display/PLUG/GitHub+Plugin
We use Jenkins as our CI Server and already have the GitHub Pull Request Builder working there.  We have also been using SonarQube for analysis but have not had much luck with the preview or incremental modes and GitHub integration.  Current versions are SonarQube 5.1.1 and GitHub Plugin version 1.0.1.
We have the plug-in installed on SonarQube and have our GitHub Enterprise API configured.  We have attempted using the SonarQube Runner in Jenkins and Maven to get this to work following the travis.sh script as a guide:
https://github.com/SonarSource/sonarqube/blob/master/travis.sh
We see the Sonar integration show up on GitHub, but it is always successful (we are working with large, legacy code bases and expect to see a lot of output).
The thing that is consistent between our javascript and java analysis is that we don't seem to be getting any files indexed and the GitHub Plugin InputFile Cache sensor is used instead of Javascript or Java sensors we are used to seeing during a full analysis.
00:01:57.532 13:12:31.109 INFO  - 0 files indexed
00:01:57.533 13:12:31.110 INFO  - 25784 files ignored because of inclusion/exclusion patterns
00:01:57.535 13:12:31.112 INFO  - Quality profile for js: Sonar way
00:01:57.758 13:12:31.334 DEBUG - 'SCM Sensor' skipped in preview mode
00:01:57.758 13:12:31.335 DEBUG - 'CPD Sensor' skipped in preview mode
00:01:57.759 13:12:31.336 DEBUG - Sensors : Lines Sensor (wrapped) -> GitHub Plugin InputFile Cache
00:01:57.759 13:12:31.336 INFO  - Sensor Lines Sensor (wrapped)
00:01:57.759 13:12:31.336 INFO  - Sensor Lines Sensor (wrapped) (done) | time=0ms
00:01:57.759 13:12:31.336 INFO  - Sensor GitHub Plugin InputFile Cache
00:01:57.759 13:12:31.336 INFO  - Sensor GitHub Plugin InputFile Cache (done) | time=0ms
00:01:57.759 13:12:31.336 DEBUG - No previous analysis, skipping issue tracking
00:01:57.763 13:12:31.340 INFO  -
00:01:57.763
00:01:57.763 -------------  Issues Report  -------------
00:01:57.763
00:01:57.763   No file analyzed
00:01:57.763
00:01:57.763 -------------------------------------------
00:01:57.763
00:01:57.763
00:01:57.763 13:12:31.340 INFO  - Export issues to /data/jenkins/workspace/mygea-mygeaviation-pullrequests/.sonar/sonar-report.json
00:01:57.766 13:12:31.343 INFO  - ANALYSIS SUCCESSFUL
00:01:57.767 13:12:31.344 DEBUG - Post-jobs : GitHub Pull Request Issue Publisher
00:01:57.767 13:12:31.344 INFO  - Executing post-job class org.sonar.plugins.github.PullRequestIssuePostJob

Are we missing something simple?
Analysis properties are as follows:
sonar.projectKey=mygea-ux-pullrequests
sonar.projectName=mygea-ux-pullrequests
sonar.projectVersion=1.0.0
sonar.sourceEncoding=UTF-8
sonar.language=js
sonar.sources=./
sonar.verbose=true
sonar.exclusions=static/ge_ux/**/*, node_modules/**/*, custom-login/custom-login-cfm/iids/**/*, custom-login/custom-login-honda/iids/**/*, custom-login/custom-login-ge/iids/**/*, static/ge.com.2013/components/**/*, static/ge.com.2013/widgets/**/*.min.js, testFiles/**/*, coverage/**/*, gulpfile.js, test-tmp/**/*, extend.js, index.js, static/ge.com.2013/js/**/*.min.js
sonar.analysis.mode=preview
sonar.issuesReport.console.enable=true
sonar.forceUpdate=true
sonar.github.pullRequest=$ghprbPullId
sonar.github.repository=mygea/mygeaviation
sonar.github.login=*****
sonar.github.oauth=*****
sonar.github.endpoint=*****

Any assistance on this would be much appreciated!  This is an awesome plug-in and we think it will really help us get our technical debt under control.
Josh

A: The answer to this was provided in the Google Group here:
https://groups.google.com/forum/#!topic/sonarqube/eoTmLMyDrtA
The analysis is automatically filtered based on the files in the pull request.  We were testing with pull requests that only had changes in pom.xml and readme files.  Once a functional change was introduced, everything lit up on the GitHub Pull Request view as expected.
User error!  Working as designed.
Thanks to Julien for pushing us in the right direction.


text:
Q: How to redirect whole domain with subdomains to another domain I need to redirect:
anything.domain.com and domain.com/anything
to
domain2.com

I've tried this .htaccess code with wildcard:
RewriteEngine On
RewriteRule ^(.*)$ http://domena2.com/$1 [R=301,L]

but it still redirects domain1.com/123 to domain2.com/123 and not to domain2.com and my subdomains are not redirected at all.

A:
i've bought an expired domain that have a lot of traffic i know that it have at least one subdomain but maybe more , that's why id like redirect anything to my domain without knowing all subdomains

If the subdomains are not actually configured then that's your problem.
You would need to configure all the subdomains in DNS (or perhaps create a wildcard subdomain), otherwise they won't even resolve (which is presumably the error you are getting in the browser?). If they don't resolve then they don't reach your site and the code in .htaccess is not even processed.
Also, if you wish to redirect to the home page then remove the $1 backreference (as mentioned in my comment). However, redirecting everything to the home page is not necessarily good for SEO. Google is likely to see these links as a soft-404 anyway and will soon be dropped from the SERPs.
Try the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain2\.com
RewriteRule ^ http://domain2.com/ [R=302,L]

This redirects all requests that are not for domain2.com to the root of domain2.com.
Make sure your browser cache is cleared before testing, as 301s are cached hard by the browser. For this reason, change the above 302 (temporary) to 301 (permanent) only when you are sure it's working OK.

i get this code from someone on another forum

It's important to understand what you are copy/pasting into your .htaccess file, as it can very quickly break your site.


text:
Q: Proteus Ares Layout - how do I reduce a 4 layer board to 2 layers? I am working on a 4 layer board and I want to eliminate the 2 inner layers. Problem is that the autorouter never seems to get the message.
I have set layer pairs as top copper and all the others as bottom
In "Set Layers Usage" I have unticked everything
What have I missed?


text:
Q: In SUMIFS function I am getting #VALUE error
For the top table above, I am using the following SUMIFS function:
=SUMIFS($C$3:$G$23,$A$3:$A$23,"=Cinthol",$B$3:$B$23,"=Bangalore")

to try to get the results in the output format shown, based on two criteria {1. Product and 2. City}.  But I am getting #VALUE! error.
Am I doing something wrong?

A: You have two issues. "each criteria_range argument must contain the same number of rows and columns as the sum_range argument" and your criteria are =Cinthol and =Bangalore.
This may directly be addressed quite easily by repeating the SUMIFS function for each of ColumnsC:G individually (and you might then sum the results).
An alternative would be to add each row up in your data set and apply a PivotTable.

A: If you use SUMPRODUCT you can get the required result without adding any columns, e.g.
=SUMPRODUCT($C$3:$G$23*($A$3:$A$23="Cinthol")*($B$3:$B$23="Bangalore"))
or with cell references to copy down a table
=SUMPRODUCT($C$3:$G$23*($A$3:$A$23=J2)*($B$3:$B$23=K2))
That assumes that there are no text values (or "formula blanks" like "") in the range C3:G23. If there are then you can still make it work like this:
=SUMPRODUCT($C$3:$G$23,ISNUMBER($C$3:$G$23)*($A$3:$A$23=J2)*($B$3:$B$23=K2))

A: There is a solution:
First sum_range must be a column so instead of
=SUMIFS($C$3:$**G**$23,$A$3:$A$23,"=Cinthol",$B$3:$B$23,"=Bangalore")

it should be
=SUMIFS($C$3:$**C**$23,$A$3:$A$23,"=Cinthol",$B$3:$B$23,"=Bangalore")

to make it work.
If it's not enough you can use =SUM(SUMIFS(), SUMIFS())


text:
Q: EJBTransactionRolledbackException occasionally occurs on @Asynchronous Function I am using Java 1.6.0_23 and Glassfish 3.1.1.  I have two Singleton EJBs.  One is using the TimerService to fire the @Timeout function. During the @Timeout, an @Asynchronous function in called in the other Singleton EJB.  It works 95% of the time without any errors.  But the other 5% of the time when the @Asynchronous function is called, I get the following error with no evidence that it even started the @Asynchronous function.  No other error details are logged.
Any ideas?
PS: I tried increasing the max number of EJBs in Glassfish from 32 to 64.  No change.

java.util.concurrent.ExecutionException: javax.ejb.EJBTransactionRolledbackException
        at com.sun.ejb.containers.EjbAsyncTask.call(EjbAsyncTask.java:132) ~[ejb-container.jar:3.1.1]
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) ~[na:1.6.0_23]
        at java.util.concurrent.FutureTask.run(FutureTask.java:138) ~[na:1.6.0_23]
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) ~[na:1.6.0_23]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) ~[na:1.6.0_23]
        at java.lang.Thread.run(Thread.java:662) ~[na:1.6.0_23]
Caused by: javax.ejb.EJBTransactionRolledbackException: null
        at com.sun.ejb.containers.BaseContainer.mapLocal3xException(BaseContainer.java:2305) ~[ejb-container.jar:3.1.1]
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2088) ~[ejb-container.jar:3.1.1]
        at com.sun.ejb.containers.EjbAsyncTask.call(EjbAsyncTask.java:114) ~[ejb-container.jar:3.1.1]
        ... 5 common frames omitted
Caused by: javax.ejb.TransactionRolledbackLocalException: Client's transaction aborted
        at com.sun.ejb.containers.BaseContainer.useClientTx(BaseContainer.java:4699) ~[ejb-container.jar:3.1.1]
        at com.sun.ejb.containers.BaseContainer.preInvokeTx(BaseContainer.java:4577) ~[ejb-container.jar:3.1.1]
        at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1910) ~[ejb-container.jar:3.1.1]
        at com.sun.ejb.containers.EjbAsyncTask.call(EjbAsyncTask.java:99) ~[ejb-container.jar:3.1.1]
        ... 5 common frames omitted

A: You'll have to look for other errors that happened before this one (maybe swallowed exceptions, since you said there are no other errors). EJBTransactionRolledbackException occurs if the current trx has been marked for a rollback, and you're still doing stuff on the DB.

A: Happened to me as well.
Seems the problem is not a coding problem, but server resources.
I increased the http thread pool size
It was 5 max for me and I changed it to 10
Seems to resolved the problem.
Also some notes on this error here:
http://pcjuzeren.blogspot.co.il/2008/12/clients-transaction-aborted.html


text:
Q: How to store a Geo Point in Backand I want to have a location associated with all of the users of my app and to be able to filter what users see based on how close they are to each other. What is the recommended approach for this? I was disappointed to see that Backand does not seem to provide a "geopoint" data type out of the box.

A: Just discovered via the Backand docs that Backand does indeed provide this out of the box. The issue was I was trying to select the data type from the options offered in the visual model view which seems to be limited.
If I just edit directly in the actual model json view, I am able to specify the "point" type and that is exactly what I am looking for.


text:
Q: angular js can not take value from select box <!DOCTYPE html>

    <button ng-click="click()">
      Button click
    </button>

      name=
      <input type="text" ng-model="caner.name">

 surnanme=
      <input type="text" ng-model="caner.surname">

 age

        <select ng-model="caner.age"
       ng-options="  person.age for person in peole" > </select>

 Welcome Message: {{ caner.name + " " + caner.surname+" "+caner.age}}

can be seen here
when i select 3 for example, output becomes
Welcome Message: caner aydin [object Object]
i get the value here
  <select ng-model="caner.age"

   ng-options="  person.age for person in peole" >

in contrller
 $scope.peole = [{
        age: 1,
        name: 'Bob'
      }, {
        age: 2,
        name: 'Alice'
      }, {
        age: 3,
        name: 'Steve'
      }];

it should give 3 , not object object output. i put to caner.age to give output.

A: Change your drop-down tag to the following.
<select ng-model="caner.age"

       ng-options="  person.age as person.age for person in peole" >

    </select>

A: The  will bind the object to your ng-model.
Meaning that caner.age will be
{
    age: 3,
    name: 'Steve'
}

If you use
 Welcome Message: {{ caner.name + " " + caner.surname+" "+caner.age.age}}

it should work. I hope this will guide you to on how to refactor your code.

A: Change caner.age.age instead of caner.age

var app = angular.module('canerApp', []);

    app.controller('canerCtrl', function($scope) {

      $scope.caner = {

        name: "caner",
        surname: "aydin",

age: "22",
      };

      $scope.peole = [{
        age: 1,
        name: 'Bob'
      }, {
        age: 2,
        name: 'Alice'
      }, {
        age: 3,
        name: 'Steve'
      }];

      $scope.isClicked = true;

      $scope.click = function() {
        $scope.isClicked = !$scope.isClicked;
      };
    });
<!DOCTYPE html>

    <button ng-click="click()">
      Button click
    </button>

      name=
      <input type="text" ng-model="caner.name">

 surnanme=
      <input type="text" ng-model="caner.surname">

 age

        <select ng-model="caner.age"

       ng-options="person.age for person in peole" >

        </select>

 Welcome Message: {{ caner.name + " " + caner.surname+" "+caner.age.age}}

A: Your problem:
You are binding the object person to the ng-model caner.age with your ng-options :
<select ng-model="caner.age"
   ng-options="person.age for person in peole" >
</select>

That's why you are getting [Object][Object] in your angular expression {{caner.age}}
Solution:
While changing it to {{caner.age.age}} is a valid solution, you might want to consider correcting your ng-model binding to bind the actual age value instead of the person object like this :
<select ng-model="caner.age"
   ng-options="person.age as person.age for person in peole" >
</select>

For why it has to be written this way, see for documentations : ng-options documentations


text:
Q: Connection Timeout on Windows Share (Network) I have set up a shared drive on my office network, the shared drive is on a Windows 7 PC and I have connected to it on my Ubuntu 16.04 using the Network (Samba Share). I am able to use the share drive but after using it for some time, I am no longer able to access it, I keep getting an error message:

The Share folder works fine after restart,
How can I keep my connection from timing out?

A: Had the same problem on Ubuntu 16.04.
Works for me after doing this quick fix:

*

*Edit the samba conf file: sudo gedit /etc/samba/smb.conf

*Then add this line in the [global] section client max protocol = SMB3


text:
Q: clone a job using boto I click on "clone job" button, change an environment variable and submit the second job. Now both the jobs are running without any problem.

But I have a python list of a few thousand variables those needs to be supplied to this job in a loop. In other words, the job needs to be "cloned" 1000 times. I need to do it using boto for obvious reasons. But what is the best way to clone jobs using boto? The tutorials available on the net shows the entire process of creating job.

A: "containerOverrides" parameter is the equivalent of "clone job" function of web interface. The submit job method will look like this...
client.submit_job(
    jobName=JOB_NAME,
    jobQueue=JOB_QUEUE,
    jobDefinition=JOB_DEFINITION,
    containerOverrides={"environment": [{"name": "senderid", "value": "XXXX"}]},
)

The full code will look like this:
import boto3
session = boto3.Session(
    aws_access_key_id="xxx",
    aws_secret_access_key="xxxx",
    region_name="us-east-1",
)
client = session.client("batch")
JOB_NAME = "nlptensorboto1"
JOB_QUEUE = "arn:aws:batch:us-east-1:302xxx:job-queue/nlpmljob"
JOB_DEFINITION = "arn:aws:batch:us-east-1:302xxx:job-definition/nlptensor:1"

client.submit_job(
    jobName=JOB_NAME,
    jobQueue=JOB_QUEUE,
    jobDefinition=JOB_DEFINITION,
    containerOverrides={"environment": [{"name": "senderid", "value": "xxx"}]},
)


text:
Q: Simple pagination in datatable using ajax without sending total count from server I'm using DataTables 1.10.5. My table uses server side processing via ajax.
$('#' + id).dataTable({
  processing: true,
  serverSide: true,
  ajax: 'server-side-php-script-url',
  "pagingType": "simple_incremental_bootstrap"
});

Everything will work properly if I send 'recordsTotal' in the server response. But I don't want to count the total entries because of performance issues. So I tried to use the pagination plugin simple_incremental_bootstrap. However it is not working as expected. The next button always return the first page itself. If I give 'recordsTotal' in server response this plugin will work properly. I found out that If we don't give 'recordsTotal', the 'start' param sent by datatable to server side script is always 0. So my server side script will always return the first page.
According to this discussion, server side processing without calculating total count is not possible because "DataTables uses the record count that is passed back to it to deal with the paging controls". The suggested workaround is "So the display records are needed, but it would be possible to just pass back a static number (like 1'000'000 or whatever) which would make DataTables think there are a million rows. You could hide the information element if this information is totally bogus!"
I wonder if anybody have a solution for this. Basically I want to have a simple pagination in my datatable with ajax without sending total count from server.

A: A workaround worth to try..
If we don't send recordsTotal from server, the pagination won't work properly. If we send a high static number as recordsTotal, table will show an active Next button even if there is no data in next page.
So I ended up in a solution which utilizes two parameters received in ajax script - 'start' and 'length'.
If rows in current page is less than 'limit' there is no data in next page. So total count will be 'start' + 'current page count'. This will disable Next button in the last page.
If rows in current page is equal to or greater than 'limit' there is more data in next pages. Then I will fetch data for next page. If there is at least one row in next page, send recordsTotal something larger than 'start + limit'. This will display an active Next button.
Sample code:
$limit = require_param('length');
$offset = require_param('start');
$current_page_data = fn_to_calculate_data($limit, $offset); // in my case, mysqli result.
$data = "fetch data $current_page_data";
$current_page_count = mysqli_num_rows($current_page_data);
if($current_page_count >= $limit) {
    $next_page_data  = fn_to_calculate_data($limit, $offset+$limit);
    $next_page_count = mysqli_num_rows($next_page_data);
    if($next_page_count >= $limit) {
        // Not the exact count, just indicate that we have more pages to show.
        $total_count = $offset+(2*$limit);
    } else {
        $total_count = $offset+$limit+$next_page_count;
    }
} else {
    $total_count = $offset+$current_page_count;
}
$filtered_count = $total_count;

send_json(array(
    'draw' => $params['draw'],
    'recordsTotal' => $total_count,
    'recordsFiltered' => $filtered_count,
    'data' => $data)
);

However this solution adds some load to server as it additionally calculate count of rows in next page. Anyway it is a small load as compared to the calculation total rows.
We need to hide the count information from table footer and use simple pagination.
  dtOptions = {};
  dtOptions.pagingType = "simple";
  dtOptions.fnDrawCallback = function() {
    $('#'+table_id+"_info").hide();
  };
  $('#' + table_id).dataTable(dtOptions);


text:
Q: Multi-threading with TPL - Access Internal Class Properties I am using the TPL library to parallelize a 2D grid operation.  I have extracted a simple example from my actual code to illustrate what I am doing.  I am getting the desired results I want and my computation times are sped up by the number of processors on my laptop (12).
I would love to get some advice or opinions on my code as far as how my properties are declared.  Again, it works as expected, but wonder if the design could be better.  Thank you in advance.
My simplified code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Gridding
{

    public abstract class Base
    {
        /// <summary>
        /// Values representing the mesh values where each node in the gridis assigned som value.
        /// </summary>
        public float[,] Values { get; set; }
        public abstract void Compute();
    }

    public class Derived : Base
    {

        /// <summary>
        /// Make the mesh readonly.  Is this necessary?
        /// </summary>
        readonly Mesh MyMesh;

        Derived(Mesh mesh)
        {
            MyMesh = mesh;
        }

        public override void Compute()
        {
            Values = new float[MyMesh.NX, MyMesh.NY];

            double[] xn = MyMesh.GetXNodes();
            double[] yn = MyMesh.GetYNodes();

            /// Paralellize the threads along the columns of the grid using the Task Paralllel Library (TPL).
            Parallel.For(0, MyMesh.NX, i =>
            {
                Run(i, xn, yn);
            });
        }

        private void Run(int i, double[] xn, double[] yn)
        {
            /// Some long operation that parallelizes along the columns of a mesh/grid
            double x = xn[i];
            for (int j = 0; j < MyMesh.NY; j++)
            {

                /// Again, longer operation here
                double y = yn[j];

                double someValue = Math.Sqrt(x * y);
                Values[i, j] = (float)someValue;
            }
        }

        static void Main(string[] args)
        {
            int nx = 100;
            int ny = 120;
            double x0 = 0.0;
            double y0 = 0.0;
            double width = 100;
            double height = 120;

            Mesh mesh = new Mesh(nx, ny, x0, y0, width, height);

            Base tplTest = new Derived(mesh);
            tplTest.Compute();

            float[,] values = tplTest.Values;

            Console.Read();

        }

        /// <summary>
        /// A simple North-South oriented grid.
        /// </summary>
        class Mesh
        {
            public int NX { get; } = 100;
            public int NY { get; set; } = 150;
            public double XOrigin { get; set; } = 0.0;
            public double YOrigin { get; set; } = 0.0;
            public double Width { get; set; } = 100.0;
            public double Height { get; set; } = 150.0;
            public double DX { get; }
            public double DY { get; }

            public Mesh(int nx, int ny, double xOrigin, double yOrigin, double width, double height)
            {
                NX = nx;
                NY = ny;
                XOrigin = xOrigin;
                YOrigin = yOrigin;
                Width = width;
                Height = height;
                DX = Width / (NX - 1);
                DY = Height / (NY - 1);
            }

            public double[] GetYNodes()
            {
                double[] yNodeLocs = new double[NY];
                for (int i = 0; i < NY; i++)
                {
                    yNodeLocs[i] = YOrigin + i * DY;
                }
                return yNodeLocs;
            }

            public double[] GetXNodes()
            {
                double[] xNodeLocs = new double[NX];
                for (int i = 0; i < NX; i++)
                {
                    xNodeLocs[i] = XOrigin + i * DX;
                }
                return xNodeLocs;
            }
        }
    }
}

A: With only 100 to 150 array elements, parallelism setup overhead would offset the gains. You could cache the result  of GetXNodes() and GetYNodes() and invalidate the cached values when XOrigin, NX, YOrigin or  NY are modified.


text:
Q: Validation not working for custom usercontrol combobox I am creating a Usercontrol which will contain a dropdown and on opening of dropdown, I want to have an Add button. Everything is working fine but validation is not working for Usercontrol controls.
Here is my xaml code:
<UserControl x:Class="Splendid.Inventory.Presentation.Controls.CustomComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Splendid.Inventory.Presentation.Controls"
             xmlns:conv="clr-namespace:Splendid.Inventory.Presentation.Converters"
             mc:Ignorable="d" x:Name="ucCombo" Validation.ErrorTemplate="{x:Null}"
             d:DesignHeight="30" d:DesignWidth="100">
    <UserControl.Resources>
        <KeyBinding x:Key="addNewBinding" Key="N" Modifiers="Shift" Command="{Binding AddNewCommand}"></KeyBinding>
        <conv:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"></conv:BooleanToVisibilityConverter>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">
        <ComboBox x:Name="hdnCombo" MaxDropDownHeight="200" Visibility="Visible" Style="{StaticResource DialogCombobox}"
                         DisplayMemberPath="{Binding DisplayMemberPath, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                         SelectedValuePath="{Binding SelectedValuePath, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                         SelectedValue="{Binding SelectedValue,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
                         ItemsSource="{Binding ItemSource, UpdateSourceTrigger=PropertyChanged}"
                         GotFocus="hdnCombo_GotFocus" LostFocus="hdnCombo_LostFocus">
        </ComboBox>

        <Canvas Visibility="{Binding IsDropDownOpen, ElementName=hdnCombo, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BooleanToVisibilityConverter}}">
            <Grid Canvas.Top="200">
            <Button HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="btnTesst"
                    MouseEnter="btnTesst_MouseEnter">Add New (Shift + N)</Button>
            </Grid>
        </Canvas>
    </Grid>
</UserControl>

I tried usercontrol with string property binding and textbox and I am able to get errors.
Here is my xaml.cs code:
public partial class CustomComboBox : UserControl, INotifyPropertyChanged, IDataErrorInfo
    {
        public ICommand AddNewCommand { get; set; }
        public CustomComboBox()
        {
            InitializeComponent();
            //this.DataContext = this;
            LayoutRoot.DataContext = this;
            AddNewCommand = new DelegateCommand(OnAddNewCommand);
        }

        private void OnAddNewCommand()
        {
            MessageBox.Show("Add New form");
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public IEnumerable ItemSource
        {
            get { return (IEnumerable)GetValue(ItemSourceProperty); }
            set
            {
                SetValue(ItemSourceProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for ListItemSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemSourceProperty =
            DependencyProperty.Register("ItemSource", typeof(IEnumerable), typeof(CustomComboBox));

        public string AddItemControl
        {
            get { return (string)GetValue(AddItemControlProperty); }
            set { SetValue(AddItemControlProperty, value); }
        }

        // Using a DependencyProperty as the backing store for AddItemControl.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AddItemControlProperty =
            DependencyProperty.Register("AddItemControl", typeof(string), typeof(CustomComboBox), new PropertyMetadata(string.Empty));

        public string DisplayMemberPath
        {
            get { return (string)GetValue(DisplayMemberNameProperty); }
            set { SetValue(DisplayMemberNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DisplayMemberPath.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DisplayMemberNameProperty =
            DependencyProperty.Register("DisplayMemberPath", typeof(string), typeof(CustomComboBox), new PropertyMetadata(string.Empty));

        public string SelectedValuePath
        {
            get { return (string)GetValue(SelectedValueNameProperty); }
            set { SetValue(SelectedValueNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedValuePath.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedValueNameProperty =
            DependencyProperty.Register("SelectedValuePath", typeof(string), typeof(CustomComboBox), new PropertyMetadata(string.Empty));

        public SelectListModel SelectedItem
        {
            get { return (SelectListModel)GetValue(SelectedItemProperty); }
            set
            {
                SetValue(SelectedItemProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(SelectListModel), typeof(CustomComboBox));

        public object SelectedValue
        {
            get { return GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedValue.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register("SelectedValue", typeof(object), typeof(CustomComboBox));

        public int ItemUnitId
        {
            get { return (int)GetValue(ItemUnitIdProperty); }
            set { SetValue(ItemUnitIdProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ItemName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemUnitIdProperty =
            DependencyProperty.Register("ItemUnitId", typeof(string), typeof(CustomComboBox), new FrameworkPropertyMetadata(string.Empty,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);

        public string Error
        {
            get
            {

                return "Item type is required";
                //throw new NotImplementedException();
            }
        }

        public string this[string columnName]
        {
            get
            {

                // use a specific validation or ask for UserControl Validation Error
                return Validation.GetHasError(this) ? Convert.ToString(Validation.GetErrors(this).FirstOrDefault().ErrorContent) : null;
            }
        }

        private void btnTesst_MouseEnter(object sender, MouseEventArgs e)
        {
            OnAddNewCommand();
        }

        bool isFocused = false;
        private void hdnCombo_GotFocus(object sender, RoutedEventArgs e)
        {
            isFocused = true;
        }

        private void hdnCombo_LostFocus(object sender, RoutedEventArgs e)
        {
            isFocused = false;
        }
    }

Is there any missing piece?

A: Resolved the issue by adding validation template to User control. Here are the changes made to UserControl:
<UserControl x:Class="Splendid.Inventory.Presentation.Controls.CustomComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Splendid.Inventory.Presentation.Controls"
             xmlns:conv="clr-namespace:Splendid.Inventory.Presentation.Converters"
             mc:Ignorable="d" x:Name="ucCombo"
             Validation.ErrorTemplate="{StaticResource ValidationErrorTemplate}"
             d:DesignHeight="30" d:DesignWidth="100">
    <UserControl.Resources>
        <KeyBinding x:Key="addNewBinding" Key="N" Modifiers="Shift" Command="{Binding AddNewCommand}"></KeyBinding>
        <conv:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"></conv:BooleanToVisibilityConverter>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">
        <ComboBox x:Name="hdnCombo" MaxDropDownHeight="200" Visibility="Visible" Style="{StaticResource DialogCombobox}"
                         DisplayMemberPath="{Binding DisplayMemberPath, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                         SelectedValuePath="{Binding SelectedValuePath, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                         SelectedValue="{Binding SelectedValue,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
                         ItemsSource="{Binding ItemSource, UpdateSourceTrigger=PropertyChanged}"
                         GotFocus="hdnCombo_GotFocus" LostFocus="hdnCombo_LostFocus">
        </ComboBox>

        <Canvas Visibility="{Binding IsDropDownOpen, ElementName=hdnCombo, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BooleanToVisibilityConverter}}">
            <Grid Canvas.Top="200">
            <Button HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="btnTesst"
                    MouseEnter="btnTesst_MouseEnter">Add New (Shift + N)</Button>
            </Grid>
        </Canvas>
    </Grid>
</UserControl>


text:
Q: Unzipping a password protected file in Node.js Is there a library that I can use to unzip a password protected file (Site makes me put a password on the file when downloading it)? There are a ton of libraries to unzip normal files, but none that I can find that will do it with a password.
Here I found some helpful starters. But I would rather not resort to using child_process and using built in unix unzipping functionality, but that may be my last resort. I would even be up to preforming my own manipulation on the encrypted code, but I'm unable to even find out how to determine the encryption type (it seems to just be very standard, since i can do it in the terminal).
Again I would rather not do this, but I'm afraid it is my only option so I have tried the following:
var fs = require('fs')
, unzip = require('unzip')
, spawn = require('child_process').spawn
, expand = function(filepath, cb) {
     var self = this
     , unzipStream = fs.createReadStream(filepath).pipe(unzip.Parse())
     , xmlData = '';

     unzipStream.on('entry', function (entry) {
            var filename = entry.path;
           // first zip contains files and one password protected zipfile.
           // Here I can just do pipe(unzip.Parse()) again, but then i just get a giant encoded string that I don't know how to handle, so i tried other things bellow.
           if(filename.match(/\.zip$/)){
                 entry.on('data', function (data) {
                     var funzip = spawn('funzip','-P','ThisIsATestPsswd','-');
                     var newFile = funzip.stdin.write(data);

            // more closing code...

Then I sort of lost what to do. I tried writing newFile to a file, but that just said [object].
Then I tried just doing something simpler by changing the last 3 lines to
   fs.writeFile('./tmp/this.zip', data, 'binary');
   var newFile = spawn('unzip','-P','ThisIsATest','./tmp/this.zip');
   console.log('Data: ' + data);

But data isn't anything useful just [object Object] again. I can't figure out what to do next to get this new unzipped file into either a working file, or a readable string.
I am super new to Node and all the async/listeners being fired by other processes is a little confusing still, so I'm sorry if any of this makes no sense. Thanks so much for the help!
EDIT:

I have now added the following code:
var fs = require('fs')
  , unzip = require('unzip')
  , spawn = require('child_process').spawn
  , expand = function(filepath, cb) {
    var self = this
    , unzipStream = fs.createReadStream(filepath)
      .pipe(unzip.Parse())
    , xmlData = '';

      unzipStream.on('entry', function (entry) {
        var filename = entry.path
            , type = entry.type // 'Directory' or 'File'
            , size = entry.size;
        console.log('Filename: ' + filename);

        if(filename.match(/\.zip$/)){
            entry.on('data', function (data) {
              fs.writeFile('./lib/mocks/tmp/this.zip', data, 'binary');
              var newFile = spawn('unzip','-P','ThisIsATestPassword', '-','../tmp/this.zip');
              newFile.stdout.on('data', function(data){
                 fs.writeFile('./lib/mocks/tmp/that.txt', data); //This needs to be something different
                    //The zip file contains an archive of files, so one file name shouldn't work
              });

           });
          } else { //Not a zip so handle differently }
       )};
    };

This seems to be really close to what I need, but when the file is written all it has is the options list for unzip:
UnZip 5.52 of 28 February 2005, by Info-ZIP.  Maintained by C. Spieler.  Send
bug reports using http://www.info-zip.org/zip-bug.html; see README for details.

Usage: unzip [-Z] [-opts[modifiers]] file[.zip] [list] [-x xlist] [-d exdir]
  Default action is to extract files in list, except those in xlist, to exdir;
  file[.zip] may be a wildcard.  -Z => ZipInfo mode ("unzip -Z" for usage).

  -p  extract files to pipe, no messages     -l  list files (short format)
  -f  freshen existing files, create none    -t  test compressed archive data
  -u  update files, create if necessary      -z  display archive comment
  -x  exclude files that follow (in xlist)   -d  extract files into exdir

modifiers:                                   -q  quiet mode (-qq => quieter)
  -n  never overwrite existing files         -a  auto-convert any text files
  -o  overwrite files WITHOUT prompting      -aa treat ALL files as text
  -j  junk paths (do not make directories)   -v  be verbose/print version info
  -C  match filenames case-insensitively     -L  make (some) names lowercase
  -X  restore UID/GID info                   -V  retain VMS version numbers
  -K  keep setuid/setgid/tacky permissions   -M  pipe through "more" pager
Examples (see unzip.txt for more info):
  unzip data1 -x joe   => extract all files except joe from zipfile data1.zip
  unzip -p foo | more  => send contents of foo.zip via pipe into program more
  unzip -fo foo ReadMe => quietly replace existing ReadMe if archive file newer

I'm not sure if the input was wrong since this looks like the error for unzip. Or if I am just writing the wrong content.  I would have thought that it would just preform like it does normally from the console--just adding all files as they are extracted to the directory. while I would love to be able to just read all content from a buffer, the - option doesn't seem to do that and so I would settle for the files just being added to the directory. Thanks so much to anyone with any suggestions!
Edit 2

I was able to get this working, not the best way probably but it works at least using this line:
var newFile = spawn('unzip', [ '-P','ThisIsATestPassword', '-d','./lib/tmp/foo','./lib/mocks/tmp/this.zip' ])

This will just unzip all the files into the directory and then I was able to read them from there. My mistake was that the second parameter has to be an array.

A: I was able to get this working, not the best way probably but it works at least using this line:
var newFile = spawn('unzip', [ '-P','ThisIsATestPassword', '-d','./lib/tmp/foo','./lib/mocks/tmp/this.zip' ])

This will just unzip all the files into the directory and then I was able to read them from there. My mistake was that the second parameter has to be an array.

A: I found the solution using unzipper.
Pasting the code from this blog
const unzipper = require('unzipper');

(async () => {
  try {
    const directory = await unzipper.Open.file('path/to/your.zip');
    const extracted = await directory.files[0].buffer('PASSWORD');
    console.log(extracted.toString()); // This will print the file content
  } catch(e) {
    console.log(e);
  }
})();

As @codyschaaf mentioned in his answer, we can use spawn or some other child_process but they're not always OS agnostic. So if I'm using this in production, I'll always go for an OS-agnostic solution if it exists.
Hope this helps someone.

A: I tried the spawn approach (the spawnSync actually worked better).
const result = spawnSync('unzip', ['-P', 'password', '-d', './files', './files/file.zip'], { encoding: 'utf-8' })

Nonetheless, this approach did not fully work as it introduced a new error:
Archive:  test.zip
   skipping: file.png                need PK compat. v5.1 (can do v4.6)

Eventually, I ended up going with 7zip approach:
import sevenBin from '7zip-bin'
import seven from 'node-7z'

const zipPath = './files/file.zip'
const downloadDirectory = './files'

const zipStream = seven.extractFull(zipPath, downloadDirectory, {
  password: 'password',
  $bin: sevenBin.path7za
})

zipStream.on('end', () => {
  // Do stuff with unzipped content
})

A: To unzip password protected zipped multilevel folder try the following code.
I am using the unzipper npm.
unzipper.Open.file(contentPath + filename).then((mainDirectory) => {
return new Promise((resolve, reject) => {
  let maindirPath = mainDirectory.files[0].path;
  let patharray = maindirPath.split("/")
  let temppath = destinationPath+patharray[0];
   fs.mkdirSync(temppath);//create parent Directory

    // Iterate through every file inside there (this includes directories and files in subdirectories)
    for (let i = 0; i < mainDirectory.files.length; i++) {
        const file = mainDirectory.files[i];
        let filepath = Distinationpath + file.path

        if(file.path.endsWith("/")) {
            fs.mkdirSync(filepath);
        }
        else {

            file.stream(password).pipe(fs.createWriteStream(filepath))
                .on('finished', resolve)
                .on('error', reject);
        }
    }
});
});


text:
Q: Batch code: between dates or greater/less than? I have a simple Batch script that does something on a certain date, but I want it to be able to perform this between dates, or always before or after a certain date.
@ECHO OFF

IF "%DATE%"=="12/12/2011" GOTO ARMREST
GOTO END

:ARMREST
ECHO HELLO WORLD!
PAUSE

:END

Now I tried using ">=" but it didn't work, I've been all over but can't seem to find what I'm looking for. I don't even know if that kind of complex boolean can be used? This is for Windows 7, very simple script, just wondering about the dates.
Also, I have a Spanish machine, of which the date value differs from the UK - so the UK's is "12/02/2011" (DD/MM/YYYY), while the Spanish one is 12/2/2011 (dd/m/yyyy) I think, but I can find that out with a simple @ECHO %DATE% can't I?!
Thanks!

A: %DATE% returns the current date using the short date format, that is fully (endlessly) customizable. One user may configure its system to return Fri040811, and another user may choose 08/04/2011...it's a complete nightmare for a BAT programmer.
A possible solution is to use WMIC. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date in a convenient way to directly parse it with a FOR.
@ECHO OFF
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   SET /A DAYS=%%F*10000+%%D*100+%%A
)
IF %DAYS% GTR 20111210 (
  IF %DAYS% LSS 20111230 (
    ECHO Yes!
  )
)
GOTO :eof

A: You have to normalize all dates with format yyyymmdd to be compared. For instance:
rem Convert from dd/m/yyyy to yyyymmdd
set date=%date:/=/0%
set year=%date:~-4,4%
set month=%date:~-8,2%
set day=%date:~0,2%
set normdate=%year%%month%%day%

Check for instance http://ss64.com/nt/syntax.html for variable substring and replace.
Comparisons are done with lss, leq, gtr and geq.


text:
Q: Trivial image face processing How can I produce an image like this http://public.lanl.gov/herbertv/home/ ,
given the picture of my face as input?
Thanks

A: http://vectormagic.com/home

A: Try out this site:
http://www.befunky.com/
They have many artistic image effects in just a single mouse click


text:
Q: Dynamically parametrize Poly1 function in shapeless I have this situation (stripped down to the essential parts)
class Foo[L <: HList](columns: L) {

  class toRecord(row: Row) extends Poly1 {
    implicit def caseColumn[T] = at[Column[T]] { /* map to a record field */ }
  }

  def asRecord = {
    val resultSet: Stream[Row] = // computation to get result set
    resultSet.map { row =>
      val m = new toRecord(row) // this can't work
      columns.map(m)
    }
  }

}

This doesn't work since map wants a stable identifier and m is not.
So I would need as many Poly1 singleton objects as many rows I have in the result set.
This is the same problem discussed here: https://groups.google.com/forum/#!topic/shapeless-dev/P5DXRgnzqkY, but I can't find a way of making this work.
In the linked discussion Miles Sabin proposed a fold with a Poly2 instead of a map with a Poly1, but I can't figure how to use this suggestion in my case.

A: Ok, I finally managed to use a Poly2 with a foldRight in order to simulate a parametric map.
Here's an example to get the idea
object toRecord extends Poly2 {
  implicit def caseColumn[A, B] = at[Column[A], (Row, B)] {
    case (col, (row, acc)) =>
      val field = doMyThingy(row, col) // "map" `col` to a recordField using `row` as parameter
      (row, field :: acc)
  }
}

def asRecord[L <: HList, O <: HList](
  implicit folder: RightFolder[L, (Row, HNil.type), toRecord.type, (Row, O)]
): Stream[O] = {
  val resultSet: Stream[Row] = // computation to get result set
  resultSet.map { row => columns.foldRight((row, HNil))(toRecord)._2 }
}

So the "trick" here is to pass the parameter as the initial value of the fold and carry it along during the computation.
Inside the computation we apply a transformation on each element using row as parameter (our "parametric mapping") and then we simply append it to the accumulator.
When we're done, we end up with a tuple containing row and the mapped HList: we can simply discard the former (._2) and we're good to go.


text:
Q: $\mathbb{Q}[X,Y]/(X^2+Y^2-1)$ is integrally closed I'm was browsing this question, where it is proven the quotient field of $\mathbb{Q}[X,Y]/(X^2+Y^2-1)$ is isomorphic to the rational function field $\mathbb{Q}(t)$ under the isomorphism
$$
(x,y) \mapsto \left( \frac{2t}{t^2+1}, \frac{t^2-1}{t^2+1} \right).
$$
How can this isomorphism be used to show $\mathbb{Q}[X,Y]/(X^2+Y^2-1)$ is normal in its quotient field?

I identified $\mathbb{Q}[X,Y]/(X^2+Y^2-1)$ with $\mathbb{Q}\left[\frac{2t}{t^2+1}, \frac{t^2-1}{t^2+1} \right]$, and was trying to show this is integrally closed in $\mathbb{Q}(t)$.

If $f/g\in\mathbb{Q}(t)$, with $f,g$ coprime, is integral over $\mathbb{Q}[2t/(t^2+1),(t^2-1)/(t^2+1)]$, then
$$
(f/g)^n+h_{n-1}(f/g)^{n-1}+\cdots+h_1(f/g)+h_0=0,\qquad h_i\in \mathbb{Q}[2t/(t^2+1),(t^2-1)/(t^2+1)].
$$
Multiplying through by $g^n$, I found the relation
$$
f^n=g(-h_{n-1}f^{n-1}-\cdots-h_0g^{n-1})
$$
so any prime dividing $g$ divides $f$, so $g$ is constant, and in fact $f/g\in\mathbb{Q}[t]$. I was hoping to see that is is in fact in $\mathbb{Q}[2t/(t^2+1),(t^2-1)/(t^2+1)]$, but I think I've made a mistake somewhere.

A:
Let's prove that $R=\mathbb{Q}\left[\frac{2t}{t^2+1},\frac{t^2-1}{t^2+1}\right]$ is integrally closed.

We have $\mathbb{Q}\left[\frac{2t}{t^2+1},\frac{t^2-1}{t^2+1}\right]=\mathbb{Q}\left[\frac{1}{t^2+1},\frac{t}{t^2+1}\right]$. It's obvious that $\mathbb Q(t)$ is its field of fractions.  Let $f(t)/g(t)\in\mathbb Q(t)$ integral over $R$ with $\gcd(f(t),g(t))=1$. For any element $h\in R$ there is $r\in\mathbb N$ such that  $(t^2+1)^rh\in\mathbb Q[t]$. Consider an integral dependence relation $$(f/g)^n+h_{n-1}(f/g)^{n-1}+\cdots+h_1(f/g)+h_0=0$$ with $h_i\in R$ and multiply this by $(t^2+1)^{nr}$ with $r$ large enough in order to get an integral dependence relation for $(t^2+1)^rf(t)/g(t)$ over $\mathbb Q[t]$. Since $\mathbb Q[t]$ is integrally closed we get $(t^2+1)^rf(t)/g(t)\in\mathbb Q[t]$, and therefore $g(t)\mid(t^2+1)^r$. Since $t^2+1$ is irreducible over $\mathbb Q$ we have $g(t)=(t^2+1)^s$. Now it's clear that $f(t)/g(t)\in R$.

A: Due to both denominator's being the same that ring  is isomorphic to the ring $\mathbf{Q}[2t, t^2-1]$. That is, the subring of $\mathbf{Q}[t]$ generated by $2t$ and $t^2-1$. But in the presence of $2t$ we do not need $t^2-1$. So this subring can be  generated by just $2t$. So this is isomorphic to the PID $\mathbf{Q}[2t]$, hence normal.


text:
Q: query to sort an column containing comma separated values in mysql Am creating an ecommerce project for a client who wants to sell groceries online
and am having a price column which will contain comma separated price of the product for the respective quantity. The problem is how I can give sort by 'price high to low' or 'price low to high' feature.
This is the example table
    **id**    **Price**         **Quantity**           Name
       1          20,30,50         250mlgm,500ml,1lt     Coca-Cola
       2          40,60,70         250mlgm,500ml,1lt     Pepsi

Now the question is what the query would look like if I want to sort the price column from low to high or high to low
ORDER BY Price DESC or ORDER BY Price ASC doesn't work in my case
Please guide me on this
Am populating the price and quantity of each product in select tag by exploding the commas and saving them in an array like this
 <select ><option style='font-size:1vw;' value="Select Unit" >Select Unit</option>

  <?php
 $drq=$rows['Quantity'];
$drp=$rows['Price'];
  $degh=explode(',',$drp);
 $tryGH=explode(',',$drq);
  for($ij=0;$ij<count($tryGH);$ij++){
 echo "<option style='font-size:1vw;' value=$degh[$ij]  >$tryGH[$ij] - $degh[$ij]</option>";
  }
  ?> </select>

the result looks like this

A: Try using convert to convert the string to number and then sort it
SELECT id, Price, Quantity FROM Products ORDER BY CONVERT(Price, UNSIGNED INTEGER) ASC

A: You could arrange your DB a few ways. One way would be
**id**    **Price**         **Quantity**           Name
       1          20         250mlgm            Coca-Cola
       2          30         500ml              Coca-Cola
       3          50         1lt                Coca-Cola

Then in your code you could output to the client to select the value with
<select name="unit" >
    <option style='font-size:1vw;' value="Select Unit" >Select Unit</option>
<?php
$query = 'select Quantity, Price, Id, Name from Products ORDER BY name asc, Price DESC';
//execute the query, I don't know your driver
while($row = FETCH_FROM_YOUR_DRIVER) {
    $quantitY = $row['Quantity'];
    $price = $row['Price'];
    $id = $row['Id'];
    $company = $row['Name'];
    echo "<option style='font-size:1vw;' value='$id'>$quantity - $price $company</option>";
}?>
</select>

Then you should take the ID they select and query the price from your DB. In your current code I think you are taking the price directly from the client. The client however could manipulate that and send you a price of 0.
Update:

<?php
$query = 'select Quantity, Price, Id, Name from Products ORDER BY name asc, Price DESC';
//execute the query, I don't know your driver
$count = 0;
while($row = FETCH_FROM_YOUR_DRIVER /*again not sure of your driver*/) {
    $products[$count]['id'] = $row['Id'];
    $products[$count]['price'] = $row['Price'];
    $products[$count]['quantity'] = $row['Quantity'];
    $products[$count]['name'] = $row['Name'];
    $count++;
}
/* Can be removed, I haven't set up a DB so this is how I test
$products = array(array('id' => 2, 'price' => 30, 'quantity' => '500ml', 'name' => 'Coca-Cola'),
            array('id' => 3, 'price' => 50, 'quantity' => '1lt', 'name' => 'Coca-Cola'),
            array('id' => 4, 'price' => 20, 'quantity' => '25mlgm', 'name' => 'Pepsi'),
            array('id' => 5, 'price' => 30, 'quantity' => '500ml', 'name' => 'Pepsi'),
            array('id' => 6, 'price' => 50, 'quantity' => '1lt', 'name' => 'Pepsi'));
*/
$sameproduct = false;
foreach($products as $key => $product) {
    if ($key == 0 || $products[($key - 1)]['name'] != $product['name']) {
        if ($key != 0) { ?>
            </select>

        <?php } ?>

<?php echo $product['name'];?>

        <img src="/images/LOCATION/<?php echo strtolower(str_replace(array(' ', '-'), '_', $product['name']));?>.jpg" />

    <select name="unit" >
    <?php } ?>
        <option style='font-size:1vw;' value='<?php echo $product['id'];?>'><?php echo $product['quantity'];?> - <?php echo $product['price'];?></option>
<?php } ?>

This requires your names are consistent and also assumes the name in the db matches the name of the image in your file system. It replaces spaces and dashes in the name with underscores.


text:
Q: Efficient way to replace all column values using list of strings R I have a dataframe called car and am trying to replace certain values in the column called make which contains a number of unique car makes. I am trying to replace any value contained my a list of characters called car_list with the value low_frequency. However I only want whole string replacements, not partial which I have done by using boundaries.
The 'make' column of 'car' looks as such:
 make
 "LANDROVER"
 "VOLKSWAGEN"
 "VAUXHALL"
 "MG-MOTOR UK"
 "ROVER"
 "BWM"

'car_list` looks as such:
"MG-MOTOR UK"
"ROVER"
"ROBIN"

I which to replace all values in make that are contained in car_list with the new value low_frequency. The output should look as such:
 make
 "LANDROVER"
 "VOLKSWAGEN"
 "VAUXHALL"
 "low_frequency"
 "low_frequency"
 "BWM"

My attempt was using gsub and a for loop as I am used to python but I know this is bad practice in R and the solution crashes:
for (string in car_list){
  car['make'] <- gsub(paste('\\b', string, '\\b', sep = ''), 'low_frequency', car['make'])}

Any help would be appreciated.

A: Using replace.
replace(car$make, car$make %in% car_list, "low_frequency")
# [1] "LANDROVER"     "VOLKSWAGEN"    "VAUXHALL"      "low_frequency" "low_frequency" "BWM"

or with ""
replace(car[["make"]], car[["make"]] %in% car_list, "low_frequency")

which would look in a function something like:
FUN <- function(x) replace(car[[x]], car[[x]] %in% car_list, "low_frequency")
FUN("make")
# [1] "LANDROVER"     "VOLKSWAGEN"    "VAUXHALL"      "low_frequency" "low_frequency" "BWM"

Data:
car <- structure(list(make = c("LANDROVER", "VOLKSWAGEN", "VAUXHALL",
"MG-MOTOR UK", "ROVER", "BWM")), class = "data.frame", row.names = c(NA,
-6L))

car_list <- list("MG-MOTOR UK", "ROVER", "ROBIN")


text: Q: not allow to access local files and unable to open files forever This is a simple question. Each time I run my program I have to click "allow" to access local files. But once I clicked "not allow",  my program shows "Unable to open file" until I recreate a new project. Is there any way to solve it?


text:
Q: Cannot connect HTML file to CSS file which are both within the same folder This is an image of my workspace

This is an image of my CSS workspace

VS Code links the styles.css in the href="styles.css" line in the link tag and that leads me perfectly to the styles.css file so I'm unsure why it is not linking. I have tried a lot of things from the internet and nothing has worked.

A: Try this out:

<link rel="stylesheet" type="text/css" href="styles.css">

A: it should be ->  link rel='stylesheet'
you have mistakenly added and extra "s" as "stylesheets"

A: All the answers that say to remove the trailing s are correct.
Here's a link to the MDN web docs on the  element. p.s., don't feel bad about this, it's just a simple mistake that anyone can make.

A: Change stylesheets into stylesheet  remove s
<link rel='stylesheet' href='styles.css' type='text/css' media='all'/>

A: change your file path
<link rel="stylesheet" type="text/css" href="./styles.css">


text: Q: install SSL certificate in mobile device(IOS ,Android) and get the Thumbprint of the installed certificate in XAMARIN project is there any way to install SSL certificate in mobile device(IOS ,Android) and get the Thumbprint of the installed certificate to verify at the time of API call using ServerCertificateValidationCallback in the mobile application using xamarin. currently I hardcoded the thumbprint values in code side and validating it with the certificate thumbprint in ServerCertificateValidationCallback.


text:
Q: jQuery fadeIn onscroll event not working I have a fixed-position header div that I want to fadeIn (by jQuery) when the page is scrolled down 100px.
The jquery I am using is this:
$(document).ready(function(){
  $("body").scroll(function(){
    if ($("body").scrollTop() > 100) {
            $(".header").fadeIn();
                }
            else {
                $(".header").fadeOut();
            }
        });
    });

The full code is here: https://jsfiddle.net/Lxj0ynuk/
I have no idea why this doesn't work. I am not particularly confident with jQuery, so I am at a loss as to what has gone wrong.
Could anyone help?

A: Firstly, you haven't added jQuery to your fiddle.
Assuming that you are loading jQuery on your page, you should be detecting scroll on window not body:

$(window).scroll(function() {
  if ($(window).scrollTop() > 100) {
    $(".header").fadeIn();
  } else {
    $(".header").fadeOut();
  }
});
div.header {
  width: 100%;
  position: fixed;
  height: 50px;
  background: blue;
  top: 0px;
  margin: 0;
  display: none;
}

p {
  width: 100px;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla convallis cursus nisi sit amet suscipit. Etiam semper risus ac vulputate tincidunt. Duis sed neque sit amet lacus posuere egestas nec scelerisque nulla. Nam purus nunc, lobortis vel mauris
    sed, convallis imperdiet enim. Praesent nec erat ullamcorper, gravida turpis eu, mattis velit. Nulla porta pulvinar dolor quis scelerisque. Nullam at est at justo porttitor volutpat. Proin facilisis erat suscipit blandit porttitor. Maecenas egestas
    enim orci, ut egestas enim consequat a. Sed vehicula magna lorem, sed convallis erat porta non. Aenean quis consectetur nibh. Fusce nisl nulla, suscipit non vulputate eget, pellentesque et ligula. Curabitur sollicitudin urna ut sem euismod suscipit.
    Suspendisse eget lacus ut nisl luctus molestie. Vivamus convallis magna a dui ullamcorper, sed sagittis arcu volutpat. Suspendisse hendrerit erat sit amet rhoncus convallis. Praesent quis suscipit velit. Suspendisse quis porta eros, non pulvinar eros.
    Nam pellentesque pharetra dui, in interdum neque faucibus sit amet. Praesent quis orci nec neque posuere viverra. Integer volutpat sem id lectus congue, id vestibulum enim congue. Cras ultricies nunc justo, faucibus aliquam erat lobortis eu. Nullam
    mollis volutpat faucibus. In hac habitasse platea dictumst. Vivamus eu lectus et quam tristique mollis in eu dolor. Aliquam volutpat scelerisque diam porta rutrum. Phasellus sed est tincidunt, pretium mauris non, bibendum nibh. Pellentesque accumsan
    lacinia ultricies. Aenean et dolor ut quam dictum dapibus quis sit amet nisi. Praesent enim tellus, scelerisque et varius eu, porta vel ex. Vestibulum vel massa

A: use window.scroll or document.scroll function and use doument or 'body' height for fadeIn header Document.scroll and body height fiddle

$(window).scroll(function(){
 if ($(document).scrollTop() > 100) {
   $(".header").fadeIn();
  }
 else {
  $(".header").fadeOut();
 }
});
div.header {
  width: 100%;
  position: fixed;
  height: 50px;
  background: blue;
  top: 0px;
  margin: 0;
  display: none;
}

p {
  width: 100px;
}

Header

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla convallis cursus nisi sit amet suscipit. Etiam semper risus ac vulputate tincidunt. Duis sed neque sit amet lacus posuere egestas nec scelerisque nulla. Nam purus nunc, lobortis vel mauris
    sed, convallis imperdiet enim. Praesent nec erat ullamcorper, gravida turpis eu, mattis velit. Nulla porta pulvinar dolor quis scelerisque. Nullam at est at justo porttitor volutpat. Proin facilisis erat suscipit blandit porttitor. Maecenas egestas
    enim orci, ut egestas enim consequat a. Sed vehicula magna lorem, sed convallis erat porta non. Aenean quis consectetur nibh. Fusce nisl nulla, suscipit non vulputate eget, pellentesque et ligula. Curabitur sollicitudin urna ut sem euismod suscipit.
    Suspendisse eget lacus ut nisl luctus molestie. Vivamus convallis magna a dui ullamcorper, sed sagittis arcu volutpat. Suspendisse hendrerit erat sit amet rhoncus convallis. Praesent quis suscipit velit. Suspendisse quis porta eros, non pulvinar eros.
    Nam pellentesque pharetra dui, in interdum neque faucibus sit amet. Praesent quis orci nec neque posuere viverra. Integer volutpat sem id lectus congue, id vestibulum enim congue. Cras ultricies nunc justo, faucibus aliquam erat lobortis eu. Nullam
    mollis volutpat faucibus. In hac habitasse platea dictumst. Vivamus eu lectus et quam tristique mollis in eu dolor. Aliquam volutpat scelerisque diam porta rutrum. Phasellus sed est tincidunt, pretium mauris non, bibendum nibh. Pellentesque accumsan
    lacinia ultricies. Aenean et dolor ut quam dictum dapibus quis sit amet nisi. Praesent enim tellus, scelerisque et varius eu, porta vel ex. Vestibulum vel massa


text:
Q: Code adding \n and 1, and I don't know why This is a bit complicated, but basically I'm making a program and one of my functions is acting a bit strange.  The function is fed an array of characters, the first time it's
new_sensor_node   SN42   42   3.57   5.0   7.
right now the function just prints out each individual "token" (each set of characters separated by spaces).  Then prints a space, and then prints the number of characters in the token.  But for some reason, the last token is always printed weird, and 1 character extra is counted.
Here's the function:
int parseCommandLine(char cline[], char *tklist[]){
    int i;
    int length;
    int count = 0; //counts number of tokens
    int toklength = 0; //counts the length of each token
    length = strlen(cline);

    for (i=0; i < length; i++) {   //go to first character of each token

        if (((cline[i] != ' ' && cline[i-1]==' ') || i == 0)&& cline[i]!= '"') {

            while ((cline[i]!=' ')&& (cline[i] != '\0')){
                toklength++;
                cout << cline[i];
                i++;
            }
        cout << " " << toklength << "\n\n";
            cout << "\n";
            toklength = 0;
        count ++;
        }
        if (cline[i] == '"') {
            do {
                i++;
            } while (cline[i]!='"');
            count++;
        }
    }
    //cout << count << "\n";
    return 0;

And here's the output (for that first array):
new_sensor_node 15

SN42 4

42 2

3.57 4

5.0 3

7.
 3

Any thoughts on what could be causing this?  I suspect it might have to do with how I'm dealing with the null character

A: It's very likely that the input string actually contains the newline at the end. Depending on how you read the input, it may or may not be in the input. For example, the fgets function reads the newline and leaves it in the buffer.
Especially since you don't actually do any actual tokenization or modification of the input string, you just print character by character, this is a very likely scenario.