text:
Q: LDAP Authentication for Apache using Puppet I am currently setting up a reverse proxy in puppet so that I can authenticate using Active Directory.
I have the following in my puppet module.
class { 'apache::mod::ldap' :}
class { 'apache::mod::authnz_ldap' :}

apache::vhost { 'reverse-proxy':
  port           => '443',
  docroot        => '/var/www/html',
  ssl            => true,
  ssl_cert       => '/etc/httpd/ssl/cert.crt',
  ssl_key        => '/etc/httpd/ssl/cert.key',
  require        => [ File['/etc/httpd/ssl/cert.crt'], File['/etc/httpd/ssl/cert.key']],
  rewrites       => [
    {
      comment      => 'Eliminate Trace and Track',
      rewrite_cond => ['%{REQUEST_METHOD} ^(TRACE|TRACK)'],
      rewrite_rule => [' .* - [F]'],
    },
  ],
  proxy_preserve_host => true,
  proxy_pass => {
      path => '/',
      url => 'http://127.0.0.1:5601/',
  },
  directories => [
    {
      path => '/',
      provider => 'location',
      auth_name => 'Kibana Authentication',
      auth_type => 'Basic',
      auth_basic_provider => 'ldap',
      auth_ldap_bind_dn => 'cn=serviceuser,ou=Users,dc=example,dc=com',
      auth_ldap_bind_password => 'supersecretpassword',
      auth_ldap_url => 'ldaps://ldap.example.com/dc=example,dc=com?CN?
sub?(objectClass=user)',
      require => 'ldap-group
cn=application_users,ou=application_groups,ou=groups,dc=example,dc=com',
    },
  ],
}

The problem I'm running into is that when I apply this configuration to my apache server auth_ldap_bind_dn, auth_ldap_bind_password, and auth_ldap_url are not being copied over.  Puppet isn't throwing any errors and apache runs fine, but it isn't authenticating against LDAP.

A: old thread but for the benefit of anyone else with the same issue:
I've taken a look at the apache module's code in github and it doesn't appear to support the parameters you've mentioned (auth_ldap_bind_dn, auth_ldap_bind_password, and auth_ldap_url).
However, the directories resource allows you to include custom fragments, which you can use to inject any custom configuration outside of the apache module's scope into your config.
In your case, this should work:
class { 'apache::mod::ldap' :}
class { 'apache::mod::authnz_ldap' :}

apache::vhost { 'reverse-proxy':
  port           => '443',
  docroot        => '/var/www/html',
  ssl            => true,
  ssl_cert       => '/etc/httpd/ssl/cert.crt',
  ssl_key        => '/etc/httpd/ssl/cert.key',
  require        => [ File['/etc/httpd/ssl/cert.crt'], File['/etc/httpd/ssl/cert.key']],
  rewrites       => [
    {
      comment      => 'Eliminate Trace and Track',
      rewrite_cond => ['%{REQUEST_METHOD} ^(TRACE|TRACK)'],
      rewrite_rule => [' .* - [F]'],
    },
  ],
  proxy_preserve_host => true,
  proxy_pass => {
      path => '/',
      url => 'http://127.0.0.1:5601/',
  },
  directories => [
    {
      path => '/',
      provider => 'location',
      auth_name => 'Kibana Authentication',
      auth_type => 'Basic',
      auth_basic_provider => 'ldap',
      custom_fragment => "AuthLDAPURL 'ldaps://ldap.example.com/dc=example,dc=com?CN?sub?(objectClass=user)'
        AuthLDAPBindDN 'cn=serviceuser,ou=Users,dc=example,dc=com'
        AuthLDAPBindPassword supersecretpassword",
      require => 'ldap-group cn=application_users,ou=application_groups,ou=groups,dc=example,dc=com',
    },
  ],
}


text:
Q: startAnimatingWithImagesInRange reverse I am developing an Apple watch application. In the application I have progress bar with animation. I am using
  - (void)startAnimatingWithImagesInRange:(NSRange)imageRange
                                 duration:(NSTimeInterval)duration
                              repeatCount:(NSInteger)repeatCount

This is fine for increasing progress like 0 to 50. I would like to know is there any way I can reverse this like 50 to 0. I have already tried with minus NSRange length value with no luck.
Thanks

A: As mentioned in the docs for WKInterfaceImage (https://developer.apple.com/library/prerelease/ios/documentation/WatchKit/Reference/WKInterfaceImage_class/#//apple_ref/occ/instm/WKInterfaceImage/startAnimatingWithImagesInRange:duration:repeatCount:), all you have to do is supply a negative value to duration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Displaying a byte[] file with wicket I want to be able to display on the browser a file with wicket. I have a form witch takes the id and storage area of the document, then by pressing the submit button, I would like to display the file on the browser if it's possible else download it.I get the file as a byte [], it's compulsory, I cannot have it another way. I searched a lot for some answers but the fact that I'am using wicket 6.8.0 is handicapand because every solution that I find uses some obsolete methods (for the 6.8.0 version).
My question is: Is there any one who can help me do this without changing the wicket version (I cannot change it). The solution doesn't have to be in wicket.
Sorry if my English is incorrect
Thank you in advance

A: I found it. For persons who want to do this with wicket 6.8.0, it's the solution. It's quite simple though. Here's the code:
WebResponse fileResponse = (WebResponse) getRequestCycle().getResponse();
fileResponse.setContentType(mimeType);
fileResponse.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");

fileResponse.write(myByteFile);
getRequestCycle().setResponse(fileResponse);

I get the file type by using the  Tika API.


text:
Q: What is the correct public access config for s3 bucket to access from lambda with http proxy integration? I have an s3 bucket and I want to upload a file from a lambda that is invoked through an API call but I don't know what is the correct config for blocking public access configuration setting of the s3 bucket. Now, none of the 4 options are checked and it works but I'm not sure about it considering the security aspects.
What is the correct configuration of policy bucket, IAM role and blocking public access for upload a file to s3 using an http call?
Thanks!

A: The appropriate configuration is:

*

*Lambda function IAM role: permit s3:PutObject to s3://mybucket/myprefix/*

*Lambda function: use AWS SDK to invoke PutObject to S3

The S3 bucket policy and S3 block public access settings are largely orthogonal to the Lambda requirement here. In the typical case, you should use standard best practices: do not have an S3 bucket policy at all (unless you specifically need it) and enable Block Public Access at the account level (unless you specifically need buckets to be public).


text:
Q: shiny: multiple conditional panels within main panel is not working I am trying to code an application for linear and multiple regression using shiny, I have an issue with multiple conditional panels,
that,

*

*It does not check for conditions and executes first conditional panel.

*That's not a single problem, it also fails to read the file and remains as it is for the first condition panel which is selected.
library(shiny)
# Define UI for application that draws a histogram
  ui <- fluidPage(

 # # Application title
 # column(9,
 #   titlePanel("Multiple Regression")
 #
 #   ),

 sidebarLayout(
    sidebarPanel(
       selectInput("sel_type",
                   "Select Regression Type ",
                   c("Linear Regression"="LR","Multiple Regression"="MR"),
                   selected = "LR"),
       fileInput("file1", "Choose CSV File",
                 accept = c(
                   "text/csv",
                   "text/comma-separated-values,text/plain",
                   ".csv")
       ),
       uiOutput("select_predict"),
       conditionalPanel(
         condition = "input.sel_type=='LR'",
         uiOutput("select_test")
       )

    ),

    mainPanel(
       conditionalPanel(
         condition = "input.sel_type=='LR'",
         h1("Simple Linear Regression"),
         br(),
         h3(textOutput("scat_plot"))
          ,plotOutput("scatter_plot",width = 500, height = 500),
         br(),
         # verbatimTextOutput("dataSet"),
         h3("Data Set"),
         br(),
         column(4,
                h4("Test variable"),
                tableOutput("tbl1"),
                offset = 1
         ),
         h4("Predicting variable"),
         tableOutput("tbl"),
         br(),
         h3("correlation analysis"),
         verbatimTextOutput("cor"),
         br(),
         h3("Linear model and Regression Analysis"),
         br(),
         verbatimTextOutput("lm_ra"),
         br(),
         uiOutput("predict"),
         br(),
         verbatimTextOutput("predicted_value")
         ),

       conditionalPanel(
         condition = "input.sel_type == 'MR' ",
          h1("Multiple Regression"),
          br(),
         verbatimTextOutput("summary"),
          h2("COrrelation Analysis"),
          br(),
          verbatimTextOutput("cor")
       )
    )
 )
)

# Define server logic required to draw a histogram
  server <- function(input, output) {

# sample1 <- read.csv(input$file1$datapath)

output$select_predict = renderUI({
  df <- read.csv(input$file1$datapath)
  selectInput("sel_test_var","Select Test variable",choices =  names(df))
})

output$select_test = renderUI({
  df <- read.csv(input$file1$datapath)
  selectInput("ip2","Select Predicting Variable",names(df)[!names(df)==input$sel_test_var])#,multiple = T)

})

output$scat_plot = renderText({
  sprintf(
    "Scatter plot between '%s' and '%s'", input$sel_test_var, input$ip2
  )

})
output$scatter_plot = renderPlot({
  df <- read.csv(input$file1$datapath)
  x<- df[,input$sel_test_var]
  y<- df[,input$ip2]

 if (!is.null(y)) {
  plot(x,y,xlab=input$sel_test_var, ylab=input$ip2)
  abline(lm(y~x))
  }
    })
# output$dataSet = renderPrint({
#   df <- read.csv(input$file1$datapath)
#   sprintf("Data of %s",input$sel_test_var)
#   df[,input$sel_test_var]
# #  sprintf("Data of %s",input$ip2)
#  #   df[,input$ip2]
# })

output$tbl = renderTable({
  df <- read.csv(input$file1$datapath)
  z <- as.data.frame(df[,input$ip2])
  names(z) <- input$ip2
  z
})
output$tbl1 = renderTable({
  df <- read.csv(input$file1$datapath)
  z <- as.data.frame(df[,input$sel_test_var])
  names(z) <- input$sel_test_var
  z
})
 output$cor=renderPrint({
 df <- read.csv(input$file1$datapath)
 result <- cor.test(df[,input$ip2],df[,input$sel_test_var],method = "pearson")
 result
 })
 output$lm_ra = renderPrint({
 df <- read.csv(input$file1$datapath)
 model1 <- lm(df[,input$sel_test_var] ~ df[,input$ip2])
 model1
 #sprintf("Summury linear model")
 cat(sprintf("Model summary"))
 summary(model1)
 })

    output$predict = renderUI({

   numericInput(inputId = "predict_value",label = "Enter Predicting value",value = 10)
 })

 output$predicted_value = renderPrint({
 df <- read.csv(input$file1$datapath)
 x <- df[,input$ip2]
 model1 <- lm(df[,input$sel_test_var] ~ x)
 y=predict(model1,data.frame(x = input$predict_value),interval = "confidence", level=0.95)
 y
 })

 ########################## Multiple Regression #################################

 output$summary = renderPrint({
 df <- read.csv(input$file1$datapath)
 cat(paste("Structure of Data Set\n"))
    str(df)
 #cat(paste("\n\n"))
 # cat(paste("Dimension of Data Set\n"))
 #  dim(df)
  cat(paste("\n\n"))
 cat(paste("Summary of Data Set\n"))
  summary(df)
 })

 output$cor = renderPrint({
 df <- read.csv(input$file1$datapath)
 cor(df)
 })

}

# Run the application
  shinyApp(ui = ui, server = server)

Thank you in advance!!!


text:
Q: Change page controls value after thread finished?
Possible Duplicate:
asp.net update UI using multi-thread

I started a thread to process on background.And i want to change my label on page after finished proceess.
But my value doesn't change.
my sample :
    protected void Page_Load(object sender, EventArgs e)
    {
         new Thread(() => ActionStart()) { IsBackground = true }.Start();
    }
    bool _shouldStop = false;

    public void ActionStart()
    {
        while (!_shouldStop)
        {
            // ....

            requestStop();
        }

        //thread finished
        ChangeValue();

    }
    private void ChangeValue()
    {
        lab.Text = "Changed";
    }

    private void requestStop()
    {
      _shouldStop = true;
    }

A: I'm afraid running this code on a Thread won't help you because you can't make sure the thread will complete before it's to late considering the page life cycle. Generally, the last chance you got to alter a control's value is the it's PreRender event, but that depends on how it  has been developed.
However, if you need to do processing in parallel, you still can use a Parallel.Foreach, for instance, inside a page event like PageLoad to take advantage of parallelism without being asynchronous (Parallel.Foreach will only return when all threads complete).


text:
Q: How to keep AppleScript running as long as a specific application is running? Normally in AppleScript it goes line by line and at the end it quits the script. Is there a way to make the script keep on running? This is the situation:
Via the AppleScript I am opening Google Chrome. This is fine. After opening it the AppleScript have to keep on running until Google Chrome is closed. When closed it needs to show a dialog that Google Chrome is closed and quit itself.
Is there a way to do this?

A: You can also try an on idle handler...
repeat until application "Google Chrome" is not running
    -- insert your code
    say "run"
    delay 2
end repeat
say "quit"


text:
Q: Fill pattern of an arbitrary size in Intel hex file I have been trying to do a fill using the open source Srecord Program. I need to do a fill that is
0xC2AF00. It appears the program can only do fills that are a byte long (ex: 0xff). If this is not possible with the  Srecord program, then how would I go about writing my own algorithm to do what I want?
I am not quite sure how to determine what needs a fill and then how I would proceed to go about doing the fill that is needed.  And on the off chance that someone could answer the same question for a Tektronix file, that would be just as good or better than how to do what I am asking for on the Intel hex file.

A: The -repeat-data generator can take multiple bytes as parameters.
The following will fill bytes 16 through 31 with C2AF00C2AF00...
srec_cat -Output -Intel -generate 0x10 0x20 -repeat-data 0xC2 0xAF 0x00

Combine with your actual input, or other generators, to fill the appropriate ranges.

A: You can have full control over generating Intel Hex file with some special library, e.g. with this IntelHex Python library


text:
Q: How to force/reproduce FullGC in JVM? Is there a way to force/reproduce FullGC in JVM  for x seconds ? Basically I needed this to verify root cause of an issue in certain heart beat based app ( a client of zookeeper)
EDIT: Does unix command kill -STOP <pid> and kill -CONT <pid> simulate FullGC ( stop the world behaviour) ?

A: You can simulate a very long stop-the-world event on HotSpot JVMs which is similar to FullGC from user's point of view.
HotSpot doesn't put safepoints into counted int loops, because it assumes that they will terminate just "fast enough"(In this case server compiler will generate more optimal loop code). Even a stop-the-world will have to wait until this loop will finish. In the following example we have very tight loop which do small but expensive computations without safepoint polling:
public static double slowpoke(int iterations) {
    double d = 0;
    for (int j = 1; j < iterations; j++) {
        d += Math.log(Math.E * j);
    }
    return d;
}

In order to reproduce FullGC like pause you can use something like this:
public class SafepointTest {

    public static double slowpoke(int iterations) {
        double d = 0;
        for (int j = 1; j < iterations; j++) {
            d += Math.log(Math.E * j);
        }
        return d;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                double sideEffect = 0;
                for (int i = 0; i < 10000; i++) {
                    sideEffect = slowpoke(999999999);
                }
                System.out.println("result = " + sideEffect);
            }
        };
        thread.start();

        new Thread(){
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis();
                while (true){
                    System.out.println("Delay " + (System.currentTimeMillis() - timestamp));
                    timestamp = System.currentTimeMillis();
                    //trigger stop-the-world
                    System.gc();
                }
            }
        }.start();
        thread.join();
    }
}

As a result:
Delay 5
Delay 4
Delay 30782
Delay 21819
Delay 21966
Delay 22812
Delay 22264
Delay 21988

In order to increase delay just change argument value for slowpoke(int iterations) function.
Here is useful diagnostic commands:

*

*-XX:+PrintGCApplicationStoppedTime this will actually report pause time for all safepoints into GC log. Unfortunately output from this option lacks timestamps.

*-XX:+PrintSafepointStatistics –XX:PrintSafepointStatisticsCount=1 this two options will force JVM to report reason and timings after each safepoint.

EDIT
Regarding to Edit: from user's point of view kill -STOP and kill -CONT have the same semantics as STW i.e. application doesn't respond on any request. However, this requires access to command line and doesn't consume resources(CPU, memory).


text:
Q: Lync for Receptionist We want to use Lync Attendant for our front desk but I'm confused on how to set this up.  We usually have one receptionist that's up there, but when she goes to lunch, there can be any number of different people covering the front desk.
I'm wondering if I should set up one account called 'receptionist' and have anyone covering the front desk log into that account.  The drawback of that is that the people can't work on their things when they're up at the front desk.
I can each have them log into the computer front desk computer.  That way, they can work on their own things AND answer calls.  The problem is that they'll have to log into the phone up there too.  That sounds like a pain.
So I wanted to see how anyone else solved this problem.  What are you guys doing for your front desk?

A: Lync provides this capability through Response Groups. Have a look at:

*

*http://technet.microsoft.com/en-us/library/gg398584.aspx.

*http://blogs.technet.com/b/ilvancri/archive/2010/11/23/creating-a-response-group-in-lync.aspx
The Attendant Client is just an alternate client for Lync.


text:
Q: React: how to uncheck all checkbox on save I am trying to create an audit form to make a list of patients and what alerts they have.  When I click the 'Save patient' button I want all the checkboxes to untick/reset themselves but I can't figure it out. I have set the state of alerts back to an empty array, but the checkboxes are still ticked.  Any help would be amazing as I am new to React :)
class AuditForm extends Component {
  state = {
hospitalNum: []
    alerts: [],
    list: [],
  };
  render() {
    const { alerts } = this.state;
    return (
      <div>
        <Form>
          <Form.Row>
            <Form.Group>
              <Form.Label>Hospital Number</Form.Label>
              <Form.Control
                value={this.state.hospitalNum}
                type="string"
                onChange={this.handleHospNumChange}
              />
            </Form.Group>
             </Form.Row>
          <Form.Group>
            <Form.Check
              onChange={(e) => {
                this.updateAlertList(e, "MRSA");
              }}
              inline
              label="MRSA"
              type="checkbox"
              id="MRSA"
            />
            <Form.Check
              onChange={(e) => {
                this.updateAlertList(e, "cDiff");
              }}
              inline
              label="cDiff"
              type="checkbox"
              id="cDiff"
            />

          </Form.Group>
          <Button variant="primary" type="submit" onClick={this.saveData}>
            Save patient
          </Button>
        </Form>
      </div>
    );
  }

  saveData = (e) => {
    e.preventDefault();
    this.setState((currentState) => {
      return {
        hospitalNum: [],
        alerts: [],
        list: [
          ...currentState.list,
          {
            hospitalNum: currentState.hospitalNum,
            alerts: currentState.alerts,
          },
        ],
      };
    });
  };

  handleHospNumChange = (e) => {
    this.setState({ hospitalNum: e.target.value });
  };

  updateAlertList = (e, alert) => {
    if (e.target.checked === false) {
      const filteredAlerts = this.state.alerts.filter(
        (prevAlert) => prevAlert !== alert
      );
      this.setState({ alerts: filteredAlerts });
    } else {
      this.setState((prevState) => {
        return {
          alerts: [...prevState.alerts, alert],
        };
      });
    }
  };
}

export default AuditForm;

A: You can store the checked or unchecked values of the checkboxes in the state and after save you can setState the state as false for all checkboxes

A: You need to add a checked property to each checkbox and check to see if that item exists in your state. Check out the react docs on forms and read up on controlled components. The react docs are awesome and have helped me a lot.
Here's a possible solution:
<Form.Check
   onChange={(e) => {
     this.updateAlertList(e, "cDiff");
   }}
   inline
   label="cDiff"
   type="checkbox"
   id="cDiff"
   checked={this.state.alerts.includes("cDiff")}
/>

Then once you save you need to handle the form data and then set the alerts list back to an empty array.
Hope that helps!


text:
Q: Android - Is it possible to overwrite userdata of another app? I want to update user data of another app from my app. The purpose of this is to update some images that the other app uses. Is this possible?

A: It depends on where the data/images are saved.
For every app there is a folder named /android/data/package.name to which only that application has access to read and write. No other application has the privilege of writing to that particular folder.
But if the data is saved somewhere else than /android/data/package.name folder, then you can definitely overwrite their data giving that you have proper  read/write permissions.


text:
Q: How do I access the new Halloween map/content? I haven't beat all the maps in regular, nor any challenges, but I'd like to see and play the new one if I can.

*

*where do I find the special map so I can unlock outfits?

*do I have to beat the regular maps first?

*Is the map available in both ranked and open?

A: To get the new content, click on the big Download Content button on the main page.  There are 2 items for the Halloween special event.  The first is the Costume Pack, which gives you these costumes:

*

*Devil – Monk

*Mummy – Apprentice

*Pirate – Squire

*Witch – Huntress

These are already unlocked and you can edit your character from the character selection screen to pick them immediately.
The second DLC is the Mission Pack, which unlocks the Halloween Spooktacular challenge (in the challenges list).  If you complete this challenge on hard or insane, you can unlock the following costumes (depending on the class you beat it with) and a class specific weapon as well:

*

*Ninja – Monk

*Vampire - Apprentice

*Death Knight - Squire

*Angel - Huntress

I do not think you have to beat the regular missions first, but I am unsure of this as I've alreayd do so.
Update
A recent patch has unlocked the content to Open players as well.  So it is now available to all.

A: The content is currently ONLY available on Ranked Online games (IE: TrendyNet games). The first set of costumes and the halloween challenge map are then just available. if you beat the new challenge map on Insane then you unlock the second set of costumes.
Trendy has said that the content will eventually work in Open/Local games as well but it doesnt right now.


text:
Q: VirtualBox installation asked me a password with UEFI system I use Ubuntu Studio 20.04.2 LTS inside 2 desktop computers and 1 laptop computer.
The laptop is an UEFI Ubuntu Studio system.
I installed Oracle VirtualBox 6.1 in all my machines, but... In the laptop, when I was installing VirtualBox, the installation asked me a password to start the UEFI system. Now, Each time I start that laptop, I get a little window with 3 options. Of course, if I click on the first option, "Continue normal", I get all my Ubuntu Studio installation without problems. But...
Is it normal, "by default"? ???


text:
Q: Origin of the expression "you can't make chicken salad out of chicken something else" I discovered this expression:

You can't make chicken salad out of chicken something else

I heard this expression from one of the NBA basketball TV commentators on Fox Sports Oklahoma, who uses it in the affirmative, and uses something else instead shit. He uses it when a basketball player manages to score from a play situation that didn't look good at all:

The player made chicken salad out of chicken something else.

I would like to know what is the origin of the expression and where does it originate from. Any ideas?

A: An outline of the origins, uses and etymology of the phrase and its relation(s) can be found by Barry Popik. A summary:

The expressive flip side to "chicken salad" is "chicken feathers" (a euphemism for "chicken shit"). A difference "between chicken salad and chicken feathers" is cited in print in 1924; "like chicken salad compares with chicken feathers" is cited from 1930.

A: The first time I heard the saying was in 2007, when Casey Printers (quarterback) was cut from the NFL's Kansas City Chiefs.  "You want me to make chicken salad out of chicken-sh."


text:
Q: How to limit the number of items from an AWS DynamoDB scan? I am using node.js.
If you look at this example:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html
It says:
aws dynamodb scan \
    --table-name Movies \
    --projection-expression "title" \
    --filter-expression 'contains(info.genres,:gen)' \
    --expression-attribute-values '{":gen":{"S":"Sci-Fi"}}' \
    --page-size 100  \
    --debug

Where page-size limits the number of result items:

Ordinarily, the AWS CLI handles pagination automatically; however, in this example, the CLI's --page-size parameter limits the number of items per page.

But if you read the Node.js AWS documentation:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property
There is no parameters associated with "page-size".
(Only Limit which limits the number of items being scanned, not returned).
How do I limit the number of returned items (that satisfies my condition)?

A: aws dynamodb scan \
    --table-name Movies \
    --projection-expression "title" \
    --filter-expression 'contains(info.genres,:gen)' \
    --expression-attribute-values '{":gen":{"S":"Sci-Fi"}}' \
    --page-size 100  \
    --debug

What you think this does: "read the entire table, find the rows that satisfy filter, and then return up to 100 of those"
What Dynamo does: "read 100 rows, find the rows that satisfy filter, and return them"
I think you need an index :)

A: Looks like you miread the documentation,
Limiting the Number of Items in the Result Set
The Scan operation allows you to limit the number of items that it returns in the result. To do this, set the Limit parameter to the maximum number of items that you want.
For example, suppose you Scan a table, with a Limit value of 6, and without a filter expression. The Scan result will contain the first six items from the table that match the key condition expression from the request.
Now suppose you add a filter expression to the Scan. In this case, DynamoDB will apply the filter expression to the six items that were returned, discarding those that do not match. The final Scan result will contain 6 items or fewer, depending on the number of items that were filtered.
On the same link,
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html
Hope it helps.


text:
Q: How can I protect a USB flash drive I am trying to create a portable development environment on a USB flash drive, I am doing this because I need something ultra portable that I can carry around with me everywhere, I am also a CS student and we have computer lab, so the drive will be a good thing to use in such a scenario.
The platform I work on is Windows, and I will use the drive 99% of the time on Windows computers as well, so cross-compatibility is not an issue for me, at least for now.
I will put VSCode (.zip version) on the drive, along with cmder.
I have one main concern, the computers that I generally plug the drive into are filled with malware and viruses, is there a way, maybe an app, that will protect the drive from such malware?
Thanks in advance

A: They make flash drives with a physical write protect switch. This seems like it might be the safest way and reminds me of the old days with floppy disks; We used to use a write protect on the disk at university for the same reason.

A: You can use a drive with a read-only switch, but keep in mind that there is no way to prevent malware on a device from writing to the drive while retaining your own ability to do so.


text:
Q: UIImagePickerController preview image shifts down I know there are questions from several years ago on this topic, but I think their solutions are out of date and/or I can't get them to work. I tried all the info.plist changes, etc.
I'm using UIImagePickerController. After taking a photo, the preview image (with Retake and Use photo options) jumps down about 20 pixels. It seems like it's occupying the mediaTypes toolbar area.
Any suggestions for how to prevent the image from shifting? Here's the relevant code (very basic)
- (IBAction)takePhoto:(UIButton *)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [picker prefersStatusBarHidden];
    [self presentViewController:picker animated:YES completion:NULL];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

A: After trying a lot of config stuff that didn't work, I took a simple approach and forced the camera view down by the same number of pixels that the preview image was shifting using a transform, i.e.
picker.cameraViewTransform = CGAffineTransformTranslate(picker.cameraViewTransform, 0.0, 30.0);

The whole method:
- (IBAction)takePhoto:(UIButton *)sender {

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;

    picker.cameraViewTransform = CGAffineTransformTranslate(picker.cameraViewTransform, 0.0, 30.0);

    [self presentViewController:picker animated:YES completion:NULL];
}


text:
Q: Method paginate does not exist When I do:
    $tournaments =  Tournament::paginate(Config::get('constants.PAGINATION'));

it works, but I just need tournaments that owns the user.
So I do:
    $tournaments = Auth::user()->tournaments;
    $tournaments->paginate(Config::get('constants.PAGINATION'));

I have a hasMany Relationship in user model
And I get this message
Method paginate does not exist.

How can I solve it? It doesn't seem complicated, but I can't do it!
EDIT:
@smartrahat
Result of the second query: Auth::user()->tournaments
Collection {#385 ▼
#items: array:1 [▼
0 => Tournament {#386 ▼
  #table: "tournament"
  +timestamps: true
  #fillable: array:17 [▶]
  #dates: array:2 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  #attributes: array:16 [▶]
  #original: array:16 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}
]
}

Result of the first query:
LengthAwarePaginator {#428 ▼
#total: 2
#lastPage: 1
#items: Collection {#430 ▼
#items: array:2 [▼
  0 => Tournament {#431 ▼
    #table: "tournament"
    +timestamps: true
    #fillable: array:17 [▶]
    #dates: array:2 [▶]
    #connection: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    #attributes: array:16 [▶]
    #original: array:16 [▶]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
    +wasRecentlyCreated: false
  }
  1 => Tournament {#432 ▶}
]
}
#perPage: "20"
#currentPage: 1
#path: "http://laravel.dev:8000/tournaments"
#query: []
#fragment: null
#pageName: "page"
}

A: In your question you are calling paginate() on a Collection more than likely.
In the answer that works you are calling paginate() on an eloquent builder.
Auth::user()->tournaments; // dynamic property for relationship, probably a collection

Auth::user()->tournaments(); // relation type object (eloquent builder)

Your answer:
$tournaments = Tournament::where('user_id',Auth::user()->id)
    ->paginate(Config::get('constants.PAGINATION'));

where is returning the eloquent builder that you are calling paginate on.
This should give you the same result:
$tournaments = Auth::user()->tournaments()->paginate(...);

A: I resolved it using:
$tournaments = Tournament::where('user_id',Auth::user()->id)
        ->paginate(Config::get('constants.PAGINATION'));;

but I still doesn't understand why is it behaving like that


text:
Q: Graphical intuition behind directional derivative interpreted as a(∂f/∂x)+b(∂f/∂y), where  is directional vector of unit length? Given a function f(x, y), the directional derivative is defined to be a(∂f/∂x)+b(∂f/∂y), with being a vector of unit length designating the direction in which we wish to take the derivative. I understand how we go from the limit definition of a derivative in the direction of unit vector to a(∂f/∂x)+b(∂f/∂y), but I do not understand how to interpret this theorem (Df(x, y) = a(∂f/∂x)+b(∂f/∂y)) GRAPHICALLY. It is hard for me to visualize the derivative at a given point (x, y) in the direction of  being a(∂f/∂x)+b(∂f/∂y). For example, evaluating f(x, y) at directional vector <1, 0> yields the derivative ∂f/∂x. I find it difficult visualizing what is happening when we evaluate the directional derivative at, say, f(1, 1) in the direction <1/√2, 1/√2>. I can't quite visualize why the partial derivative with respect to x at point f(1, 1) multiplied by the x component plus the partial derivative with respect to y at point f(1, 1) multiplied by the y component ends up being derivative at f(1, 1) in the direction of the vector. Can you explain what is happening?

A: To visualize what is happening, think about the graph of the function in 3D space as a wiggly sheet above (and possibly below) the x-y plane, which is like the floor.  Picking a point $(x_0,y_0)$ on the floor, the height of the sheet above that point is given by $f(x_0,y_0)$.  If you want to know the directional derivative at that point in the direction of a vector $(a,b)$, what you are doing is essentially slicing the graph above the point $(x_0,y_0)$ in the direction of the vector $(a,b)$ (i.e. cutting through x-y plane along the line given by $y-y_0 = \frac{b}{a}(x-x_0)$).  When we restrict our attention to just this 2D slice, we have what looks like the graph of a single-variable function, and the directional derivative gives the slope of the tangent line of this function above the point in question.
The reason the directional derivative ends up being a linear combination of the directional derivatives in the two standard directions is because the differentiability of the function $f$ at $(x_0, y_0)$ means that the function can be locally approximated by a plane at that point (this is called the tangent plane).  So if we look at the tangent line of our "slice" in the direction of the x-axis and the tangent line of the "slice" in the direction of the y-axis, these form two lines in 3D space that intersect at the point $(x_0, y_0, f(x_0,y_0))$ on our wiggly sheet.  There is only one plane that contains two intersecting lines, and this plane is the tangent plane.  So these two tangent lines completely determine the tangent plane, and hence any other tangent line of any other slice. If we slice the function in a direction almost parallel to the x-axis, then the slope of the tangent line will be almost equal to $\partial f/\partial x$, whereas if we slice it in a direction almost parallel to the y-axis, it will be almost $\partial f/\partial y.$  The unit vector $(a,b)$ basically tells you what proportion of the slope is determined by the slope in the x-direction (a) and what proportion is determined by the y-direction (b).
As an interesting aside: if the function $f$ is not differentiable at $(x_0, y_0)$, it may still be possible to find the directional derivatives $\partial f/\partial x$ and $\partial f/\partial y$, however the directional derivative in a different direction might not exist, or if it does, might not be given by the formula you state.  This is because there is no well-defined tangent plane to the function at that point.


text:
Q: Comparing DateTime values in EntitySQL when starting with a querystring I am using the QueryBuilder as following:
var queryString = String.Format(
    "SELECT VALUE e FROM Entity AS e WHERE e.EndDate {0} {1} ",
    operator,
    DateTime.Today.AddYears(1).ToString("d", DateTimeFormatInfo.InvariantInfo)
);
ObjectQuery<Entity> query = new ObjectQuery<Entity>(queryString, Context);

Please note that I extremely simplified this example and that my goal is to build the query as string before creating a QueryBuilder instance. (As long as this is possible)
I already tried the following
...DateTime.Today.AddYears(1)...
...DateTime.Today.AddYears(1).ToString()...
...DateTime.Today.AddYears(1).ToString("yyy\MM\dd")...

which all result in a exception which says that I either cannot compare DateTime with a String or with a Int32.
I'm beginning to asking me if this is possible at all with this approach...

A: In Entity SQL DateTime literals must be expressed in the following format:
DATETIME'2012-02-02 16:26'

where both the date and time parts are mandatory. For example:
"SELECT VALUE e FROM Entity AS e WHERE e.EndDate > DATETIME'2012-02-02 16:26'"


text:
Q: Is resetting the array a valid way to break from Array.forEach? I was looking for an easy way to break out of forEach. This answer mentions using the some method, but that doesn't give you the index of the current element: How to short circuit Array.forEach like calling break?
I found that setting the array to false will break the forEach "loop". Is that valid or a hack?

A: If you mean by setting its .length to the current index in the iteration, then yes, it's "valid", but be aware that in doing so, you're clearing any Array members from that point forward.
var arr = ["foo","bar","baz"];

console.log(arr.length); // 3

arr.forEach(function(v, i) {
    if (i == 1)
        arr.length = i;
    else
        console.log(v);
});

console.log(arr.length); // 1

If you set the .length to false, you're effectively setting it to 0, and so you're clearing the entire Array.
Using .some or .every seems more sensible to me.

I should note that the iteration doesn't necessarily stop, but your callback won't be invoked because the native .forEach() does not invoke the callback for non-existent properties. According to the spec, the length in cached.
This can be tested by expanding the Array during the iteration. The added members are never reached.

A: According to the documentation, the index of the current element is passed as the 2nd parameter to the callback function:
Syntax:  array.some(callback[, thisObject])
callback is invoked with three arguments:
   1. the value of the element
   2. the index of the element
   3. the Array object being traversed

See documentation here

More importantly...
Is there any reason you can't do it the normal way:
var matchIndex = -1;
for (i = 0; i < someArray.length; i++) {
    if (isFound(someArray[i])) {
        matchIndex = i;
        break;
    }
}
alert("Mathing index: " + matchIndex);


text:
Q: Unauthorized status from mobile Xamarin Forms application with Axelor Rest web-services I want to connect to the Axelor server with a Xamarin forms application, I use this method to test the rest services connectivity :
                Login login = new()
                {
                    UserName = Constants.Login,
                    Password = Constants.Password
                };

                // Build authentication string
                byte[] bytes = Encoding.UTF8.GetBytes($"{login.UserName}:{login.Password}");
                string authorizationString = Convert.ToBase64String(bytes);

                // Add headers to the HTTP client
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationString);

                // Build HTTP message and send, strRoot = login.jsp
                string url = $"{Constants.RestBaseUrl}/{strRoot}";
                HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, url);
                var sessionResponse = await httpClient.SendAsync(message);

                /* sessionResponse.IsSuccessStatusCode = true, and sessionResponse.Headers =
                 {
                     Set-Cookie: JSESSIONID=E5EA31C3A5CBDF0A1C4B05ED2230679E; Path=/Gradle___com_axelor___axelor_erp_6_3_0_war; HttpOnly
                     Date: Mon, 14 Nov 2022 19:40:04 GMT
                 }
                 */
                sessionResponse.Headers.ToList().ForEach(x =>
                httpClient.DefaultRequestHeaders.Add(x.Key, x.Value.FirstOrDefault()));

                var rt = $"{Constants.RestBaseUrl}/ws/rest/com.axelor.apps.poultryfarming.db.Hatchery";
                var response = await httpClient.GetAsync(rt);

                var returnValue = await response.Content.ReadAsStringAsync();
                /* returnValue :
                 <!doctype html><title>HTTP Status 401 – Unauthorized</title>
HTTP Status 401 – Unauthorized

Type Status Report

Description The request has not been applied because it lacks valid authentication credentials for the target resource.

Apache Tomcat/8.5.73

                 */
                var stat = response.StatusCode; // return: Unauthorized
                var cc = response.IsSuccessStatusCode;

                return returnValue;
            }
            catch (Exception e)
            {
                throw;
            }

but i always get the Unauthorized status !
Can you help me please
When I test with navigator I have correct response like this :

A: It works well with RestSharp.RestRequest!
Call Axelor rest services with RestClient example : https://github.com/dalmed/Maui-Axelor-Mobile.git
This is my solution :
public class RestClientService : IRestClientService
{
    //private readonly ILogger<RestClientService> _logger;
    public RestClientService()
    {
        //_logger = logger;
    }

    public async Task<bool> LoginAsync(Login login)
    {
        string jsonString = JsonSerializer.Serialize(login);
        try
        {
            Constants.Cookies = null;
            Constants.IsServerConnected = false;

            var uri = new Uri($"{Constants.RestBaseUrl}/login.jsp");
            var _RestClient = new RestClient(uri);
            var request = new RestRequest(uri, Method.Post);
            request.AddHeader("Content-Type", "application/json");

            request.AddParameter("application/json", login, ParameterType.RequestBody);

            RestResponse response = await _RestClient.ExecuteAsync(request);

            if (response.IsSuccessStatusCode)
            {
                Constants.Cookies = response.Cookies;
                Constants.IsServerConnected = true;
            }
            return response.IsSuccessStatusCode;
        }
        catch (Exception e)
        {
           // _logger.LogError(e, "LoginError");
            throw;
        }
    }

    public async Task<RootData<T>> RestServiceGetAsync<T>(string model, int offset = 0, int limit = 10)
    {
        try
        {
            var uri = $"{Constants.RestBaseUrl}/ws/rest/{model}";
            var _RestClient = new RestClient(uri);
            var request = new RestRequest(uri, Method.Get);

            request.AddHeader("Content-Type", "application/json");

            if (Constants.Cookies.Any() && Constants.IsServerConnected)
            {
                string cookie = "";
                Constants.Cookies.ToList().ForEach(x => cookie += $"{x.Name}={x.Value}; ");
                request.AddHeader("Cookie", cookie);
            }
            else
            {
                throw new Exception("The server is not connected !");
            }

            request.AddParameter("offset", offset, ParameterType.UrlSegment);
            request.AddParameter("limit", limit, ParameterType.UrlSegment);

            RestResponse response = await _RestClient.ExecuteAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var data = new MemoryStream(Encoding.UTF8.GetBytes(response.Content));
                var rslt = await JsonSerializer.DeserializeAsync<RootData<T>>(data);
                return rslt;
            }
            return null;

        }
        catch (Exception e)
        {
            //_logger.LogError(e, $"GetModelError: {model}");
            throw;
        }
    }

    public async Task<bool> LogoutAsync()
    {
        try
        {
            var uri = $"{Constants.RestBaseUrl}/logout";
            var _RestClient = new RestClient(uri);
            var request = new RestRequest(uri, Method.Get);

            request.AddHeader("Content-Type", "application/json");

            if (Constants.Cookies.Any() && Constants.IsServerConnected)
            {
                string cookie = "";
                Constants.Cookies.ToList().ForEach(x => cookie += $"{x.Name}={x.Value}; ");
                request.AddHeader("Cookie", cookie);
            }
            else
            {
                throw new Exception("The server is not connected !");
            }

            RestResponse response = await _RestClient.ExecuteAsync(request);
            return response.IsSuccessStatusCode;
        }
        catch (Exception e)
        {
            //_logger.LogError(e, "LogoutError");
            throw;
        }
    }
}


text:
Q: Cassandra source code ConfigurationException expection URI in cassandra.config found cassandra.yaml For my master thesis, I have to modify the source code of Cassandra. So, as suggested by https://wiki.apache.org/cassandra/HowToBuild, I git clone, then run ant, and everything seems nice (I managed to build the project without any error), but when I run the unitTests (cassandra/test), I have this strange error:
org.apache.cassandra.exceptions.ConfigurationException:
   Expecting URI in variable: [cassandra.config].
   Found[cassandra.yaml].
   Please prefix the file with [file:\\\] for local files and
      [file:\\<server>\] for remote files.
   If you are executing this from an external tool, it needs
   to set Config.setClientMode(true) to avoid loading configuration.

at org.apache.cassandra.config.YamlConfigurationLoader.getStorageConfigURL(YamlConfigurationLoader.java:80)
    at org.apache.cassandra.config.YamlConfigurationLoader.loadConfig(YamlConfigurationLoader.java:100)
    at org.apache.cassandra.config.DatabaseDescriptor.loadConfig(DatabaseDescriptor.java:252)
    at org.apache.cassandra.config.DatabaseDescriptor.daemonInitialization(DatabaseDescriptor.java:131)
    at org.apache.cassandra.auth.jmx.AuthorizationProxyTest.setup(AuthorizationProxyTest.java:48)"

I would like to test my modifications on the source code with the unitTests (because I didn't find any tutorial of how to set up cassandra from the source code on Windows, so if you have one, I would like to have the link ^^) but I didn't manage to find any solution for this bug :(. Anyone know a solution to this problem?
I am working on Windows 10 with IntelliJ and I have updated my Jdk and ant to the latest version.

A: I was facing the same issue. Those variables ("cassandra.config", "cassandra.storagedir", etc...) are System variables.
You can either set them in your code by doing something like:
System.setProperty("cassandra.config", "file:///<PATH>/cassandra.yaml");

You can also set them whilst running the jar file:
java -Dcassandra.config=file:///<PATH>/cassandra.yaml -jar <JAR>

Best,
Shabir

A: Start a new process in jdk 1.8 and start embedded cassandra in it. and run your junit in your java version. I faced similar isue which jdk11 upgrade. Now i fixed this.
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;

import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmbeddedCassandraApplication {
    public static void main(String[] args) throws Exception {
        EmbeddedCassandraServerHelper.startEmbeddedCassandra("cassandra-test.yaml");
    }
}


text:
Q: Pass URL parameter to frame I have index.html with this content
<frameset rows="100%,*" border="0" frameborder="0">
    <frame name="__main" src="https://mywebsite.com" noresize frameborder="0">
</frameset>

Trying to figure out how I can pass url parameters to the frame. E.g if I open url with ?param1=abc I want frame to open "https://mywebsite.com?param1=abc"
Is it possible with vanilla js?

A: You can use it like this.
iframe = document.getElementById('myIframe');

iframe.src = iframe.src + '?' + params;

A: with jquery use it like this:
let src = 'https://mywebsite.com';
$('#your frame id').prop('src',src);


text:
Q: Add missing values in the list by comparing the other list and vice versa I am trying to add the missing values to the list by comparing the other list. If the data is not present in list_1 which is there in list_2, in same index of list_2 we have to add "Missing" in list_1
list_1 = [('state', 'YES', 'varchar'), ('quantity', 'YES', 'int')]

list_2 = [('name', 'NO', 'varchar'), ('marks', 'YES', 'varchar'), ('state', 'YES', 'int')]

expected output of the lists is
list_1 = [("missing",),("missing",),('state', 'YES', 'varchar'), ('quantity', 'YES', 'int'))]

list_2 = [('name', 'NO', 'varchar'), ('marks', 'YES', 'varchar'), ('state', 'YES', 'int'),("missing",)]

I have tried the below, but its not working.
new_list1 = set(list1).difference(list2)
new_list2 = set(list2.difference(list1)

 for i in new_list1:
     for x in range(len(list_2)):
         if list_2[x][0] == i:
             list_1.insert(x, ("missing",))

 for i in new_list2:
          for x in range(len(list_1)):
         if list_1[x][0] == i:
             list_2.insert(x, ("missing",))

Some one help to resolve this

A: I didn't complete this using your tuple structure, but the general idea should be the same.
list1 = [1,2,3]
list2 = [0,1,7, 2,3]
new = []
for i in range(len(list2)):
    new += ["missing"]
    if list2[i] in list1:
        new[i] = list2[i]

list1 = new
print(list1)

A: It is not really possible to infer the total ordering of all the keys from your two lists, and from your comments, order is not really important anyway. Thus, it would be much easier to use dictionaries instead, mapping the key (the first element of the tuples that you use for deciding equality) to the actual tuples.
>>> d1 = {a: (a,b,c) for a,b,c in list_1}
>>> d2 = {a: (a,b,c) for a,b,c in list_2}

You can then easily get all the keys from both (or any number of) dictianaries and use a dictionary comprehension to get the final dict with "missing" values.
>>> all_keys = set(d1) | set(d2)
>>> {k: d1.get(k, "missing") for k in all_keys}
{'quantity': ('quantity', 'YES', 'int'),
 'marks': 'missing',
 'name': 'missing',
 'state': ('state', 'YES', 'varchar')}

And analogeously for list_2. Of course, you can also use a list comprehension. It will be more difficult to know which items are missing, but corresponding items will be in the same position, although not necessarily the same (relative) positions as in the original lists.
>>> [d1.get(k, "missing") for k in all_keys]
[('quantity', 'YES', 'int'), 'missing', 'missing', ('state', 'YES', 'varchar')]
>>> [d2.get(k, "missing") for k in all_keys]
['missing', ('marks', 'YES', 'varchar'), ('name', 'NO', 'varchar'), ('state', 'YES', 'int')]


text:
Q: How to start an executable from console and read the output with Qt I want to start an executable from Qt, on cmd and then read the output of it.
Do I have to use WinAPI for this; such as CreateProcess()?
I used QProcess and it worked fine on Windows 10, however it does not work with Windows CE. Here is the sample code that works on desktop;
    QProcess p;
    p.start(path, arg);
    p.waitForFinished();
    std::string output = p.readAll();

A: Try this class(Some error checks were omitted)
#pragma once
#include <windows.h>
#include <thread>
#include <iostream>
#include <sstream>
#define BUFSIZE 4096
class m_Process
{
public:
    m_Process();
    ~m_Process();
    BOOL start(char* path, char* cmd);
    void waitForFinished();
    std::string readAll();

private:
    HANDLE hProcess;
    HANDLE hRead;
    HANDLE hWrite;
    std::ostringstream stream;
    friend void ReadFromPipe(m_Process* Process);
};

void ReadFromPipe(m_Process* Process)
{
    DWORD dwRead;
    CHAR chBuf[BUFSIZE];
    BOOL bSuccess = FALSE;
    Process->stream.clear();
    for (;;)
    {
        bSuccess = ReadFile(Process->hRead, chBuf, BUFSIZE-1, &dwRead, NULL);
        if (!bSuccess || dwRead == 0) break;
        chBuf[dwRead] = 0;
        Process->stream << chBuf;
    }
}

m_Process::m_Process()
{
    hProcess = NULL;
    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;
    CreatePipe(&hRead, &hWrite, &saAttr, 0);
    SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
}

m_Process::~m_Process()
{
    if(hRead)
        CloseHandle(hRead);
    if (hWrite)
        CloseHandle(hWrite);
    CloseHandle(hProcess);
    stream.clear();
}

BOOL m_Process::start(char * path, char * cmd)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    si.dwFlags = STARTF_USESTDHANDLES;
    si.wShowWindow = TRUE;
    si.hStdOutput = hWrite;
    si.hStdError = hWrite;
    BOOL ret = CreateProcess(path, cmd, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
    CloseHandle(hWrite);
    hWrite = NULL;
    std::thread t(&ReadFromPipe,this);
    t.join();
    if (ret)
        hProcess = pi.hProcess;
    return ret;
}

void m_Process::waitForFinished()
{
    if (hProcess)
        WaitForSingleObject(hProcess, INFINITE);
}

std::string m_Process::readAll()
{
    return stream.str();
}

Usage:
m_Process p;
p.start(path, arg);
p.waitForFinished();
std::string output = p.readAll();

A: QT 4.8 documentation states
Note: On Windows CE and Symbian, reading and writing to a process is not supported.


text:
Q: MySQL - checking if column exists if not create it in Java I've spent a few hours researching on how to create a Java method that will help with my program. I am very new to MySQL, so I am not the most experienced person out there.
What I am trying to do is write a Java method that checks if a column that has the is named after a username exists inside of a table. If it does not exists, it will create that column.
I have seen lot's of tutorials on the internet about similar solutions to my problem. I don't see how I am supposed to implement the TABLE_SCHEMA into a java method since I only know the very basics of MySql.
It would be nice to see how to implement this or some other solution into the Java method. I've mostly erased my previous work since I could not figure it out, so sorry if I need to show that(This is my first question.)
Edit:
        try {
        ResultSet res = conn.createStatement()
                .executeQuery("ALTER TABLE `package_table` ADD " + username + "  VARCHAR(15);");
        if (!res.next()) {
            conn.createStatement()
                    .executeUpdate("INSERT INTO `package_table` (`uuid`, `name`, `packages`) VALUE ('"
                            + event.getPlayer().getUniqueId() + "', '" + event.getPlayer().getName() + "', '" + "" + "');");
        }
    } catch (SQLException e) {
        e.printStackTrace();
        try {
            conn.close();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

Edit2:
 The reason I need to do columns is that I need to store the 'packages' a username has. There can be "infinite" amounts of packages.
Thanks,
Jack

A: You can do it using jdbc. Just get column names and then add one if you need.
Something like this:
Connection con;
Statement st;
ResultSet rs;

try {
  Class.forName("com.mysql.jdbc.Driver");
  con = DriverManager.getConnection(
      "jdbc:mysql://localhost:3306/dbname",
      "dbuser",
      "bdpass"
  );

  st = con.createStatement();

  String sql = "select * from table";
  rs = st.executeQuery(sql);
  ResultSetMetaData metaData = rs.getMetaData();
  int rowCount = metaData.getColumnCount();

  boolean isMyColumnPresent = false;
  String myColumnName = "myColumnName";
  for (int i = 1; i <= rowCount; i++) {
    if (myColumnName.equals(metaData.getColumnName(i))) {
      isMyColumnPresent = true;
    }
  }

  if (!isMyColumnPresent) {
    String myColumnType = "some type";
    st.executeUpdate("ALTER TABLE table ADD " + myColumnName + " " + myColumnType);
  }
} catch (Exception e) {
  e.printStackTrace();
}

A: You can do something like this,
DatabaseMetaData  metadata = conn.getMetaData();
Resultset rs = null;
  rs=metadata.getColumns(null, null, "package_table", null);
boolean found=false;

         while (rs.next()) {

               if(username.equals(rs.getString("COLUMN_NAME"))
              {
              found=true;
              }

             }

       if(found){
       //Skip column creation
       }else{
       //Create column
      }


text:
Q: Custom UserControl events I have an UserControl defined as follows:
<UserControl x:Class="Speaker.View.Controls.Prompt"
         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:conv="clr-namespace:Speaker.View.Converters"
         mc:Ignorable="d" Height="Auto" Width="300" x:Name="PromptBox">
<UserControl.Resources>
    <conv:VisibilityConverter x:Key="VConverter" />
</UserControl.Resources>
<Border Background="White" Padding="10" BorderThickness="1"
        BorderBrush="Gray" CornerRadius="10" Height="80"
        Visibility="{Binding Path=Show, ElementName=PromptBox,
                             Converter={StaticResource VConverter}}"
        UseLayoutRounding="True">
    <Border.Effect>
        <DropShadowEffect BlurRadius="20" RenderingBias="Quality" />
    </Border.Effect>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="20" />
            <RowDefinition Height="10" />
            <RowDefinition Height="20" />
        </Grid.RowDefinitions>

        <TextBox x:Name="InputText" Width="Auto" Height="20"
                 Text="{Binding Path=InfoText, ElementName=PromptBox, Mode=OneWay}"
                 Grid.Row="0" BorderThickness="0" Foreground="#FF8D8D8D"
                 GotFocus="InputText_GotFocus" LostFocus="InputText_LostFocus" />
        <Separator Grid.Row="1" />
        <Button Content="{Binding Path=ButtonText, ElementName=PromptBox}" Grid.Row="2"
                Width="100" Command="{Binding Path=OkCommand, ElementName=PromptBox}" />
    </Grid>
</Border>

What I want to do is this:
when the user clicks on the button, I'd like to run some code (obviously :) ) - this control will be used in some other controls / windows, and the code I'd like to run will be different depending on a scenarion. So how do I bind the Command property of this button with some custom command? Example usage:
<ctrls:Prompt Show="{Binding ShouldLogIn}" ButtonText="{Binding LogInText}"
              InfoText="{Binding LogInInfo}" OkCommand="what goes here???" Grid.Row="0" Grid.ZIndex="2" />

Also - I follow the MVVM patern, using the MVVMLight fw, so I'd like the solution to follow it as well.
So the question is - How do I bind to the Button.Command from outside of the prompt control?

A: I would also suggest making a CustomControl, but if you want to use your UserControl you will need to add a DependencyProperty in your code behind.
public partial class Prompt : UserControl
{
    private bool _canExecute;
    private EventHandler _canExecuteChanged;

    /// <summary>
    /// DependencyProperty for the OKCommand property.
    /// </summary>
    public static readonly DependencyProperty OKCommandProperty = DependencyProperty.Register("OKCommand", typeof(ICommand), typeof(Prompt), new PropertyMetadata(OnOKCommandChanged));

    /// <summary>
    /// Gets or sets the command to invoke when the OKButton is pressed.
    /// </summary>
    public ICommand OKCommand
    {
        get { return (ICommand)GetValue(OKCommandProperty); }
        set { SetValue(OKCommandProperty, value); }
    }

    /// <summary>
    /// Gets a value that becomes the return value of
    /// System.Windows.UIElement.IsEnabled in derived classes.
    /// </summary>
    protected override bool IsEnabledCore
    {
        get { return base.IsEnabledCore && _canExecute; }
    }

    // Command dependency property change callback.
    private static void OnOKCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Prompt p = (Prompt)d;
        p.HookUpCommand((ICommand)e.OldValue, (ICommand)e.NewValue);
    }

    public Prompt()
    {
        InitializeComponent();
    }

    // Add the command.
    private void AddCommand(ICommand command)
    {
        EventHandler handler = new EventHandler(CanExecuteChanged);
        _canExecuteChanged = handler;
        if (command != null)
            command.CanExecuteChanged += _canExecuteChanged;
    }

   private void CanExecuteChanged(object sender, EventArgs e)
    {
        if (OKCommand != null)
            _canExecute = OKCommand.CanExecute(null);

        CoerceValue(UIElement.IsEnabledProperty);
    }

    // Add a new command to the Command Property.
    private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
    {
        // If oldCommand is not null, then we need to remove the handlers.
        if (oldCommand != null)
            RemoveCommand(oldCommand);

        AddCommand(newCommand);
    }

    // Remove an old command from the Command Property.
    private void RemoveCommand(ICommand command)
    {
        EventHandler handler = CanExecuteChanged;
        command.CanExecuteChanged -= handler;
    }
}


text:
Q: Black Jack Game in Java Problem statement
I have another thread on this, but I can't seem to locate it. Basically, I have a Black Jack game. The user is given two random cards (then those cards are added together, and display the total). Then it prompts user if they want another card (They pretty much will want to have a total lower than 21). If they choose "yes," they are given a random card number (they can keep getting a card, but should avoid going over 21), but if they choose "no," the game stops.
Here's the output I should get: [blackjackoutput.jpg]
And here's what I'm getting: [output1.jpg]
Source code:
public class BlackJackGame {
    public static void main(String[] args) {
        int randomnum1 = (int) (1 + Math.random() * 10);
        int randomnum2 = (int) (1 + Math.random() * 10);
        int total;
        char anotherCard = 'y';
        char playAgain;
        Scanner input = new Scanner(System.in);

        // Prints cards player starts off with
        System.out.println("First cards: " + randomnum1 + ", " + randomnum2);

        // Sum of the 2 cards
        total = randomnum1 + randomnum2;

        // Prints Total
        System.out.println("Total: " + total);

        // Do While Loop that asks question to get lower than 21 or terminate.
        while (anotherCard != 'n') {
            if (total <= 21) {
                System.out.print("Do you want another card? (y/n): ");
                anotherCard = input.next().charAt(0);

                int randomnum3 = (int) (1 + Math.random() * 10);
                System.out.println("Card: " + randomnum3);

                total += randomnum3;
                System.out.println("Total: " + total);
            } else if (total > 21) {
                System.out.println("BUST.");

                System.out.print("Would you like to play again? (y/n): ");
                playAgain = input.next().charAt(0);
            }
        }
    }
}

Issue

*

*When I reach to 21, I choose "no," to stop the program. But, it continues to display the next card and the updated total.

*When I "BUST." (Or go over 21). It'll ask me if I want to play. And on separate occasions, I choose "y" and it says "Bust." and asks me if I want to play again (it loops, says "BUST.", and asks me the same question, without being able to end the program). Same thing if I choose "no" it'll say "Bust." and ask me if I can want to play again.

*How do you play the game again?
PLEASE HELP!!!

A: The issue you have is a logic issue here:
 if (total <= 21)
    {
      System.out.print("Do you want another card? (y/n): "); //<--------------
      anotherCard = input.next().charAt(0);

      int randomnum3 = (int) (1 + Math.random() * 10);

      System.out.println("Card: " + randomnum3);

      total += randomnum3;

      System.out.println("Total: " + total);

You need to check if(anotherCard == 'n') to break out of the loop
Side Note
This blackjack game should have a better distribution of random cards better modeled off  a 52 card deck


text:
Q: Migrating MySQL 5.0 to 5.5 - simple databases I have a LAMP server on my LAN running a very old version of RedHat with MySQL 5.0, and I'm trying to migrate it to Ubuntu 12.04 to update it.
I know the advice is to migrate MySQL 5.0 to 5.1 then 5.2, and so on.  However, there are no triggers or stored procedures in these databases, just simple MyISAM and InnoDB tables and indexes.
Can anyone tell me what if I can just export the databases in 5.0 from the RedHat server using phpMyAdmin, and then import them into 5.5 on Ubuntu?
The data is mainly used by PHP to build dynamic web pages.

A: *

*Make full back (preferably mysqldump)

*Follow official guide : http://dev.mysql.com/doc/refman/5.5/en/upgrading.html
and also this one http://dev.mysql.com/doc/refman/5.0/en/upgrading-from-early-5-0.html


text:
Q: iPhone programming: How much data can I store in my app's Documents Directory (root folder)? The reason I ask is my app lets users cache map tiles. Does anyone know the real cap on how much data I can let them store?

A: You can store as much as you want until you run out flash. Having said that, your users probably won't like it if you start eating all of the space on the phone.
Also, make sure you put it in the Cache folder, as opposed to Documents. The Documents folder gets backed up when you sync to iTunes, the Cache folder is not. If you have a ton of data in the Documents folder it will massively slow down iTunes synching.

A: About a year ago the word was there is a 2Gb limit on app size, but you'll be hard pressed to find an "official" declaration of such, even on apple's site or the discussion forums there
That being said 2Gb is pretty hearty for a mobile app, caching and all

A: I'm not aware of any quota for apps using the writable area, but it would be easy enough to check.


text:
Q: Adding a second wireless router to my network I have Verizon DSL service that came with a westell 7500 wireless router, but the wireless does not cover a big enough area.
I also own a linksys wireless router which I would like to place about 75 feet away, up one floor, in order to have complete coverage for the building.
It seems it is not as simple to simply plug the second wireless router into the network, it shows up as a wireless router, but if I connect to it from a laptop I can't get to the internet...
What is the basic steps I need to take in order to inexpensively add a second wireless access point to my network? I don't mind if I need t omanually pick one wireless point versus another, but it would be better if it was possible to just log onto either one and have the laptops talk to whichever router is available.
Thanks.

A: You mention both routers and access points in your question. An access point bridges wireless media to wired media (with many optional bells an whistles, too, on a real access point). A "wireless router" provides access point functionality along with additional functions to route TCP/IP between subnets (and provide network address translation, etc). I don't think you're looking for a second TCP/IP subnet and routing between it and your existing LAN subnet. I think you just want an access point, and you can use another router as a cheap access point.
Go get a second wireless router, and configure it as follows:

*

*Plug one of your computers into the new router's wired Ethernet ports w/ nothing else connected on the new router.

*Configure the new router to disable its DHCP server, and with an IP address that's in the existing TCP/IP subnet that your current network uses.

*Configure the wireless Ethernet functionality on the new router to match your existing router's SSID and encryption settings.

*Set the WAN interface on the new router to "DHCP client" and forget about it -- put a piece of tape over the port or something similar so you never plug anything into it.

*Disconnect your computer from the new router and plug one of the LAN ports on the new router into your LAN.

*The new router will bridge the wireless segment to the wired LAN, and clients of the new router will get DHCP and Internet access from wherever current wireless clients get DHCP.

We've done this fairly frequently with one Customer who wanted access points "on the cheap" by using Linksys WRT54G wireless routers and, through the procedure above, effectively disabling their "routing" functionality and just using them as wireless access points.
Alternatively, if you want to spend a little more money go get a wireless access point that doesn't have router functionality. It will need less configuration but will be a little more expensive. (Market dynamics are at play there... There's less demand for low-end access points than routers so the price of an access points ends up being higher than a router even though an access point "does less".)

A: I'm not sure about the standard Linksys firmware, but DD-WRT supports AP mode. You could use your Linksys router as a secondary router running in Access Point mode, though I think you might have to connect the two routers via wire as opposed to wireless.

A: The DD-WRT suports Repeater Mode, just take the other SSID and spam the coverage..


text:
Q: Different scale in bar plot I am creating a bar plot for a situation, however the scale of each bar is different and should be represented in the scale of 10. My code is:
\documentclass[runningheads]{llncs}
\usepackage{graphicx}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}

    \pgfplotscreateplotcyclelist{gray}{ % define a new cycle list
     {fill=black!20},
     {fill=black!40},
     {fill=black!60}
    }

    \begin{tikzpicture}
    \begin{axis}[
      ymin = 0, ymax = 25,
      ybar,
      bar width=17, % added
      enlarge x limits=0.3,
      legend  style={at={(0.7 ,1)},
      anchor=north,legend  columns =-1},
      ylabel ={Gas Cost and Price in ETH},
      xlabel ={Sources Quantity},
      symbolic x coords ={7,14,21},
      xtick=data,
      nodes  near  coords ,
      nodes  near  coords  align ={vertical},
      nodes near coords style={font=\tiny}, % reduce font size of nodes near coords
      cycle list name=gray, % use the new cycle list
    ]

    \addplot  coordinates  {(7,11) (14,15) (21,19)};
    \addplot  coordinates  {(7,5) (14,7) (21,9)};

     \addlegendentry{Gas}
     \addlegendentry{ETH}
    \end{axis}
    \end{tikzpicture}
\end{document}

My values are:
%7:   0.11449906 ETH - 5 724 953 Gas
%14: 0.153421 ETH     - 7 671 050 Gas
%21: 0.1962195 ETH -  9 810 975 Gas

*

*How could I represent the value shown above the bars on a scale of ten (i.e., 5.75 * 10⁶)

A: Another option would be to read the values into a table, and do some scaling here and there with visualization depends on and y expr.
\documentclass[border=5mm]{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.16}
\begin{document}

    \pgfplotscreateplotcyclelist{gray}{ % define a new cycle list
     {fill=black!20},
     {fill=black!40},
     {fill=black!60}
    }

    \begin{tikzpicture}
    \pgfplotstableread{
       p  ETH  gas
       7  0.11449906 5724953
      14 0.153421   7671050
      21 0.1962195  9810975
     }\DataTable
    \begin{axis}[
      ymin = 0, ymax = 25,
      ybar,
      bar width=17pt, % added
      enlarge x limits=0.3,
      legend  style={at={(0.7 ,1)},
      anchor=north,legend  columns =-1},
      ylabel ={Gas Cost and Price in ETH},
      xlabel ={Sources Quantity},
      xtick=data,
      xticklabels from table={\DataTable}{p}, % instead of symbolic coords
      nodes  near  coords  align ={vertical},
      nodes near coords style={font=\tiny}, % reduce font size of nodes near coords
      cycle list name=gray, % use the new cycle list
    ]

     \addplot  +[
       visualization depends on=y*1e-2\as\RawY,
       nodes near coords={\pgfmathprintnumber{\RawY}}
       ]
           table[x expr=\coordindex, y expr=\thisrow{ETH}*1e2] {\DataTable};
     \addplot  +[
       visualization depends on=y*1e6\as\RawY,
       nodes near coords={\pgfmathprintnumber{\RawY}},
       node near coords style={anchor=south west,rotate=45}]
            table[x expr=\coordindex, y expr=\thisrow{gas}*1e-6] {\DataTable};

     \addlegendentry{ETH}
     \addlegendentry{Gas}
    \end{axis}
    \end{tikzpicture}
\end{document}

A: Here is a proposal. Note that I had to add dimensions to the bar width in order to be able to compile it with the most recent version of pgfplots.
\documentclass[border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}

    \pgfplotscreateplotcyclelist{gray}{ % define a new cycle list
     {fill=black!20},
     {fill=black!40},
     {fill=black!60}
    }

    \begin{tikzpicture}
    \begin{axis}[
      ymin = 0, ymax = 25,
      ybar,
      bar width=17pt, % added
      enlarge x limits=0.3,
      legend  style={at={(0.7 ,1)},
      anchor=north,legend  columns =-1},
      ylabel ={Gas Cost and Price in ETH},
      xlabel ={Sources Quantity},
      symbolic x coords ={7,14,21},
      xtick=data,
      nodes  near  coords  align ={vertical},
      nodes near coords style={font=\tiny}, % reduce font size of nodes near coords
      cycle list name=gray, % use the new cycle list
    ]
    %7:   0.11449906 ETH - 5 724 953 Gas
    %14: 0.153421 ETH     - 7 671 050 Gas
    %21: 0.1962195 ETH -  9 810 975 Gas
    \edef\myLstA{0.11449906,0.153421,0.1962195}
    \addplot+[nodes  near  coords=\pgfmathparse{{\myLstA}[\coordindex]}%
      \pgfmathprintnumber{\pgfmathresult}]  coordinates  {(7,11) (14,15) (21,19)};
    \edef\myLstB{5724953,7671050,9810975}
    \addplot+[nodes  near  coords=\pgfmathparse{{\myLstB}[\coordindex]}%
      \pgfmathprintnumber{\pgfmathresult},
      nodes near coords style={xshift=1.5ex,yshift=3.5ex,rotate=70}]  coordinates  {(7,5) (14,7) (21,9)};

     \addlegendentry{Gas}
     \addlegendentry{ETH}
    \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: refactoring nested if statements I'm trying to refactor some code that looks similar to the code below. I feel that there should be a simpler way to do what it does. My main concern is the call to getDataB() in both if and else blocks of the (!dataA.isEmpty()) condition.
    DataA dataA = getDataA();

    if (!dataA.isEmpty()) {

        if (dataA.getStatus() == Status.FINAL) {
            // process finalized dataA
        }

        if (dataA.getStatus() == Status.RECEIVED) {
            DataB dataB = getDataB();
            if (!dataB.isEmpty()) {
                dataA.setStatus(dataB.getStatus());
                // process dataA with updated status from dataB
            }
        }

        if (dataA.getStatus() == STATUS.IN_PROGRESS) {
            // process in progress dataA
        }

    // empty dataA
    } else {
        Datab dataB = getDataB();
        if (!dataB.isEmpty()) {
            // process dataB
        }
    }

A: There is still room for improvement, but as an initial refactoring you can do something like this:
// I like to get rid of the negations, assuming that DataA and DataB are your objects.
// I would normally declare a method with more meaning, like hasData(), otherwise just use the negation and the isEmpty.

DataA dataA = getDataA();
DataB dataB = getDataB();

// When DataA has data
if (dataA.hasData()) {
    Status statusA = dataA.getStatus();

    switch(statusA) {
        case Status.FINAL:
            // process finalized dataA
            break;
        case Status.RECEIVED:
            if (dataB.hasData()) {
                dataA.setStatus(dataB.getStatus());
                // process dataA with updated status from dataB
            }
            break; // If you want to process dataA in progress after setting the dataB status in A, then remove this break.
        case Status.IN_PROGRESS:
            // process in progress dataA
            break;
    }

// When DataB has data
} else if (dataB.hasData()) {
    // process dataB
}

A: First, take the processing of dataB (present in the bottom else in your code) out in its own function like:
private void processDataB() {
    DataB dataB = getDataB();
    if (dataB.isEmpty()) return;
    // process dataB
}

Notice how we inverted the if condition to return from the method if dataB is empty.
Next, apply the same inverting of if to the main code. The new code will look like:
DataA dataA = getDataA();
if (dataA.isEmpty()) { //Inverted the test.
    processDataB();
    return;
}

if (dataA.getStatus() == Status.FINAL) {
    // process finalized dataA
}

if (dataA.getStatus() == Status.RECEIVED) {
    DataB dataB = getDataB();
    if (!dataB.isEmpty()) {
        dataA.setStatus(dataB.getStatus());
        // process dataA with updated status from dataB
    }
}

if (dataA.getStatus() == STATUS.IN_PROGRESS) {
    // process in progress dataA
}

A: You can move the duplicate logic to a method that accepts a lambda:
void processDataB(Consumer<DataB> action) {
    DataB dataB = getDataB();
    if (!dataB.isEmpty()) {
        action.accept(dataB);
    }
}

Then call it like this:
//...
    if (dataA.getStatus() == Status.RECEIVED) {
        processDataB(dataB -> {
            dataA.setStatus(dataB.getStatus());
            // process dataA with updated status from dataB
        });
    }
//...
} else {
    processDataB(dataB ->
        // process dataB
    });
}


text:
Q: Link to the current page with a specific get url param I have a page which by default has a plain looking theme.  In order to swap between one of 5 themes the url parameter agency=x where is the name of the theme must set.
So if the default url of my page was
http://127.0.0.1:8888/index.html?&some.param=123&someother.param=321
I need to have a url that would link to
http://127.0.0.1:8888/index.html?&some.param=123&someotherparam=321&agency=2
Keep in mind that some.param and someother.param are arbitrary, users could hit this page with all sorts of crazy get params, I just need to (if possible) link to itself with the addtional get parameter.
I can always render this out dynamically via a servlet or jsp but if there is a way to do this with standard links/hrefs it would be much better.
Any ideas?

A: It's a bit of both, but I would do, in the <head> element:
<link rel="stylesheet" type="text/css" href="agency<%= the agency %>.css" />

And have agency.css for the default, agency1.css for theme 1 and so on.

A: You could do this with javascript.
On all hrefs add an onclick callback (using document.getElementsByTagName('a')) which parses window.location and adds it to the href on the fly.


text:
Q: Using .Net Core with OpenGL on LInux Can I use OpenGL in .Net Core on Linux. I asking, because I encountered a few problems...
If not, which library can I use?

A: There are quite a few options out there. In general, OpenGL is portable across systems and cards, but there are always implementation quirks. Are you following a tutorial, or are trying to port something from Windows or .NET Full Framework to Linux and/or .NET Core?
If you are trying to games related stuff (as many people doing graphics are), then you might want to check out MonoGame, as it will give you graphics access and a good starting point for games. This project is derived from an old unmaintained Microsoft project called XNA.
If you are going lower level, I'm sure there are countless libraries. There is a C/C++ library called  Simple Direct Media Layer (SDL) which I'm sure has many C# wrappers,  here's what I found on Nuget.org. You can also just search "C# .NET SDL Simple Direct Media Layer Wrapper" and find something that looks good for your use case.
SDL is great to learn because it is widely used library that makes writing portable graphics-related code easier, but still is quite minimal.


text:
Q: Fluent nHibernate - Flatten Entities to ViewModel I am using FluentNHibernate with AutoMapping and conventions to create my database.
I have 3 tables - Person, Address and Job as shown below.
    //Database table
  public class Person()
  {
    public virtual int Id { get; set; }
    public virtual string FirestName { get; set; }
    public virtual string SecondName { get; set; }

    public virtual PersonAddress Address { get; set; }
    public virtual PersonJob Job { get; set; }
  }

  //Database table
  public class PersonAddress()
  {
    public virtual int Id { get; set; }
    public virtual string AddressLine1 { get; set; }
    public virtual string AddressLine2 { get; set; }
    public virtual string AddressLine3 { get; set; }
  }

  //Database table
  public class PersonJob()
  {
    public virtual int Id { get; set; }
    public virtual int Description { get; set; }
  }

I want to display a list of Person details in a Grid using a flattened view model below.
Do I have to create a Mapping for ViewModelPerson even though its not a database table (will Automapping affect this) or should  I do this using a nHibernate query to create get the list of ViewModelPerson entities.
  //NOT database table - only used as ViewModel
  public class ViewModelPerson()
  {
    public virtual int PersonId { get; set; }
    public virtual string FirestName { get; set; }
    public virtual string SecondName { get; set; }

    //AddressLine1 + AddressLine2 + AddressLine3
    public virtual int AddressId { get; set; }
    public virtual string Address { get; set; }

    public virtual int JobId { get; set; }
    public virtual string Job { get; set; }
  }

A: Let me give you my view, the approach I do believe in...
Data Layer - The mapping Entity vs Table is a Data layer related. It is just a way, how to later profit from ORM tool like NHibernate. All the CRUD operations are generated for us - reflecting the mapping.
Presentation Layer - The ViewModel, should help us to "map" the Entity(-ies) to Client View. So while in many simple scenarios will: Entity, Table, ViewModel .. (e.g. Country or Currency) match 1-1, we are ready to handle it differently in more complex scenarios.
The above scenario Displaying Person, Address, Jobs at one View - is a complex one. Can we profit from separation, indirect filling of the ViewModel?
Suggestion: Fill the ViewModel on a Service layer using queries to underlying Business model
The first benefit I see, is that the population of the ViewModelPerson is in our hands. It is not fixed inside of the mapping. We can reduce amount of data (even use Projections to load less data) and we can even extend it (load City from some CodeList)
The second benefit is that if we will need to change something, e.g. introduce async loading of the Addresses, we have to change it only from the Service layer UP (in MVC Controller, Model and View) while the data layer (mapping is untouched)


text:
Q: Remove columns from a matrix after performing a computation Suppose I have a matrix A with 10 values.
And each of these values exist in separate cells:
A = [A{1}, A{2}, A{3}, A{4}, A{5}, A{6}, A{7}, A{8}, A{9}, A{10}

Suppose I apply a strange made-up function to this matrix (strangef, please don't worry too much about what this function actually does! ;) ) which ends up giving me 10 non-identical values:
B = strangef(A);
B(1,:) = [1.3, 4.2, 1.0, 2.3, 6.4, 0.9, 4.5, 2.6, 7.1, 3.1]

Then I look to find the minimum value in B:
c = find(B==min(min(B)))

I find that it's the 6th value of A, so now I want to reconstruct my matrix so that it excludes this 6th value, as in:
A = [A{1}, A{2}, A{3}, A{4}, A{5}, A{7}, A{8}, A{9}, A{10}]

I can construct this new matrix using an index as follows:
col = 10; %number of columns
index = setdiff(1:col, c);

However while I can use the c (column value) on the first iteration of the loop my new matrix is missing one value if the minimum value of this new matrix is A{3} the column value in this new matrix that has only 9 columns is 2.
Therefore I actually end up creating this matrix:
A = [A{1}, A{3}, A{4}, A{5}, A{7}, A{8}, A{9}, A{10}]

rather than this one:
A = [A{1}, A{2}, A{4}, A{5}, A{7}, A{8}, A{9}, A{10}]

Here's some pseudocode
excludingMinimums = [];
col = 10;

while col>1
      index = setdiff(1:col,excludingMinimum)
      for i = 1:col
          A = [A{i}]
      end
      B = strangef(A)
      c = find(B==min(min(B)))
      excludingMinimums = [excludingMinimums, c]
      col = col - 1;
end

A: Logical indexing makes it much simpler than you think:
B = strangef(A);
A = A(:, B~=min(B));

We can keep track of the remaining columns similarly:
col = 1:size(A,2);
while length(col)>1
    B = strangef(A);
    idx = (B == min(B));
    col = col(idx);
    A = A(:, ~idx);
end

A: How about something like this instead: keep a running copy of your shrinking A.  Deleting is easier than reconstructing with missing elements.
while size(A,2)>1
    B = strangef(A);
    c = find(min(min(B)));
    A(c) = [];   % delete the element from A
    excludingMinimums = [excludingMinimums c];  % save this vector for future output?
end

Note the () notation for deletion, even though A is a cell.


text:
Q: Distance Between 2 Coordinates Using the query below in SQL, I am trying to get the distance between the source and target coordinates:
DECLARE @source geography = 'POINT(42.3629 -121.3897)'
DECLARE @target geography = 'POINT(47.2921 -111.469)'
SELECT @source.STDistance(@target)

However, I get the following error:
> Msg 6522, Level 16, State 1, Line 55 A .NET Framework error occurred
> during execution of user-defined routine or aggregate "geography":
> System.FormatException: 24201:
> Latitude values must be between -90 and 90 degrees.

The error is stating that my latitude values are out of range, but the 42 and 47 values are well within. This code works whenever the longitude is reduced to something within the specified latitude range.
Where is the incorrect conversion happening?

A: WKT format used to represent Geography values uses (X Y) coordinate order, which is typically mapped to (longitude latitude). MS SQL uses this order too, see example of this format usage here:
https://learn.microsoft.com/en-us/sql/t-sql/spatial-geography/spatial-types-geography?view=sql-server-ver15
So you have lat/lng order swapped, use  'POINT(-121.3897 42.3629)' instead.


text:
Q: If $S$ is a free $R$-algebra, then no element of $S$ is integral over $R$? And other questions. Suppose $R$ and $S$ are commutative rings.

*

*If $S$ is any $R$-algebra (not necessarily finitely generated), then every element of $S$ is written as a polynomial with coefficients in $R$ ?

*If $s \in S$ is integral over $R$, then there exists a monic polynomial over $R$, say $p(x) \in R[x]$, such that $p(s)=0$. So, if $S$ is a free $R$-algebra, then no element of $S$ is integral over $R$?


text:
Q: How to assign multiple values for a matrix in R? I have a 93060-by-141 matrix file with filled values.
I need to assign zeros to some rows and columns with the condition: Row 1: 65 of column 1; row 67:131 of column 2; row 133:197 of column 3 and so on.
This condition excludes for some column, i.e the values in rows of column 10,20,36 are unchanged.
I think I will need a For-loop. But I have no idea how to code for the link of rows and columns expressing the mentioned condition.

A: You can change multiple values by providing a matrix of indexes to a matrix.  The indices correspond with the row (first column) and column (second column) numbers of the cells.  For example doing mymat[cbind(1:10, 1)] <- 0 would change the first through tenth rows of column 1 to zero. In you case, you could put together several such cbind() statements with a call to rbind().  For example, mymat[rbind(cbind(1:5, 1), cbind(6:10, 2))] <- 0 would change the first through fifth rows of column 1 and the sixth through tenth rows of column 2 to zero.  In the example you proposed above, it would be something like this:
my_mat[rbind(
  cbind(1:65, 1),
  cbind(67:131, 2),
  cbind(133:197,3))] <- 0


text:
Q: Return two values from for loop in Kotlin I am trying to return two values from the array with the for loop, but am only getting the first value instead.
data class Batches(
    var qty: Int?,
    var entries: List<TruckEntry>?,
    var entryIds: ArrayList<String>?,
    var priceconfig: PriceConfig?

) {
    constructor() : this(0, null, null, null)
}

data class TruckEntry(var name: String?, var id: String?, var qty: Int?, var observed: Int?) {
    constructor() : this(null, null, null, null)
}

My function:
private fun getBatchName(batches: Batches): String? {
                  if (!batches.entries.isNullOrEmpty()) {
                    val entrySize = arrayOf(batches.entries!!)
                    for(index in 0..entrySize.size - 1){
                        return batches.entries!![index].name
                    }
                }
                      return "****************"

    }

A: Return always exits the function with a value or null. You need to store the value found inside the loop in a variable and return it at the end of the function with the other value you want.
I'm not a kotlin programmer, so here is a pseudo code which might help you.
//A class that will hold your return values
//as you can only return one value from a function once

class Holder{
  constructor(data1, data2){
    this.returnValue1 = data1
    this.returnValue2 = data2
  }
}

function yourFunction(batches){
  var data1
  var data2 = "whatever"

  for( batch in batches ){
    if( condition ){
      data1 = batch
      break
    }
  }

  return new Holder(data1, data2)
}

Also when accessing this values from another functions/classes you need to access these according to your Holder class. Like
var returnVal = yourFunction(batches)
var val1 = returnVal.returnValue1

A: If you want to return more than one thing from a function, you need to return something that can hold multiple values, such as a Pair, Triple, or List. List makes the most sense in this case since you don't know for sure how many values there will be.
Example:
private fun getBatchNames(batches: Batches): List<String?> {
    return batches.entries.orEmpty()
        .map { it.name }
}


text:
Q: Faster way for migration of delta Data from one DB to another in Postgres using Java I am having a process that migrates data from one Postgres DB to another Postgres DB. It does so by looping over certain tables. Currently, I am using pg_dump and pg_restore through Java code in my application and the migration is considerably fast. However, for each execution, it transfers the complete data from Table 1 in DB 1 to its equivalent in DB 2 irrespective of what is already present in DB 2.
Is there any faster way that helps me to decide what data I must migrate to avoid copying files that already exists in DB2? These databases can be in the same cluster or different also. I want to explore the concept of parallel loading here but still, I need to avoid copying already existing files.
Please help me here and let me know if anything is required.


text:
Q: How to make React input a text and select? I am trying to make my react-bootstrap form-control/input to allow both text and select. So, when an user clicks on the input box, the user have the options to type the values themselves, or select one of the options that popup when input box is clicked. I am using this as my form (https://react-bootstrap.github.io/components/forms/).
I was able to get it working by using autoComplete and datalist:
<Form.Group as={Col}>
    <Form.Label>Number</Form.Label>
    <Form.Control id="number" name="number" list="numberList"
                   autoComplete="new-password" value={number} onChange={this.handleChange}>
    </Form.Control>
    <datalist id="numberList">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
    </datalist>
</Form.Group>

However, I was wondering if there's a different way to achieve this.


text: Q: R google maps, ggmap - rendering pdf files is very slow, is there a way make an efficient pdf file? I'm currently using the get_map function from package ggmap to grab a google map, I then use ggmap and annotate to add points to the plot.  For each call to annotate there is roughly 1000 points being added, and I call annotate around 100 times.  After saving the output to pdf the rendering and subsequent interaction with the pdf is very slow.  Is there a good way to save to pdf from the quartz or X11 device that will have the same resolution but render faster?  And/Or is there a way of using ggmap to create efficient maps?


text:
Q: Jquery script sometimes work, sometimes doesn't I made script for my ASP.net page to validate values of few textboxes. The thing is, sometimes script works, sometimes do not. Here is my script:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <script type="text/javascript"></script>
   <script>
       $(document).ready(function () {

           var _t1 = $(document.getElementById("<%=textbox5.ClientID%>"));
           var _t2 = $(document.getElementById("<%=textbox4.ClientID%>"));
           var _t3 = $(document.getElementById("<%=textbox10.ClientID%>"));
           var _t4 = $(document.getElementById("<%=textbox9.ClientID%>"));
           var _t5 = $(document.getElementById("<%=textbox15.ClientID%>"));
           var _t6 = $(document.getElementById("<%=textbox14.ClientID%>"));

           var _tLabel = $(document.getElementById("<%=IsMatch.ClientID%>"));

           if (_t1.val() < _t2.val()) {
               $(_tLabel).fadeIn('fast');
               $(_tLabel).html('ERROR ');
               $("#tg-yw4l-1").css("background-color", "red");
           }
           else if (_t3.val() < _t4.val()) {
               $(_tLabel).fadeIn('fast');
               $(_tLabel).html('ERROR');
               $("#tg-yw4l-2").css("background-color", "red");
           }
           else if (_t5.val() < _t6.val()) {
               $(_tLabel).fadeIn('fast');
               $(_tLabel).html('ERROR');
               $("#tg-yw4l-3").css("background-color", "red");
           }
           else {
               $(_tLabel).fadeOut('fast');
           }
       });
       </script>

What happens is that sometimes if requirements for error are met, it won't show error message and change backround.


text:
Q: The dimension of the SU(2) matrix group Let's take the matrix $R = \begin{pmatrix} a & b \\ c & d \end{pmatrix}$.
Consider its transpose $R^\dagger = \begin{pmatrix} a^* & c^* \\ b^* & d^* \end{pmatrix}$.
Then $RR^\dagger =1$ implies that $|a|^2 + |c|^2 = 1, |b|^2 + |d|^2 = 1, ab^* + cd^* = 0,$ and $a^*b + c^*d = 0$.
The last two equations are equivalent to each other, so we have three complex equations.
If $a=a_0+ia_1, b=b_0+ib_1, c=c_0+ic_1,$ and $d=d_0+id_1$, then the above three complex equations lead to $a_0^2 + a_1^2+c_0^2+c_1^2=1, b_0^2 + b_1^2+d_0^2+d_1^2=1, a_{0}b_{0} + a_{1}b_{1} + c_{0}d_{0} + c_{1}d_{1} = 0,$ and $a_{0}b_{1} - a_{1}b_{0} + c_{1}d_{0} - c_{0}d_{1} = 0$.
Therefore, the three complex equations lead to four real equations (the first two equations have only real components, but the final equation has both real and complex components).
Therefore, the four real equations ensure that the number of real variables that parametrise the matrix $R$ drops from 8 to 4.
Now, let's consider the determinant equation $ad-bc=1$, which decomposes into $(a_{0}d_{0} - a_{1}d_{1} - b_{0}c_{0} + b_{1}c_{1}) + i(a_{1}d_{0} + a_{0}d_{1} - b_{1}c_{0} - b_{0}c_{1}) = 1,$ which decomposes into $a_{0}d_{0} - a_{1}d_{1} - b_{0}c_{0} + b_{1}c_{1} = 1,$ and $a_{1}d_{0} + a_{0}d_{1} - b_{1}c_{0} - b_{0}c_{1} = 0$.
Therefore, we have two real equations, so the number of parameters that characterise the matrix $R$ should now drop from 4 to 2. But several sources mention that the number of parameters drop from 4 to 3.
Can someone explain?

A: The explanation is that the determinant is already constrained to be on the unit circle.  We have $|\det(R)|^2 = \det(R)\overline{\det(R)} = \det(R)\det(R^\dagger) = \det(RR^\dagger) =\det(I) = 1$.
This means that the equation $a_0d_0 - a_1d_1 - b_0c_0 + b_1c_1 = 1$ implies $a_0d_1 + a_1d_0 - b_0c_1 - b_1c_0 = 0$, and the latter equation  implies $a_0d_0 - a_1d_1 - b_0c_0 + b_1c_1 = \pm 1$.  In other words, the set of five real equations has a nontrivial relation, which increases the dimension of the solution set.
Another way of looking at it is that the determinant gives a homomorphism $U(2) \to S^1$, and the first isomorphism theorem then guarantees that the dimension of the kernel $SU(2)$ is the dimension of the source minus the dimension of the image.


text:
Q: Getting a web-server error in Eclipse that is Usage: java javassist.tools.web.Webserver  In Eclipse when I'm trying to run my project as java project I'm getting an error like this

Usage: java javassist.tools.web.Webserver

and nothing happens. Not showing any problems or anything.

A: Are you sure you are running the project with the correct run configurations?
I was having the same issue. For some reason (maybe because I had just updated eclipse?) eclipse decided to change my run to AppletServer - javassist.tools.rmi when I was using Main - io.helidon.microprofile.server.
Hopefully this may give you an insight into your issue.