text:
Q: Cypress: Using multiple selector wih OR condition I have multiple login pages as:
First login page
Input element is as:
<input placeholder="name@email.com" class="input" name="email" type="text" value="">

Cypress selector is as follows:
cy.get('input[name="email"]').as('email').click();

Second login page:
Input element is as:
<input id="email" type="email" required="required" class="input">

Cypress selector is as follows:
cy.get('input[id="email"]').as('email').click();

If we notice, the 1st input element has name=email while the 2nd has id=email.
Is there a way to write a cypress selector where it can look for selector input[name="email"] if not found it looks for input[id="email"]?

A: Yes, there is. It is called cypress conditional testing according to the docs.
There are a number of ways to get this done as seen in the docs depending on what you may want.
Below is something we can do
  cy.get('input[name="email"]').then(($btn) => {
    if ($btn.length) {
      // do something if it's active
      $btn[0].click();
    } else {
      // do something else
      cy.get('input[id="email"]').as('email').click();
    }
  })

A: You can use the comma , to do an OR condition if you are using css selectors. Something like:
cy.get('input[name="email"],input[id="email"]').click()


text:
Q: Unbiased estimate of the variance of an *unnormalised* weighted mean I have a follow-up question to this one:
unbiased estimate of the variance of a weighted mean
Specifically, how do I generalise the result given here (and on Wikipedia) for the unbiased sample estimate of the variance of a weighted population to the case where the weights are not normalised to 1? (or equivalently are not in the standard simplex, as in the previous question's answer derivation)
I'm not sure how much of the previous answer relied on the weights being in the unit simplex, but it's clear that the given answer contains denominator terms like $1 - \sum_i w_i^2$ which aren't going to be nice if $\sum_i w_i^2 > 1$! Maybe there's a simple ansatz for modification to unnormalized weights, but it's not obvious to me which to choose!
Thanks!
Andy

A: Hi,
Rather long after your question, but it can be done directly in the same way Matus did it, or you can simply use the following:
Matus assumed weights $W_i$ which sum to $1$. Suppose you have weights Ui, and write $V_1 = \sum U_i$, and $V_2 = \sum U_i^2$, consistent with the Wikipedia entry for weighted sample variance.
Then we can put $\displaystyle W_i = \frac{U_i}{V_1}$.
Now, look at the factor $\displaystyle \frac{1} {(1 - \sum W_i^2)}$, replace the $W_i$ with $\displaystyle\frac{U_i}{V_1}$, multiply top and bottom lines by $V_1^2$ and - voila! - you get $\displaystyle \frac{V_1^2}{ V_1^2 - V_2 }$  .
However, like Matus, I'm wondering when you would ever use such a "weighted sample variance" - see my question as a response to the original post.
I suspect there is much confusion over the different reasons for weighting.
Kathy

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve "R object is not a matrix" error #data splicing
set.seed(12345)
train <- sample(1:nrow(student.mat.pass.or.fail),size =
ceiling(0.80*nrow(student.mat.pass.or.fail)),replace = FALSE)

# training set
students_train <- student.mat.pass.or.fail[train,]
# test set
students_test <- student.mat.pass.or.fail[-train,]

# penalty matrix
penalty.matrix <- matrix(c(0,1,10,0), byrow=TRUE, nrow=2)

# building the classification tree with part
tree <- rpart(class~.,
          data =  students_train, # as.matrix(students_train)
          parms = list(loss = penalty.matrix),
          method = "class")

object is not a matrix, can someone help me cause I'm new in R I also used the as. matrix(students_train) but it still showing the same problem


text:
Q: Changing a foreach loop to a Parallel.ForEach loop Okay, so here is the basic background.  This program connects to outlook/exchange and parses through all the mail messages to see which are encrypted.  One of the things I would like to do is to use multi-threading to decrease the time it takes to scan through the messages.
Currently the code looks like this:
foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}

And I would like to utilize the Parallel.ForEach function instead.  I was wondering how I could set it up.  I tried setting up the expression to how it is now, but I get an error stating that the Object type is being used as a variable.  Any help with this would be greatly appreciated.
Okay, The layout I have been given seems to be correct.  The code looks like this right now:
Parallel.ForEach(folder.Items, item =>
{
//does stuff
});

I am now getting the following error:

Error 15  The type arguments for method
  System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,
  System.Action)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.

Any ideas?  Thanks for your help guys, it is appreciated.
Okay, I found this site: http://blogs.msdn.com/b/pfxteam/archive/2010/03/02/9971804.aspx and it gave me the answer I needed to the error.  I just needed to change the collection to a generic one by making a casting function.
static IEnumerable<object> Cast(IEnumerable source)
{
    foreach (object o in source)
        yield return o;
}

And then tweak the original to
Parallel.ForEach(Cast(folder.Items), item =>
{
//does stuff
});

Now it runs without errors.  Hurray.

A: Something like this:
Parallel.For(0, folder.Items.Count - 1, delegate(int i) {
  object item = folder.Items[i];
});

Or with ForEach:
Parallel.ForEach(folder.Items, item => {whatever you want to do with item})

Note: folder.Items has to be implementing IEnumerable

A: Assuming that this is correct
foreach (Object item in folder.Items)
   Process(item);

then it changes to
Parallel.ForEach (folder.Items, item => Process(item));


text:
Q: Creating an array of char pointers to eleven strings but having an issue with printing them I'm attempting to create a program that takes an input of eleven strings or things to do and stores them in an array and I want to store them such that only the last byte for each string in storage is the null character. I then want to be able to press the enter key and have the program print randomly one of these items from the strings. However, I appear to be having a hard time with memory management as the first string being stored is never the string that I stored it is always junk. I was curious why this is the case and what I am doing wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    time_t t;
    srand((unsigned) time(&t));
    int num_string=11,k=0;
    char** list_of_strings;
    list_of_strings=malloc(4*11);

    while (num_string>0){
        int i=0;
        char* string;
        string=malloc(100);
        for(i=0;i<100;i++){
            scanf("%c",&string[i]);
            if(string[i]=='\n'){
                string[i]='\0';
                break;
            }
        }
        string=realloc(string,i+1);
        list_of_strings[k]=string;
        k++;
        num_string--;

    }

    char ch;
    while(1){
        scanf("%c",&ch);
        if(ch=='\n'){
            int rand_num=rand()%11;
            char*sel_string=list_of_strings[rand_num];
            while(*sel_string!='\0'){
                printf("%c",*sel_string);
                sel_string++;
            }
        }
    }

    return 0;
}


text:
Q: Devise not responding correctly to JSON message I am finding trouble in having Devise responding correctly to a JSON message.
the following is working fine
curl -XPOST 'http://localhost:5000/users/sign_in.json' -d 'user[email]=MYUSER' -d 'user[password]=MYPASSWORD'

Completed 201 Created in 171ms

In place, I would like to have a more proper JSON format
curl -v -b cookie.file -c cookie.file -H "Content-Type: application/json" -X POST -d '{"user":{"mail":"MYUSER","password":"MYPASSWORD"}}' http://localhost:5000/users/sign_in.json

But I does not seem to work

Processing by Devise::SessionsController#create as JSON
  23:10:32 web.1     |   Parameters: {"user"=>{"mail"=>"MYUSER", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"mail"=>"MYUSER", "password"=>"[FILTERED]"}, "action"=>"create", "controller"=>"devise/sessions", "format"=>"json"}}
  23:10:32 web.1     | Completed 401 Unauthorized in 11ms

Any ideas?
thanks

A: curl -v -b cookie.file -c cookie.file -H "Content-Type: application/json" -X POST -d '{"user" : {"email":"MYUSER" , "password":"MYPASSWORD" }}' http://localhost:5000/users/sign_in.json

It is doing the job. It turn out to be a (plain) misspelling (mail in place of the correct email). Rails logs did not help me to find the solution quickly


text:
Q: jQuery slidedown jumps page Here is a link to the site: http://p7dev.com/bella
When you click on any of the logos, they drop down correctly but the browser also jumps down. How can I keep your place in the browser the same when you click any of the logos?
jQuery(document).ready(function() {

jQuery('.slick-down').click(function() {
jQuery('#hqh-logo').toggleClass('active');
jQuery('#hqh').slideToggle('400');
jQuery('#hqt, #scion, #best, #rent').hide();
jQuery('#hqt-logo, #scion-logo, #best-logo, #rent-logo').removeClass('active');
 });

jQuery('.slick-down2').click(function() {
jQuery('#hqt-logo').toggleClass('active');
jQuery('#hqt').slideToggle('400');
jQuery('#hqh, #scion, #best, #rent').hide();
jQuery('#hqh-logo, #scion-logo, #best-logo, #rent-logo').removeClass('active');
});

jQuery('.slick-down3').click(function() {
jQuery('#scion-logo').toggleClass('active');
  jQuery('#scion').slideToggle('400');
jQuery('#hqt, #hqh, #best, #rent').hide();
jQuery('#hqh-logo, #hqt-logo, #best-logo, #rent-logo').removeClass('active');
});

jQuery('.slick-down4').click(function() {
jQuery('#best-logo').toggleClass('active');
jQuery('#best').slideToggle('400');
jQuery('#hqt, #hqh, #scion, #rent').hide();
jQuery('#hqh-logo, #hqt-logo, #scion-logo, #rent-logo').removeClass('active');
});

  jQuery('.slick-down5').click(function() {
  jQuery('#rent-logo').toggleClass('active');
 jQuery('#rent').slideToggle('400');
jQuery('#hqt, #hqh, #scion, #best').hide();
jQuery('#hqh-logo, #hqt-logo, #scion-logo, #best-logo').removeClass('active');
  });

$(".slick-down").change(function(){
$("select").not("#style").hide();
$("#"+$(this).val()).show();
});

A: By default, the browser jumps to the location of the element with the ID in the hash. You need to prevent this in your javascript click handler by modifying each of them to use preventDefault() like so:
jQuery(".myclass").click(function(event) {
  event.preventDefault();
  // Do normal things
});

You may also want to take a look at the difference between using preventDefault() & return false.

A: It's because you're linking to a local anchor. For example, the first logo goes to #hqh.
That's going to jump the page to wherever the element with id="hqh" is.
Remove the target div id's from the href of the logo links. Just use # instead:

A: If your triggering with an A element, you have to do the following
.click(function(e){
    e.preventDefualt();

    // Your code.
});

A: You can prevent the default href from being followed (in this case they point to anchors on the same page) by using event.preventDefault():
jQuery('.slick-down').click(function(event) {
    event.preventDefault();
    //run your code here
});

You can also return false; at the end of your event handlers like this:
jQuery('.slick-down').click(function() {
    //run your code here
    return false;
});


text:
Q: Reference of primitive root mod p Can any body give me a reference of the result about  primitive root mod p for a class of prime number p.
The result that I am looking for is something along this line:
$2$ is a primitive root mod $p$ for all prime $p$ of the form $p=4q+1$ where $q$ is also a prime.
Thanks in advance.

A: There are two things that you might want.
1) your example of 2 being a primitive root for $p=4q+1$ where $q$ is also prime comes from the more general criterion that if $p-1 = q_1^{e_1} \dots q_r^{e_r}$ is a prime factorization then a non-zero reside $a$ is a primitive root if and only if
$a^{(p-1)/q_i} \ne 1 \bmod p$ for all $i$.
In the particular case you give $p-1 = 2^2 q$.  So the criterion reduces to:
$2^{(p-1)/2} \ne 1 \bmod p$ and $2^2 \ne 1 \bmod p$.  The second is certainly true if $p \ne 3$.  The first is true if and only if 2 is quadratic non-residue $\bmod p$, which is true (by the law of quadratic reciprocity) if and only if $p \equiv 3,5 \bmod 8$.  However, since if $q$ is odd, $p \equiv 5 \bmod 8$.
2) You might be interested in Artin's conjecture on primitive roots:
If $a$ is an integer $\ne 0,\pm 1$ or a square then there are an infinite set of primes $p$ for which $a$ is a primitive root.  In fact this set is a positive proportion of all primes, where the constant of proportionality depends on $a$, see http://en.wikipedia.org/wiki/Artin%27s_conjecture_on_primitive_roots
Artin's original conjecture was amended due to computations by D.H. and Emma Lehmer (in a paper entitled "Heuristics Anyone"), and the amended conjecture was proved conditional on various extended Riemann Hypotheses by Hooley.  Without the GRH it isn't known that there are even an infinite number of primes for which 2 is a primitive root (in particular it isn't known if there are an infinite number of primes $q$ for which $4q+1$ is prime)

A: Take a look at "A criterion on primitive roots modulo p" by H.Park, J.Park, D.Kim.
There is a collection of various criteria including the above for small primes to appear as primitive roots. I hope it helps, or are you looking for something more general?


text:
Q: Not able to retrieve the facts in clips I wish to get a list of friends by using a function.
(deffunction get-freinds-list (?age)

  (bind ?facts (find-all-facts ((?f userdata))
                               (and (eq ?f:name userdata)
                                    (>= ?f:age ?age))))

return ?facts)

(defrule getfriends
   (wantlist yes)
=>
   (printout t "under what age you want list for?" crlf)
   (bind ?age (read))
   (printout t "list is=" (get-freinds-list ?age ) crlf))

(defrule main-control
(initial-fact)
=>
(assert(wantlist yes))
)

(deffacts userfact
(userdata(name "pranay" )(likes tea cricket badminton table farewell)(age 12)(location pakistan)(employer Oracle))
(userdata(name "rohan" )(likes lunch kabaddi tt khoko farewell)(age 10)(location china)(employer TCS))
(userdata(name "srinath" )(likes dinner kabaddi cricket farewell)(age 15)(location china)(employer TCS))
(userdata(name "prateek" )(likes dinner kabaddi cricket farewell drinks)(age 15)(location china)(employer TCS))
(userdata(name "sachin" )(likes drinks kabaddi cricket)(age 15)(location china)(employer TCS))
)

(deftemplate userdata "Knoweledge base"

(slot name)
(multislot likes)
(slot age)
(slot location)
(slot employer)
)

A: CLIPS>
(deftemplate userdata "Knowledge base"
   (slot name)
   (multislot likes)
   (slot age)
   (slot location)
   (slot employer))
CLIPS>
(deffunction get-friends-list (?age)
  (bind ?list (create$))
  (do-for-all-facts ((?f userdata)) (>= ?f:age ?age)
     (bind ?list (create$ ?list ?f:name)))
  return ?list)
CLIPS>
(defrule getfriends
   (wantlist yes)
   =>
   (printout t "under what age you want list for? ")
   (bind ?age (read))
   (printout t "list is " (implode$ (get-friends-list ?age)) crlf))
CLIPS>
(deffacts main-control
   (wantlist yes))
CLIPS>
(deffacts userfact
   (userdata (name "pranay") (likes tea cricket badminton table farewell) (age 12) (location pakistan) (employer Oracle))
   (userdata (name "rohan") (likes lunch kabaddi tt khoko farewell) (age 10) (location china) (employer TCS))
   (userdata (name "srinath") (likes dinner kabaddi cricket farewell) (age 15)(location china) (employer TCS))
   (userdata (name "prateek") (likes dinner kabaddi cricket farewell drinks) (age 15) (location china)(employer TCS))
   (userdata (name "sachin") (likes drinks kabaddi cricket) (age 15) (location china) (employer TCS)))
CLIPS> (reset)
CLIPS> (run)
under what age you want list for? 13
list is "srinath" "prateek" "sachin"
CLIPS> (reset)
CLIPS> (run)
under what age you want list for? 9
list is "pranay" "rohan" "srinath" "prateek" "sachin"
CLIPS>


text:
Q: powershell script to re-run workflow for each items in list I have a workflow in list and i have changed something in workflow.
List has already 2000 items, new modified workflow works for new item added. can someone provide me powershell command to re-run workflow on each existing items in list. As it will be very hectic to run manually for each item. Thanks

A: Try following
# URL of Site
$web = Get-SPWeb -Identity "https://yoursite/sitetest"

$manager = $web.Site.WorkFlowManager

# Name of the list
$list = $web.Lists["Shared Documents"]

# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName("On Item Created","en-US")

$data = $assoc.AssociationData
$items = $list.Items
foreach($item in $items)
 {
 $wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
 }

$manager.Dispose()
$web.Dispose()
#

More detail: http://www.thesysadminhimself.com/2013/09/sharepoint-start-workflow-all-items-powershell.html

A: I was able to do so using the script below:
$sourceWebURL = '<URL>'
$sourceListName = '<List Name>'
$TargetWorkflow = '<Workflow Name>'
$spSourceWeb = Get-SPWeb $sourceWebURL
$spSourceList = $spSourceWeb.Lists[$sourceListName]
$items = $spSourceList.getItems()

#-- Getting a Workflow manager object to work with.
$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($spSourceweb)
#-- Getting the subscriptions
$sub = $wfm.GetWorkflowSubscriptionService()
#-- Getting the specific workflow within the list of subscriptions on the specific list. (SP2010 associated workflows basically)
$WF = $sub.EnumerateSubscriptionsByList($spSourcelist.ID) | Where-Object {$_.Name -eq "$TargetWorkflow"}
#-- Getting a Workflow instance in order to perform my commands.
$wfis=$wfm.GetWorkflowInstanceService()

Foreach($item in $items){
    #-- Creating the dictionary object I need to parse into StartWorkflow. This could be most other workflow commands.
    $object = New-Object 'system.collections.generic.dictionary[string,object]'
    $object.Add("WorkflowStart", "StartWorkflow");
    $wfis.StartWorkflowOnListItem($WF, $item.ID, $object)
}

Reference is below:

*

*https://stackoverflow.com/questions/15045189/how-to-start-workflow-2013-from-powershell


text:
Q: Asynchronous Requests Error "object of type 'method' has no len()" - Python, BS4 & asyncio/aiohttp Hi so I'm working on a web scraper that loops through a list of URLS and returns true if the URL is not owned by an active users account, and false if the URL is in use by an account. The process was too slow with the requests library so I opted to use asyncio and aiohttp instead to run the scraper asynchronously. However I'm at a part in my code where I am receiving the following error: elif len(markup) <= 256 and ( TypeError: object of type 'method' has no len(). The console states the error is due to lines 33, 44, and 49, but I have no idea why this error is thrown. Another user suggested it may be due to missing brackets in my calls, but I have called all functions correctly.
Any help is greatly appreciated. Thank you

A: Replace
soup = BeautifulSoup(response.text, "lxml")

with
soup = BeautifulSoup(await response.text(), "lxml")

Please read documentation carefully.


text:
Q: Cannot override padding in print style when transition-duration is set I have a peculiar problem that only seems to affect Chrome (tested in Chromium 47.0.2526.73 on Ubuntu, Chrome 48.0.2564.82 m on Windows, Firefox 43.0.4 on Ubuntu), and only in an actual print-preview (the problem does not occur when emulating print media in the developer tools).
I have been trying to fix an issue with the print styles in GitLab, in which there is an undesirable gap on the left-hand side of the page, as shown below.

Now, one would expect this to be an easy fix. The main container element has a padding-left of 230px to leave room for the sidebar, which needs to be zero when printing. However, I cannot get a print style in place that actually eliminates this padding.
I have reduced it down to a minimal test case, as shown here. I'd use an in-place snippet, but that doesn't work so well when you try to print-preview it. The source of my example is as follows:
<!DOCTYPE html>

<title>Print style problem demonstration</title>

I have no left padding.

I should have no left padding when printed

In this example, I am trying to eliminate the padding of the purple p when printing by setting padding-left: 0!important; in the print style. I have isolated the problem to the transition-duration: .3s; style, and the problem goes away if it is removed. However, setting transition-duration: 0s!important; does not successfully override it.

I have read this thread, which is the most relevant I could find, but the solutions described do not appear to work for me (making the transition screen-only, and adding the other transition: none lines).
One further observation of interest is the the problem also relies on the @media(min-width: 1199px) rule. If this is removed, the problem also goes away.
None of the factors I've identified that make this problem occur are easily changeable by me in GitLab, and even if they were I'd really love to know what is causing this behaviour.
Am I doing something wrong or is this a bug in Chrome?

A: the main issue is transition property, you can write it inside media check the following css, i have tested this as well and working fine.

A: I logged this as a potential bug in Chromium, and it's now been verified as such, which I think answers this question.

Able to reproduce on Windows 7, Mac OS 10.11.2 and Ubuntu 14.04 using chrome stable M48 - 48.0.2564.82.
Bisect Information:
Good Build: 47.0.2524.0
  Bad Build : 47.0.2526.0

As a workaround (until the fix is released) I will try leaving the padding in place, and using negative margin to counteract it.


text:
Q: How to set default value for HTML drop-down list not from the option element? I'm using an adaptation of PHPBB to create a drop-down list.
  <select name="destination_path">
    <!-- BEGIN path -->
    <option value="{path.DESCRIPTION}">{path.DESCRIPTION}</option>
    <!-- END path -->
  </select>

The list is generated from a MySQL query, so it is dynamic. This list is within a form and when the form is fired I want to retain (and return) it's state in session variables. My first thought was to place something in the <select> statement.
I  know you can use:
selected="option_selected"

in the relevant <option>, but it seems like a messy way to do this and would require an if statement to compare each tag as the tag is created.
Is there a way to declare the default option in the select tag, or a better defined method to achieve the same result?

A: Short answer: No.
The select tag defines the selected option in its option elements. What you could do if you want to achieve it differently, is putting the selected option on top without specifying a selected attribute. Most browsers select the first option as default if there is no selected attribute present.
Ex :
 <select>
 <option value="Hi"> Hi </option>
 <option value="Hello" selected> Hello </option>
 </select>

A: You may be able to select the option you need after compiling the list by adding a little jQuery.
A similar question has been asked on the jQuery Forums.
Using the example of:
<select name="options">
  <option value="1">Red</option>
  <option value="2">Green</option>
  <option value="3">Blue</option>
</select>

You can set the selected option by value:
$('[name=options]').val( 3 ); // To select Blue

Or you can set the selected option using the text:
$('[name=options] option').filter(function() {
    return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);

Links to jsFiddle can be found in this post.
Credit to: Godsbest on the jQuery Forums.

A: Yes.... there is a way to declare the default option in the select tag
Try this...
To set a default value first you have to mention the name of the select tag and in the find() function just pass the value you have to set as default value.
$('select[name="destination_path"]').find('option:contains("default")')
.attr("selected",true);


text:
Q: Terraform output from a nested list I am trying to get my output from my module in order to attach the iam policies I am creating to the roles I am creating. However it seems I am not getting the output to line up with my module. Code below will be what I have and then I'll show what I am trying to get with attaching it. when I try to add the attach it just starts complaining and I can't figure out why. Names for the roles will not always be the same length as in this case I just swapped out the names to test.
Example is attaching policy1 to role1 and then etc
Any help would be appreciated
within module folder
./modules/iam_dev/main.tf
locals {
    assume_policy = file("${path.module}/assume_policy.json")
}

resource "aws_iam_role" "dev" {
    for_each = var.roles

    name = each.key
    assume_role_policy = local.assume_policy
    managed_policy_arns = var.managed_policy
    tags = var.tags
}

./modules/iam_dev/vars.tf
variable "roles" {
    type = map(map(list(string)))
    description = "Roles to create"
}

variable "managed_policy" {
    type = list(string)
    description = "List of managed policies to be included with the IAM role"
    default = []
}

variable "tags" {
  description = "A map of tags to add to IAM role resources"
  type        = map(string)
  default     = {}
}

./modules/iam_dev/outputs.tf
output "role_name" {
  value = {
    for role in aws_iam_role.dev :
    role.name => {
      name = role.name
      arn  = role.arn
    }
  }
}

within my project folder this is what I have.
./projects/main.tf
module "iam_admin" {
  source = "../../modules/iam_dev"

  roles = {
    test1 = {
    }
    test2 = {
    }
    test3 = {
    }
  }
  tags = {
   Created     = "terraform"
  }
}

resource "aws_iam_policy" "test_policy1"{
    name = "test_policy1"
    policy = file("${path.module}/json_files/test_policy1.json")
}

resource "aws_iam_policy" "test_policy2" {
    name = "test_policy2"
    policy = file("${path.module}/json_files/test_policy2.json")
}

resource "aws_iam_policy" "test_policy3" {
    name = "test_policy3"
    policy = file("${path.module}/json_files/test_policy3.json")
}

### tried the following few ideas but to no avail. I also assume the second one would apply to all which is not what I am wanting.
resource "aws_iam_role_policy_attachment" "test1" {
  role       = module.iam_admin.roles.test1.name
  policy_arn = aws_iam_policy.test_policy.arn
}

resource "aws_iam_role_policy_attachment" "test1" {
  role       = module.iam_admin.roles.name
  policy_arn = aws_iam_policy.test_policy1.arn
}

edit:
Here is the error output. I tried it where I put the name in for example but same result.
module.iam_admin.roles.test1
71:   role       = module.iam_admin.roles
│     ├────────────────
│     │ module.iam_admin is a object, known only after apply
│
│ This object does not have an attribute named "roles".


text:
Q: Creating a DBF File, as part of a shape file, without a DBT file - in C# I want to create a DBF file: it should be dBase III format.

*

*As part of an ESRI Shapefile

*dBase format III

*WITHOUT A MEMO \ DBT FILE.

*Single column multiple rows.

I've tried a lot of options the closest I got was using this: ( But it creates the annoying memo file along with it ).
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp;Extended Properties=dBase III";

using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = connection.CreateCommand())
{
    connection.Open();

    command.CommandText = "CREATE TABLE Test (Id Integer, Changed Double, Name Text)";
    command.ExecuteNonQuery();
}

as was suggested here.

A: You probably won't come back to see this but this is to you and others who might benefit:
I'm also working on ESRI's shapefile and found that changing that connection string to specify the Provider to VFPOLEDB solves the problem.
Try:
 string connectionString = @"Provider=VFPOLEDB;Data Source=D:\temp;Extended Properties=dBase III";

VFPOLEDB is Visual Fox Pro provider for Ole DB.


text:
Q: exception while Installing WP7.1? Previously I installed WP7 RTW in my machine. Now, I need to install the latest version for windows phone 7.1 SDK in to my machine. So, when I try to install the windows phone SDK 7.1 I'm getting exception, it says, need to uninstall the "Visual Basic for windows phone developer tool-RTW".
thanks in advance.

A: update to Visual Studios Service Pack 1 2010, that helped with my issues.


text:
Q: Multiselect option with remove button, and assigning class/id to each selected item differently Select numbers (you can select each number any number of times):

 <select name="number_selection" method="post" id="number_selection" >
    <option value="0">0</option>
    <option value="1">1 </option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
   </select>
 <input type="button" value="Select" id="select_button"/>

This is the jquery i've written to select and deselect:
$('#select_button_gs').click(function(){
    var gs= $('#slct_fcb_gs').val();
    $('#fcb_pt_gs').append('' + gs + '' + '  ' + '<input type="button" value="Remove" class="gs_remove" />' + '
');

    });

    $('#fcb_pt_gs').on('click','.gs_remove',function(){
         $(this).prev('span').remove();
         $(this).next('br').remove();
          $(this).remove();
       });

Now,  What should I do if i want to assign different class/id to the each option after selecting them ?


text:
Q: Recibir un txt, reemplazar una palabra completamente en minúsculas por una con mayúscula en la primera letra y crear otro archivo txt El código es en C++ y al recibir como dato el archivo de texto arc.txt compuesto por cadenas de caracteres en las que puede aparecer la palabra méxico escrita con minúsculas, cada vez que localice la palabra méxico en una cadena, la reemplace por su forma correcta —la primera letra con mayúsculas (México)— y escriba la nueva cadena en el archivo arc1.txt.
#include <stdio.h>
void sust_a(void)
{
    FILE *arch;
    char car;
    arch=fopen("arc.txt","r+");       //mando a pedir el txt
    while (fscanf(arch,"%c",&car)!=EOF)
    {
        if (car=='mexico')     //aqui es donde me marca el error, id returned 1 exit status
        {
            fprintf(arch,"Mexico");
        }
    }
    fclose(arch);
}

A: Para trabajar la lectura y escritura de archivos, suponiendo que lo haces en C++, deberías usar la librería fstream, usando string::find para encontrar la palabra deseada dentro de cada línea y string::replace para reemplazarla si fue encontrada (ver este post, está en ingles). Conjuntamente con la librería string, una posible solución a lo que deseas sería:
#include<fstream>
#include<iostream>
using std::cout;
#include<string>
using std::string;

void sust_a(void){
    string reemp = "méxico";
    string reemp_con = "México";
    string line;
    size_t len = reemp.length();

    std::ifstream archivo_in{ "arc.txt" };//archivo de entrada
    std::ofstream archivo_out{ "arc1.txt" };//archivo de salida

    if (archivo_in && archivo_out) {//si los archivos fueron abiertos correctamente dara true
        while (getline(archivo_in, line)){//lee una línea
            while (true){
                size_t pos = line.find(reemp);//busca méxico en la línea actual
                if (pos != string::npos)
                    line.replace(pos, len, reemp_con);//si la encuentra la reemplaza con México
                else
                    break;
            }
            archivo_out << line << '\n';//aqui escribe la línea corregida en el nuevo archivo
        }
    }
    else
        cout << "No se pueden abrir los archivos";
}

A: En un primer vistazo, ya se ven al menos tres errores en tu código:

*

*La pregunta está etiquetada como c++ pero el código es absolutamente c.

*La cabecera <stdio.h> es de C y no debe ser usada en código C++, si es necesario usarla (casi nunca lo es) debe usarse la versión adaptada a C++: <cstdio>. Lee este hilo para saber más.

*Usas un literal multibyte en lugar de una cadena para comprobar el valor de un carácter… aunque no lo parezca 'mexico' es un número (no una cadena de caracteres) cuyo valor es dependiente de la implementación del compilador1, pero sea cual sea el valor nunca será el valor de un carácter como car.

Mientras escribía vi dos errores más:

*

*Un carácter no es una palabra, 'm' nunca será "mexico".

*Una vez leído un carácter, el puntero de lectura está en el siguiente carácter, por lo que aún suponiendo que leyeses la palabra "mexico" si escribes "Mexico" en la posición de lectura, obtendrás "mMexico".

Suponiendo que realmente quisieras programar en C++ (que no lo parece) tu código debería parecerse a:
// Abrir archivo arc.txt
if (std::fstream arc{"arc.txt"})
{
    // Leer palabra por palabra.
    for (std::string palabra; arc; arc >> palabra)
    {
        // Si la palabra leída es "mexico"
        if (palabra == "mexico")
        {
            // Rebobina seis caracteres.
            arc.seekg(arc.tellg() - 6l);
            // Escribe "Mexico".
            arc << "Mexico";
        }
    }
} // El archivo se cierra aquí automáticamente.

Puedes ver el código funcionando en Try it online!.

1Podría ser un número cuya representación binaria tuviera el valor del carácter 'm' en el byte de mas peso y el valor de 'o' en el de menos: 6d657869636f16 o 12028257929713510.


text:
Q: How to use a modified ls program to execute another program? I got a modified ls:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv){
    char command[50];
    strcpy(command,"/bin/ls ");
    gid_t egid = getegid();
    setregid(egid, egid);
    if(argc > 1) {
        if(strlen(argv[1]) > 40) {
            printf("The command you have given is too long, try again.\n");
            return 0;
        }
        strcat(command,argv[1]);
        system(command);
    }else{
        printf("This is a special NSA-modified 'ls' program. See 'man ls' for further details on how to use it.\n");
        printf("USAGE: %s [flags & files]\n",argv[0]);
    }
    return 0;
}

I have to execute a program called get-code but i don't have the privileges to execute it without the ls (the modified ls is in the same directory as the get-code program), so how can I execute the get-code program using the modified ls?
Can someone help me?

A: Glad the teacher said it is allowed.  Actually I would have a bigger problem is this was a real-life issue -- what you are trying to do is exploit a security hole, and that's not a good idea in the real world.
This exercise is designed to show you how careful you have to be when writing code so that you don't open big security holes in the system. The "ls" command does not have any option to exec another program. The program adds absolutely anything you have in the arg1 to the end of the string "/bin/ls". If you know shell, you know that the ";" character separates two commands. Can you think of a way to set up the argument so that it has a semi-colon and then the command you want to run?


text:
Q: C# HttpClient with X509Certificate2 - WebException: The request was aborted: Could not create SSL/TLS secure channel I'm working on implementing a payment service called Swish and testing it using this guide (Guide is in English even though filename is Swedish).
https://www.getswish.se/content/uploads/2015/06/Guide-Testverktyg_20151210.zip
As you can see the test project contains two certificates, .p12 and .pem file. I have tried to authenticate the request with both.
However even though trying solutions I found to this problem I still get the error.
As suggested here I implemented logging and this is the result. Pastebin link due to character limitation. I do not see anything pointing to StatusCode=401 in the logs so I don't think it is HTTP 401 Unauthorized.
public class PaymentRequest
{
    [JsonProperty("payeePaymentReference")]
    public string PayeePaymentReference { get; set; }

    [JsonProperty("callbackUrl")]
    public string CallbackUrl { get; set; }

    [JsonProperty("payerAlias")]
    public string PayerAlias { get; set; }

    [JsonProperty("payeeAlias")]
    public string PayeeAlias { get; set; }

    [JsonProperty("amount")]
    public string Amount { get; set; }

    [JsonProperty("currency")]
    public string Currency { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new SwishService();

        var paymentRequest = new PaymentRequest();
        paymentRequest.PayeePaymentReference = "0123456789";
        paymentRequest.CallbackUrl = "https://example.com/api/swishcb/paymentrequests";
        paymentRequest.PayerAlias = "4671234768";
        paymentRequest.PayeeAlias = "1231181189";
        paymentRequest.Amount = "100";
        paymentRequest.Currency = "SEK";
        paymentRequest.Message = "Kingston USB Flash Drive 8 GB";

        service.SendPaymentRequest(paymentRequest);
    }
}

public class SwishService
{
    private HttpClient client;
    public SwishService()
    {
        var baseAddress = new Uri("https://mss.swicpc.bankgirot.se");

        var certHandler = new WebRequestHandler();
        certHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
        certHandler.UseDefaultCredentials = false;

        //Same result with Swish Merchant Test Certificate 1231181189.p12 file
        var certPath = $"C:\\Users\\<Path>\\Testcertifikat\\Test Swish Root CA v1 Test.pem";

        var certificate = new X509Certificate2(certPath, "swish");
        certHandler.ClientCertificates.Add(certificate);

        client = new HttpClient(new LoggingHandler(certHandler));
        client.BaseAddress = baseAddress;
        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    }

    public void SendPaymentRequest(PaymentRequest paymentRequest)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                               | SecurityProtocolType.Tls11
                                               | SecurityProtocolType.Tls12
                                               | SecurityProtocolType.Ssl3;

        //Code throws exception before this callback is called
        ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };

        var content = new StringContent(JsonConvert.SerializeObject(paymentRequest), Encoding.UTF8, "application/json");

        var response = client.PostAsync("/swish-cpcapi/api/v1/paymentrequests/", content).Result;

        var resultStream = response.Content.ReadAsStreamAsync().Result;
        var result = string.Empty;

        using (var streamReader = new StreamReader(resultStream))
        {
            result = streamReader.ReadToEnd();
        }
    }

}

Update:
Using Postman in Chrome I could send a request after first importing the certificate in Chrome and then through mmc in the store Trusted Root Certification Authorities. I have not managed to find a solution in code yet. PS: The hosting for the application requires that the certificate is loaded from file and not fetched from a certificate store.

Update 2:
System diagnostics log with stack trace:
https://pastebin.com/qMz6X6yJ

A: Found an SSL test performed on the server:
https://www.ssllabs.com/ssltest/analyze.html?d=mss.swicpc.bankgirot.se
From here I could see that the following protocols were allowed:

After I set this everything worked:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

A: You can attach eventHandler to ServicePointManager like this:
ServicePointManager.ServerCertificateValidationCallback = ForcedAuthDelegate;

and implementation of ForcedAuthDelegate should return true to accept connection:
        static bool ForcedAuthDelegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }


text:
Q: Callback not being executed, though request works fine with jQuery getJSON I am trying to obtain a list of assets (via JSON) inside of a drop using a free drop.io account.
Note that I have already looked at the other two questions (question1 and question2) concerning this and neither of them provided a solution.
    var dropName = escape("greganddonny");
            var apiKey = "some key I'm not displaying it here...";
            var version = "2.0";

    var assetsListBaseURL = "http://api.drop.io/drops/greganddonny/assets.json?api_key=" + apiKey + "&version=" + version;

    var resultingdata = null;

    function getFileList() {
        console.log("BEGIN: getFileList()");
        var surl = assetsListBaseURL + '&callback=?';

        $.getJSON(surl, function(data, textStatus) {
            console.log("textStatus:" + textStatus);
            console.log("BEGIN: Callback()");
            resultingdata = data;
            showResult();
            console.log("END: Callback()");
    });

        console.log("END: getFileList()");
    }

    function showResult()
    {
        alert(resultingdata);
    }

    $(document).ready(function() {
        console.log("BEGIN: document.ready");
            $.ajaxSetup({
            "error": function(XMLHttpRequest,textStatus, errorThrown) {
              alert(textStatus);
              alert(errorThrown);
              alert(XMLHttpRequest.responseText);
              }
            })

            $("#search").click(function() {getFileList();});
        console.log("END: document.ready");
    });

When the search button on the page is clicked this triggers the getFileList() function.  According to my firebug console the getFileList() function is called just fine.
The JSON request is also made successfully as the firebug console's Net tab displays a 200OK status when I call assets.json on drop.io's site.  I also receive the following return JSON in the list of requests in the "Net" tab:
    [{"converted":"http:\/\/drop.io\/download\/public\/x0yfnmzdtet1vtxesqcm\/12a9ebc74c9a3e4e3b2e2b4ea3546b919a2519ff\/df43d2b0-926f-012c-26c2-fbe072d62af6\/2a0a5270-9270-012c-8fc9-fbfd417303a8\/v2\/content","type":"audio","status":"converted","title":"MikeAndAndyOnPhone2009.MP3","duration":118,"artist":"Unknown","created_at":"2009/10/03 17:29:02 +0000","filesize":1895424,"description":null,"track_title":"Unknown","hidden_url":"http:\/\/drop.io\/hidden\/sazpcf7522exzb\/asset\/bWlrZWFuZGFuZHlvbnBob25lMjAwOS1tcDM=","name":"mikeandandyonphone2009-mp3"}]

I validated the above block of returned JSON using JSONLint and it reports that the JSON returned is indeed valid, you can test this out by copying and pasting the block above.
I've tried everything I know how to try, I've even added an "error" option to the $.ajaxSetup method and I still haven't had any success returning even an error message as to why my callback function is not being called.
Any idea why this might be?  You can test out my script here

A: JSONP requires the server to support JSONP requests. However if you visit
http://api.drop.io/drops/greganddonny/assets.json?api_key=API_KEY_HERE&version=2.0&callback=x

the document returned looks like [{"converted..) although it should look like x([{"converted"..) because of the x callback.
Apparently drop.io doesn't support JSONP (documentation doesn't tell so either). The only option that's left for you is the classic approach to cross-domain js: Use a Proxy.


text:
Q: How do I create a bootable GPT UEFI Linux disk? Aaargh.  After days of reading and trying everything I'm still stuck in a maze. It should be simple but I cannot work it out.
I need to create one bootable UEFI disk partition that contains all the space on the disk.  The steps must work in a shell script. Ideally with syslinux/extlinux but if not possible then grub.
How to do this?  Surely it should be dead easy, a handful of lines?  Nothing I do works.
This is what I have so far:
DISK_DEVICE_NAME_CURRENT_OS=hda
echo remove all partitions
sudo /usr/local/sbin/sgdisk -Z /dev/${DISK_DEVICE_NAME_CURRENT_OS}
echo create GPT partition
sudo /usr/local/sbin/sgdisk -n 1:: /dev/${DISK_DEVICE_NAME_CURRENT_OS}
echo format file system
sudo mkfs.ext4 -F /dev/${DISK_DEVICE_NAME_CURRENT_OS}1
sudo mkdir -p /mnt/target
sudo mount /dev/${DISK_DEVICE_NAME_CURRENT_OS}1 /mnt/target
sudo mkdir -p  /mnt/target/boot
sudo /usr/local/sbin/extlinux --install /mnt/target/boot
sudo dd if=/usr/local/share/syslinux/gptmbr.bin of=/dev/${DISK_DEVICE_NAME_CURRENT_OS}

When I boot, it says:
Booting from Hard Disk.
Missing OS.
No bootable device.
Any suggestions please as to how I can get this disk to boot?
thanks

A: Please use Gparted to create a gpt based disk (not ms-dos, older partitions).

*

*Create a new partition table (gpt type).

*Have a EFI system partition (ESP)

*Create the remaining partitions needed for the OS and boot the installation media in UEFI mode. To boot linux: usually /boot, /, and swap.

Please read:
UEFI partitioning for dummies
EFI System Partition


text:
Q: Express.js / Multer. Response being sent before onFileUploadComplete is complete I am using the following stuff for a file upload service:
onFileUploadStart: function (file) {
        uploadPath = "";
        imageDimensions = null;
        console.log(file.originalname + ' is starting to upload...');
    },
onFileUploadComplete: function (file) {
        uploadPath = file.path;
        uploadPath = uploadPath.replace(/\\/g,"/");
        console.log("Upload complete. " + file.fieldname + ' uploaded to  ' + file.path)
        sizeOf(file.path, function (err, dimensions) {
            if (err){
                console.log("ERROR, Can't get size of image! " + err);
                return;
            }
            else{
                imageDimensions = {
                    width : dimensions.width,
                    height: dimensions.height
                };
                console.log("Size of image: width: " + imageDimensions.width + ". height: " + imageDimensions.height);
            }

        });
    }

and
app.post('/imageupload',function(req,res){
  upload(req,res,function(err) {
    console.log("response is being send..");
    if(err) {
        return res.end("Error uploading file.");
    }
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.json({
        dimensions: imageDimensions,
        path: uploadPath
    });
});

});
From what I understand (https://stackoverflow.com/a/30458411/2742995) onFileUploadComplete is first processed before the .post handler is being executed. However, my console shows:
a.jpg is starting to upload...
Upload complete. file uploaded to uploadeddata\a1235412.jpg
response is being send..
Size of image: width: 2835, height: 1654

So it seems that right in the middle of the onFileUploadComplete function the .post handler is already being exectued..
Any ideas how I can solve this?

A: Ok yeah got it... the sizeOf function I used is async.....
var dimensions = sizeOf(file.path);

is the synced version.


text:
Q: Any ket as a sum of eigenkets of a given observable Most quantum mechanics texts include a phrase such as 'any ket can be written as a sum of eigenkets of a given observable'.
I have problems with the generalities of any ket.
Does this literally mean any ket, or does it mean any ket of the same observable? It seems odd that any ket, say an eigenket of position, should be expressible as a sum of eigenkets of a different observable?
Edit:
Unless of course a general state is dependent on more than one summation of eigenkets of more than one observable, but the measurement of one of those observables does not depend on the other summations.

A: Think about it this way: When you measure some observable $O$, you get some measured value. If you measure many identically prepared systems, you may measure different values corresponding to the operator $O$. In the limit where you do this infinitely many times, you are able to recover exactly which values are possible, and with which probability. Basic quantum theory now tells you that the system (before you measured anything) was in a superposition of eigenstates corresponding to the (eigen)values for $O$ which you ended up measuring.
This means that the system is in the state $$|\psi\rangle =\sum_{i=1}^\infty c_i |o_i\rangle$$ i.e. it can be written as a weighted sum of eigenkets $|o_i\rangle$ of $O$. This basically just expresses that one can always measure the observable $O$, and get some value. In some cases, the sum should be replaced by an integral, or it can be a sum over finitely many eigenstates, but the idea is the same.

A: Look it like this, a ket is a vector of a (fancy) vector space and as such it has different components with different weights.
Now, going to a more familiar vector space of the $R^3$, you can choose for example the cartesian coordinate system to describe a vector in space, but you can also choose any other set of three vectors (provided they're not colinear) to describe such a vector. In particular you can pick any rotation of the initial cartesian system.
That procedure and possibility in real space, also translates to the Hilbert vector space where kets (and bras) "live". It's nothing else than to say you're expressing your vector in a different basis.


text:
Q: Flatten an array of objects and get unique keys and values by a repeated date with Lodash? I've been playing around with Lodash and not getting close to a solution that doesn't involve a lot of extra looping and overhead.
data: [
    {
      name: "FirstResult", values: [
        {
          value: { NameCount: 1, OtherCount: 1 },
          date: 2019-05-15T07:00:00+0000
        },
        {
          value: { NameCount: 1 },
          date: 2019-05-16T07:00:00+0000
        }
      ]
    },
    {
      name: "SecondResult",
      values: [
        {
          value: { NameCount: 1 },
          date: 2019-05-15T07:00:00+0000
        },
        {
          value: { BuyCount: 2, SellCount: 1 },
          date: 2019-05-16T07:00:00+0000
        }
      ]
    }
  ]

I'd like to flatten this and have it combined and aggregated by using the date as the key returning some configuration like:
[
  { date: 2019-05-15T07:00:00+0000, values: { NameCount: 2, OtherCount: 1 } },
  { date: 2019-05-16T07:00:00+0000, values: { NameCount: 1, BuyCount: 2, SellCount: 1 } }
]

Or even just a flat object array is fine like:
[
  { date: 2019-05-15T07:00:00+0000, NameCount: 2, OtherCount: 1 },
  { date: 2019-05-16T07:00:00+0000, NameCount: 1, BuyCount: 2, SellCount: 1 }
]

Does anyone have any ideas on how to do this with either a Lodash or Vanilla solution?

A: You can use a lodash's chain to flatten, group by the date, and then map and merge each group to a single object:

const fn = data => _(data)
  .flatMap('values') // flatten to array of objects
  .groupBy(o => o.date.toISOString()) // group by the iso representation
  .map(group => { // map the groups by merging, and converting to require format
    const { date, value } = _.mergeWith({}, ...group, (objValue, srcValue) =>
      _.isNumber(objValue) ? objValue + srcValue : undefined // combine numeric values
    )

    return {
      date,
      ...value,
    }
  })
  .value()

const data = [{"name":"FirstResult","values":[{"value":{"NameCount":1,"OtherCount":1},"date": new Date("2019-05-15T07:00:00.000Z")},{"value":{"NameCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]},{"name":"SecondResult","values":[{"value":{"NameCount":1},"date":new Date("2019-05-15T07:00:00.000Z")},{"value":{"BuyCount":2,"SellCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Or you can use _.flow() to generate the function (I'm using lodash/fp here):

const { flow, flatMap, groupBy, map, mergeAllWith, cond, isNumber, add } = _

const fn = flow(
  flatMap('values'), // flatten to array of objects
  groupBy(o => o.date.toISOString()), // group by the iso representation
  map(mergeAllWith(cond([[isNumber, add]]))), // combine numeric values
  map(({ date, value }) => ({ date, ...value })) // format the objects
)

const data = [{"name":"FirstResult","values":[{"value":{"NameCount":1,"OtherCount":1},"date": new Date("2019-05-15T07:00:00.000Z")},{"value":{"NameCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]},{"name":"SecondResult","values":[{"value":{"NameCount":1},"date":new Date("2019-05-15T07:00:00.000Z")},{"value":{"BuyCount":2,"SellCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]}]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

A: Here is pure ES6 solution based on Array.reduce and Array.forEach for the object keys:

const data = [{"name":"FirstResult","values":[{"value":{"NameCount":1,"OtherCount":1},"date": new Date("2019-05-15T07:00:00.000Z")},{"value":{"NameCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]},{"name":"SecondResult","values":[{"value":{"NameCount":1},"date":new Date("2019-05-15T07:00:00.000Z")},{"value":{"BuyCount":2,"SellCount":1},"date": new Date("2019-05-16T07:00:00.000Z")}]}]

let result = data.reduce((r, { values }) => {
  values.forEach(({ value, date }) => {
    let keys = Object.keys(value), d = date.toISOString()
    r[d] = r[d] || Object.assign({}, ...keys.map(x => ({ date: d, [x]: 0 })))
    keys.forEach(k => r[d][k] = (r[d][k] || 0) + value[k])
  })
  return r
}, {})

console.log(Object.values(result))

The main idea is to get the keys of the value object white iterating and compose an object with them while grouping by the date. Then last forEach just sums each result object value.


text:
Q: Scripts being deleted by AV So I have been building a bat/powershell tool to make my job easier. It is full of scripts to fix, modify, and configure systems to the company standard for our clients. Over the past 6 months I have just disabled AV programs that falsely detect my script as malicious.
I would like to tackle this issue and switch to a way to work without having files deleted as I use them when I forget to disable an AV.
The system primarily works in Powershell, but as we deal with a lot of Windows 7 machines still, I have to have a batch program to initiate the script to install the powershell module. At the same time, it copies all the files to run the program into a folder under C:.
I have looked into a bat2exe solution, but I have everything broken up into tiny files for ease of use for myself and powershell. I also cant just compile batch and powershell into one exe from my understanding.
Am I better off just rewriting it into a compiled language, or is the a way to have my little project work around the false positives of the AV's?

A: The correct answer here is to sign your scripts. The specific process to configure A/V appropriately may vary between different A/V tools, but signing your Powershell scripts is a solid method to verify the integrity of your Powershell code.
For batch scripts, I'm not sure there is a way outside of running them from a directory or filepath whitelisted by your A/V.
This blog post contains some good info on self-signing your Powershell scripts, or using a certificate from AD Certificate Services.
Here is Microsoft's official doc on Powershell script signing as well.
Update: If you are still developing your script and are not ready to sign it as indicated by one of your comments, temporarily disabling A/V is a bit heavy-handed. Typically on development systems, engineers add (or if they don't have access, have their IT dept. add) their project/source folder(s) to the A/V whitelist, which should prevent A/V from interfering with your development code.


text:
Q: Where can i find ROW_NUMBER(), RANK(), DENSE_RANK() functions? Where can i find ROW_NUMBER(), RANK(), DENSE_RANK() functions, like all other functions in sql server 2012 i can find in Programmability->Functions->System Functions

A: I'm not sure that your statement that "you can find the list of all system function[s] in your database" is accurate - I looked through all the sections and I didn't see those three.
Why do you need to find them, though?  What problem are you trying to solve?


text:
Q: Android for loop not working in main thread i try to rotate image. i used runnable to rotate image,i wrote for loop and i want to rotate image inside for loop
this is a my source
public void rotateimages(final View myView) {
    myHandler = new Handler();
    runnable = new Runnable() {

        @Override
        public void run() {

            double k = 30;

            double speed = Math.PI / k;
            for (alpa = 0; alpa < (Math.PI * 6 + res * 2 * Math.PI / 5); alpa += speed) {

                myView.setRotation((float) (myView.getRotation() - alpa));

                Log.e("alpa values", String.valueOf(alpa));

                k = Math.min(k + 0.2, 240);
                speed = Math.PI / k;
                myHandler.postDelayed(this, 100);
            }
            // rotateimages();
        }

    };

    myHandler.postDelayed(runnable, 180);
}

when i run my app i can rotate only one time.what is a wrong in my code? if anyone knows solution please help me

A: If you want to loop , you need to define this 'runnable' loop again itself
 edit your code to:
myHandler = new Handler();
count = 0;
public void rotateImage(final View myView, final int size) {

    runnable = new Runnable() {

        @Override
        public void run() {

            count++;
            myView.setRotation(myView.getRotation() + size);
            if(count == 10){
               myHandler.removeCallBack(runnable );
            }
           myHandler.postDelayed(this, 1000); // 1000 means 1 second duration
         }
        };
        myHandler.postDelayed(runnable, 180); // 180 is the delay after new runnable is going to called

}

How to loop itself, that's mean one code line, or one statement call the event again. Some example:
 void nothing(int a){
   if(a> 0)
     nothing(a-1);
   }

and call nothing(10). that's all, and avoid some action like:
void nothing(int a){
       for(int i =0; i< a;i++)
         nothing(a-1);                //BIG WRONG
       }
 Do you know your solution?

A: In your for loop, you continually increment myView's rotation with 180.
If the number of iterations in the for loop is divisible with 2, then the resulting rotation will be the same as in the beginning. This is why if you rotate the shape once, it gets flipped and you can see the new rotation, but if you rotate it again, it gets flipped back.
Illustration:
no flip. rotation: 0
#
#
# #

one flip. rotation: 180
# #
  #
  #

two flips. rotation: 360
#
#
# #

To fix your code in the way you supposedly want it:
public void rotateImage(final View myView, final int size) {

    myHandler = new Handler();
    runnable = new Runnable() {

        @Override
        public void run() {

            // include one of the following:

            // Way #1: supports animation more easily
            for (int i = 0; i < size; i++) {
                myView.setRotation(myView.getRotation() + 1);
            }

            // Way #2: more performant way of doing it
            myView.setRotation(myView.getRotation() + size);

        }
    };
    myHandler.postDelayed(runnable, 180);

}


text:
Q: CSS: make div slide over another div (i.e., use a div as background) I have a div that acts as the page background and other divs are showing over it.
However when the user scrolls, the background div scrolls too. I'd like it to be fixed while the content div scrolls over it.
This is my actual code:
#background {
    z-index: 1;
    width: 100%;
    height: 100vh;
    position: fixed;
}
#content {
    z-index: 99;
    position: absolute;
    top: 2em;
    padding: 1em 1em;
    width: 100%;
}

Can this be done? Thank you

A: you can see the demo page:
body, html, main {
    /* important */
    height: 100%;
}

.cd-fixed-bg {
    min-height: 100%;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-position: center center;
}

.cd-fixed-bg.cd-bg-1 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-2 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-3 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}
.cd-fixed-bg.cd-bg-4 {
  background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg");
}

.cd-scrolling-bg {
    min-height: 100%;
}

HERE MY DEMO

A: When using position: fixed you need to also specify values for the position of the element.
A jsfiddle demonstrating this:
HTML:

    This is the content

CSS:
#background {
    z-index: 1;
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background-image: url(https://wallpaperscraft.com/image/metal_lines_stripes_light_shiny_silver_18401_1920x1080.jpg);
}
#content {
    z-index: 99;
    position: absolute;
    top: 2em;
    padding: 1em 1em;
    width: 100%;
    color: blue;
    font-size: 300%;
    height: 400%;
}


text:
Q: Fire Ajax Rest call only for elements in viewport i've got the following problem.
We're using a template which generates a list of divs, all with the same classes etc.
Each div contains a hidden input field containing the ID of the target site it links to.
Now my job is to use this ID to generate ajax rest calls for each of the divs to receive the amount of comments on the target site.
My current solution is a simple jQuery each, iterating through all divs and firing a rest call for each div containing the individual target ID and then appending the number of comments on the target page.
However, there might be a huge amount of divs on the page, so the customer only wants the rest calls of the currently viewable divs fired while scrolling down the page.
Is there any way to do this?
IMPORTANT INFORMATION: i have to use jQuery 1.7 and it has to work in IE8! -.-
kind regards
Additional info:
All divs that are rendered by the template are visible, so i can't check for :visible. I need a way to check if they are in the viewport. I tried some inview-plugins etc., but they need a specific ID they are tied to, and then check if the element with this ID comes into view. However, all my elements have the same class and no ID at all as they are rendered by the same template.

A: You can try with $('.element').is(":visible")
http://jsfiddle.net/4mu18z2y/1/
I haven't tested it in IE8 though.

A: You have to get the window position and the offset top of each element...
$(document).ready(function(){
    var windowSize = $(window).height();
    console.log("Window size: " + windowSize);
    $(".test").each(function(){
        var top = $(this).offset().top; // element top position
        if(top < windowSize){
            console.log($(this));
            // your ajax call
        }
    });
});

Finddle: http://jsfiddle.net/m2wnbp2c/


text:
Q: Newlookuprow not return 2 Informatica I have a problem with the dynamic lookup of the Informatica. My new lookup row is only returning 0 (duplicate) and 1 (Insert) it never returns 2(update). When i added a new row with the same natural key and update a column in a row the lookup returns 1 rather 2 which is update!

A: You have (at least) of things to look for:

*

*Check in the property label of the lookup transformation that the
"Insert Else Updated" and "Update else insert" are checked (they are
not by default).

*Check also the port that could cause an update are correctly associated (in the port label) and have not the "Ignore in comparison" flag checked.

A: Okay i solved it! The problem is that you need to sort your table ports before creating the dynamic lookup!


text:
Q: How to update data using Web Services I'm trying to update my data on Xamarin. Android using Web Services. When i tried the web service on browser the data is updated in SQL Server and shows a message Account is successfully updated But when i bind the web service in the xamarin.android. The message shows ** The account is not exist** Can you help me fix my code pls!
I've tried using Web API as well but the data is not updated instead it shows an error Internal server error
Web service
        [WebMethod(MessageName = "PUT")]
        [System.Xml.Serialization.XmlInclude(typeof(ReturnData))]
        public ReturnData PUT(string FullName, string Gender, string ICNo, string Address,
            string PhoneNo, string Email, string Username, string Password, string PayMethod)
        {
            int IsAdded = 1;
            string Message = "";

            // check if this account is already created
            Users myUsers = new Users();
            if (myUsers.IsAvailable(Username, Email) == 0)
            {

                IsAdded = 0;
                Message = "Account is not exist";
            }
            else
            {
                //saving into db
                SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);

                try
                {
                    SqlCommand cmd = new SqlCommand("UPDATE pmsVehicleRecord SET clFullName=@fullName, clGender=@gen, clICNo=@ic, clAddress=@address, clPhoneNo=@phoneNo, clEmail=@email, clPwd=@pwd, clPaymentMethod=@payMethod WHERE clUsername=@username");

                    cmd.Parameters.AddWithValue("fullName", FullName);
                    cmd.Parameters.AddWithValue("gen", Gender);
                    cmd.Parameters.AddWithValue("ic", ICNo);
                    cmd.Parameters.AddWithValue("address", Address);
                    cmd.Parameters.AddWithValue("phoneNo", PhoneNo);
                    cmd.Parameters.AddWithValue("email", Email);
                    cmd.Parameters.AddWithValue("username", Username);
                    cmd.Parameters.AddWithValue("pwd", Password);
                    cmd.Parameters.AddWithValue("payMethod", PayMethod);
                    cmd.Connection = conn;
                    if (conn.State == System.Data.ConnectionState.Closed)
                        conn.Open();
                    SqlDataReader ds = cmd.ExecuteReader();

                    Message = "Account is successfully updated";
                }
                catch (Exception ex)
                {
                    IsAdded = 0;
                    Message = ex.Message;
                }
            }
            ReturnData rt = new ReturnData();
            rt.Message = Message;
            rt.lstIndex = IsAdded;

            return rt;
        }

    public class Users
    {
        public int IsAvailable(string UserName, string Email)
        {
            //Result result = new WebAppTest.Result();
            int lstIndex = 0;
            SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);

            try
            {
                SqlDataReader reader;
                {
                    SqlCommand cmd = new SqlCommand("SELECT lstIndex FROM pmsVehicleRecord WHERE clUsername=@username AND clEmail=@email");

                    cmd.Parameters.AddWithValue("username", UserName);
                    cmd.Parameters.AddWithValue("email", Email);
                    cmd.Connection = conn;
                    if (conn.State == System.Data.ConnectionState.Closed)
                        conn.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        lstIndex = reader.GetInt32(0);
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return lstIndex;
        }
    }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            EditText username = FindViewById<EditText>(Resource.Id.txtUsername);
            EditText fullName = FindViewById<EditText>(Resource.Id.txtFullName);
            EditText gender = FindViewById<EditText>(Resource.Id.txtGender);
            EditText icNo = FindViewById<EditText>(Resource.Id.txtICNo);
            EditText address = FindViewById<EditText>(Resource.Id.txtAddress);
            EditText phoneNo = FindViewById<EditText>(Resource.Id.txtPhoneNo);
            EditText email = FindViewById<EditText>(Resource.Id.txtEmail);
            EditText password = FindViewById<EditText>(Resource.Id.txtPwd);
            EditText payMethod = FindViewById<EditText>(Resource.Id.txtPayMethod);

            PUTWebRef.WebServicePMS webserUpdate = new PUTWebRef.WebServicePMS();
            webserUpdate.PUTAsync(username.Text, fullName.Text, gender.Text, icNo.Text, address.Text, phoneNo.Text, email.Text, password.Text, payMethod.Text);
            webserUpdate.PUTCompleted += WebserUpdate_PUTCompleted;
        }

        private void WebserUpdate_PUTCompleted(object sender, PUTWebRef.PUTCompletedEventArgs e)
        {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog alert = dialog.Create();
                alert.SetTitle("Error");
                alert.SetMessage(e.Result.Message);
                alert.SetButton("Ok", (c, ev) =>
                { });
                alert.Show();
        }

The expected output should be Account is successfully updates.
The actual output is The account is not exist


text:
Q: Javascript Basic animation problems I am trying to use pure JavaScript to animate a plus sign (+) but moving it up, when a button is clicked.
When the button is clicked, the plus sign moves up for about 100px and the animation ends. I would like to make it so that when the animation ends, another function brings back the plus sign back to its original position so that if the button is clicked again, the animation replies.
I cannot use jQuery for this, otherwise it would have been so much easier.

cool.onclick = function() {
  let start = Date.now();

  let timer = setInterval(function() {
    let timePassed = Date.now() - start;

    train.style.top = timePassed / -3 + 'px';

    if (timePassed > 300) clearInterval(timer);

  }, 1);

  /////////////////
  //code to return the + sign back to its original position fayded
  ////////////////
}
#train {
  position: relative;
  cursor: pointer;
}

#cool {
  position: relative;
  cursor: pointer;
  border: 1px solid red;
  width: 100px;
  text-align: center;
}

BUTTON

+

A: Of course, the way to do it is with CSS.  Use the translateY animation.  But if you are really wanting to do it with Javascript, your code would look more like this:

Notice, this code moves it both up and down, by changing the increment to +1 when the button is clicked (at the start of the onclick function), and to -1 when the widget reaches the top, then stopping the timer when the position is on its way down (increment is -1) and the position offset reaches zero.
Notice that when the user clicks the button, even if the + sign is halfway up or already coming back down, it will start going back up again.  Reach the top, and head back down.
I've set the interval to 10 milliseconds, that means that by incrementing the position by 1 pixel on each tick of the timer, it will go up 100 pixels in 1 second (100px * 10msec/px = 1 sec).  If you want the animation to go faster or slower, just change that interval time.
Also, you were trying to use some variable called train in train.style.top = ..., but you never set that.  You can use javascript to get at the div that has that id, by just simply calling document.getElementById.
You may have other issues, (like, in order for changing the top to work, you have to set the style of your train div to have absolute position), but this should get you closer.
Check out this fiddle.


text:
Q: XPath query working in XPath tester, but not in VB.NET Why does this XPath return a result in XPath Tester, but not in my code? I think that I'm overlooking something simple.
Sub Main()
    Dim doc As New XmlDocument()
    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

    Dim xmlNode As XmlElement = TryCast(doc.SelectSingleNode("/configuration/Status"), XmlElement)
    Dim xpath = "/Status/ElementOne[@ID='1234']"

    Console.WriteLine(xmlNode.OuterXml)

    Console.WriteLine()

    Console.WriteLine(xpath)

    Dim eFileEvent = xmlNode.SelectSingleNode(xpath)

    Console.WriteLine()
    Console.WriteLine("Results")

    If (eFileEvent Is Nothing) Then
        Return
    End If

    Console.WriteLine(eFileEvent.OuterXml)
End Sub

Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
  <configSections>
    <section name="Status" type="System.Configuration.IgnoreSectionHandler,     System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
         allowLocation="false" />
  </configSections>
  <Status xmlns="">
    <ElementOne ID="1234"></ElementOne>
  </Status>
</configuration>

A: It isn't clear how you did the test in XPath tester (or what exactly the XPath expression you tested), but I think your code is fair to fail because it is trying to get node having path configuration -> Status -> Status -> ElementOne which clearly doesn't exist :
Dim xmlNode As XmlElement = TryCast(doc.SelectSingleNode("/configuration/Status"), XmlElement)
Dim xpath = "/Status/ElementOne[@ID='1234']"

You can either fix the xpath variable value this way :
Dim xpath = "ElementOne[@ID='1234']"

or this way (single period (.) at the beginning is mandatory) :
Dim xpath = "./ElementOne[@ID='1234']"

or if possible, just get the right node in one line :
Dim xmlNode As XmlElement = doc.SelectSingleNode("/configuration/Status/ElementOne[@ID='1234']")


text:
Q: Give HTML time to render its text I have a very long VBScript code which runs in an HTA. The script includes DOM manipulation, DLL calls, and other scrips. Now I had a problem because it takes a significant amount of time to render the text on screen because there are a lot of scripts that pause the HTML parsing.
Now I'm planning to create a simple delay that would block the code execution but not the HTML parsing. But I don't know how to do it.
Update
Here is a sample code of what I want(sorry please don't mind the syntax I'm new to HTA vbs)
Sub Window_Onload()
    Call Main()
End Sub

Sub Main()
    Dim delay
    el.innerHtml = "Please"
    el2.innerHtml = "Help"
    el3.innerHtml = "me"

    'more scripts here
    'more scripts here
    'more scripts here
    'more scripts here

    el4.innerHtml = "this element is dependent to other scripts"
    el5.innerHtml = "this element is dependent to other scripts"
    el6.innerHtml = "this element is dependent to other scripts"

    delay = 2
    Call PauseAndRenderHtml(delay) 'this function will block the code execution
                                   'but not the html parsing

   'more scripts here

    Do While True
       'very long scripts that loops and pause, loops and pause........
    Loop
End Sub

Sub PauseAndRenderHtml(timeToBreath)
   'Take a breath :)
   'breath/pause for timeToBreath seconds
End Sub

I need the function PauseAndRenderHtml()

A: Perhaps a timer as described here might help:
<head>
<title>Sample</title>
<HTA:APPLICATION ID="oHTA"
     APPLICATIONNAME="Sample"
>
</head>

<script language="VBScript">
  idTimer = window.setTimeout(GetRef("PausedSection"), 10000, "VBScript")

  Sub PausedSection
    ContinueWork
    window.clearTimeout(idTimer)
  End Sub

  Sub ContinueWork
    'other code here
  End Sub
</script>

<body>
...
</body>

A: On page load, execute this as the first statement of your ASP script
Response.Buffer = false

This should render the HTML until there is a call to ASP or COM DLLs.
However, since in ASP, HTML and Logic are in the same page, it is more sequential.
Note: Response.Buffer is set to true by default and server will not send output until all of the scripts on the page have been processed, or until the Flush or End method has been called

A: This is what I use. For example, in a For loop, I'll call this at each loop and it'll update the HTML.
'This sleep function produces a near-instant delay for inserting a break in script execution
'mainly for updating HTML in the middle of script execution.
Sub Sleepy
    strCmd = "%COMSPEC% /c"
    objShell.Run strCmd,0,1
End Sub


text:
Q: Chrome for macOS shows raw HTML for gmail.com I posted this question in the google communities forum here but did not receive a response so I thought I'd ask here. I'm not sure if it's specific to apple but I thought it could be worth a shot trying this here first, over stack overflow.
When I visit gmail, Chrome doesn't render the HTML but just displays it raw, similar to if I had right-clicked and then regular clicked View Page Source. And it's just the source code and not an working HTML-only render.
Visiting the same URL with a different browser, on the same machine with the same OS, does render the HTML in the typical fashion.
How can I get Chrome to render the HTML rather than just print it out?
I've tried resetting Chrome to default settings, and uninstalling and re-installing Chrome. The problem still persists. I did just upgrade to Mojave but Chrome worked normally after the upgrade for awhile before it started behaving strangely.
Shot of how it appears.

A: This was solved thanks to a solution posted in the Google forum. It was solved but hitting command-shift-R. I have no idea why.
Link to forum post.


text:
Q: python and pip not in sync I installed ubuntu16.04 today and automatically went and installed python from their website.
Now I have python3.5 preinstalled in usr/bin and python3.6 installed in usr/local/bin.
When I type in pip3 -V in bash i get:

pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

When i type in python3 -V i get:

Python 3.6.5

So everything I do with pip3, wont follow through to python3.
How can I fix this?
I cant find how to uninstall just python3.6.
I tried making an alias for python3 in the hope itd overwrite it, it didnt.
I haven tried changing PATH order, I dont know how and if it would even fix it.
Also, apt-get remove python3.6 doesnt work, since it was installed via the browser.
I hope I provided enough info. Id be happy to provide more if needed


text:
Q: Puppet can't downgrade with ensure installed/latest I'm using the following in my Puppet manifest:
$packages = [
  '2klic-gateway=2.10.5',
]

package { $packages: ensure => latest }

Also tried using installed instead of latest. But I get back the following error:
Error: Could not update: Execution of '/usr/bin/apt-get q -y -o DPkg::Options::=-force-confold install 2klic-gateway=2.10.5' returned 100: Reading package lists...
Building dependency tree...
Reading state information...
The following package was automatically installed and is no longer required:
2klic-updates
Use 'apt-get autoremove' to remove it.
The following packages will be DOWNGRADED:
2klic-gateway
0 upgraded, 0 newly installed, 1 downgraded, 0 to remove and 5 not upgraded.
Need to get 22.0 MB of archives.
After this operation, 312 kB disk space will be freed.
E: There are problems and -y was used without --force-yes
Error: /Stage[main]/Main/Node[default]/Package[2klic-gateway=2.10.5]/ensure: change from purged to latest failed: Could not update: Execution of '/usr/bin/apt-get q -y -o DPkg::Options::=-force-confold install 2klic-gateway=2.10.5' returned 100: Reading package lists...
Building dependency tree...
Reading state information...
The following package was automatically installed and is no longer required:
2klic-updates
Use 'apt-get autoremove' to remove it.
The following packages will be DOWNGRADED:
2klic-gateway
0 upgraded, 0 newly installed, 1 downgraded, 0 to remove and 5 not upgraded.
Need to get 22.0 MB of archives.
After this operation, 312 kB disk space will be freed.
E: There are problems and -y was used without --force-yes

If I manually ssh into the node I can use apt-get install 2klic-gateway=2.10.5 and it works. I can also remove the program and then run puppet and the manifest works fine. But as soon as I add the -y flag I get:
E: There are problems and -y was used without --force-yes

A: I was able to fix this by telling Puppet to use --force-yes when installing like this:
package {
  $packages: ensure => installed,
  install_options   => ['--force-yes'],
}

I will leave this question open as, this answer is not safe.
--force-yes
       Force yes; this is a dangerous option that will cause apt to continue
       without prompting if it is doing something potentially harmful. It
       should not be used except in very special situations. Using force-yes
       can potentially destroy your system! Configuration Item:
       APT::Get::force-yes. This is deprecated and replaced by
       --allow-downgrades, --allow-remove-essential,
       --allow-change-held-packages in 1.1.

Option #2
If your nodes are running a system that have apt version 1.1 or higher you can use --allow-downgrades instead of --force-yes. This is a safer option though still not recommended in the man pages:
 --allow-downgrades
       This is a dangerous option that will cause apt to continue without
       prompting if it is doing downgrades. It should not be used except
       in very special situations. Using it can potentially destroy your
       system! Configuration Item: APT::Get::allow-downgrades. Introduced
       in APT 1.1.

Unfortunately in my situation my nodes are running apt version 1, so this would require first upgrading the version of apt.


text:
Q: Xpath return empty list but Xpath expression is correct and tested on browser console I am currently working on scraping similarweb datas using Scrapy Python in a virtual environment.
I have this example site : "https://www.similarweb.com/fr/website/golfgenius.com", and I want to scrape the number of visitors.
Unfortunately, divs and span are relatives so they won't have specific name you can scrape easily.
It means that if you wanna do a Xpath request you are going to have multiple answers everytime, unless you get a little more accurate.
So the span/text() I want is inside some span with relatives class names. (see screenshot)
The yellow highlighted expression is what i want, here is my Xpath expression yet :
//span[@class='engagementInfo-value engagementInfo-value--large u-text-ellipsis']/span[@class='engagementInfo-valueNumber js-countValue']/text()
On browser it highlight only one span(which is good) and the right one, so everything cool.
but if I try this expression inside scrapy shell for example, it returns me an empty list.
What am I doing wrong ? Is it not the way to get a text inside a span?
thank you if you wanna help !


text:
Q: pass Table data cell into Sql string so here is my mission. I have a datatable with one single row.  i'm trying to call one cell of data out from the table and pass it into a sql string dynamically for a filter. I do have data in my table when i see it in debug mode. but when i try to view my sql string in a console write line the values are blank, so i'm not sure if test this correctly or writing it incorrectly. I really don't want to deal with a reader since i have to open and close connection multiple times.
String sqlpquery = "select * form FeedPreping where path =" + dt.Rows[0]["path"] + " and subdirectory =" + dt.Rows[0]["subd"];

After researching i was not able to find any luck with out a loop process. This data table will always have only one row in it. So there is no need for a loop.
Thanks Tdubs

A: Besides the usual SQL Injection issues you will face (you should read more about How To: Protect From SQL Injection in ASP.NET), you're not escaping your strings (assuming path and subdirectory are strings.
You also have a typo in your statement - form instead of from
Try (notice single quotes around your string data)
String sqlpquery = "select * FROM FeedPreping where path ='" + dt.Rows[0]["path"] + "' and subdirectory = '" + dt.Rows[0]["subd"] + "'";

As Blake mentions, in the comments you should really be using parameters in your command.
For example
string sqlpquery = "select * from FeedPreping where path = @path and subdirectory = @subdir";
SqlCommand cmd = new SqlCommand(sqlpquery, conn);
cmd.Parameters.AddWithValue("@path", dt.Rows[0]["path"]);
cmd.Parameters.AddWithValue("@subdir", dt.Rows[0]["subd"]);

A: Here is a little easier way to read something similar to what you should have.
The syntax error has been corrected ( form should be from ) and was re-written to use parameters SQL.
I added 2 vars to hold your dt values so you can do null checking and set defaults if needed or required.
I went with SqlConnection as you do not have a particular flavor of SQL specified.
 string sqlpquery = "SELECT * FROM FeedPreping WHERE path = @path AND subdirectory = @subd";

// Added these so you can do a NULL check and default if necessary
var qryPath = dt.Rows[0]["path"];
var qrySubd = dt.Rows[0]["subd"];

 using (SqlConnection conn = new SqlConnection(connectionString)) {
      conn.Open();

      using (SqlCommand cmd = new SqlCommand(sqlpquery, conn)) {
           cmd.Parameters.AddWithValue("@path", qryPath);
           cmd.Parameters.AddWithValue("@subd", qrySubd);

           try {
                // sql execution and read here
           }
           catch {
                // exception handling
           }
      }
           conn.Close();
  }


text:
Q: How are these ObjC declarations different: ie what is this really doing? I'm trying to understand what this is doing in each case. Can someone explain what the first case is doing in detail and how it differs from the second? Thanks // :)
//declare in first case
NSManagedObjectModel *mom();

NSManagedObjectModel *mom() {
 static NSManagedObjectModel *mom = nil;
//implementation goes here...
 return mom;
}

vs.
//no declaration in second case
- (NSManagedObjectModel *) mom {
 static NSManagedObjectModel *mom = nil;
//implementation goes here...
 return mom;
}

A: The first is a standalone function; it's not tied to a class. You'd call it like:
NSManagedObjectModel *retVal = mom();

The second is an instance method definition, and thus is defined in the context of a class. You'd call it like:
NSManagedObjectModel *retVal = [someObject mom];


text:
Q: Testing for undefined variables in Ruby a la JavaScript? In JavaScript there's a useful way to test for a variable which has never been defined at any given point. For example, the following snippet of code will return true if the variable bob has not been defined:
typeof(bob)=='undefined'

How do I accomplish the same test in Ruby?
edit: I'm looking for a test which is equally compact in nature. I've come up with some awkward approximations using exceptions and such, but those aren't very pretty!

A: defined?(variable_name)

irb(main):004:0> defined?(foo)
=> nil
irb(main):005:0> foo = 1
=> 1
irb(main):006:0> defined?(foo)
=> "local-variable"

Here is a good write up on it.

A: Keep in mind that defined? returns a string if the variable is defined, nil if it isn't, so use conditional checking on its results. I think the syntax alludes that it would return a boolean.

A: defined? is a function that returns nil if the item is undefined.
defined? somevar
=> nil
somevar = 12
defined? somevar
=> "local-variable"

So:
if defined?(somevar)
  do_something
end

A: All use cases :
defined? ur_variable
=> nil

ur_variable= 12
defined? ur_variable
=> "local-variable"

another_variable = nil
defined? another_variable
=> "local-variable"

A: Can also test this way.
   if somevar.nil
        # not set do something
    else
        # is set do something else
    end


text:
Q: How do i use mysqli_real_escape I have been converting my site over from mysql to mysqli and am wondering how i use mysqli_real_escape_string like mysqli_real_escape_string. In other words, how do i treat the string with the new escape like the old escape would.
I uses to just do
mysql_real_escape_string($string);

But now i have to do
mysqli_real_escape_string(<-What should i put here?->,$string);

So what do i put in the first parameter to treat the string like the old escape?
Error:
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in /var/www/frostbase/core/functions/general.php on line 22

A: According to PHP Manual the prototype is
string mysqli_real_escape_string ( mysqli $link , string $escapestr )

That means as the first parameter you have to provide the mysqli link identifier, second parameter should be the string you want to escape
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$escapedValue = mysqli_real_escape_string($link, "yourString");
?>

A: Its better to use prepared statements as suggested here for security reasons. Mysql_real_escape_string might not be suffiecient to prevent sql injection e.g. because multibyte character sets can be abused despite the escape function ().mysql_real_escape_string() versus Prepared Statements.
Prepared statements in PHP can be used like this:
  $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
  $stmt->bindParam(1, $name);
  $stmt->bindParam(2, $value);

More information on prepared statements in PHP

A: All mysql* functions implicitly passed an opened connection around behind the scenes. In mysqli, you always have to pass the connection around explicitly. This is much better coding practice. For this, you have the choice between two styles, procedural and object oriented:
$link = mysqli_connect(...);

$string = mysqli_real_escape_string($link, $string);
$string = $link->real_escape_string($string);

Even better yet, you should be using prepared statements. See The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for some background information.

A: Nobody told you that you must not call this function manually, in the application code.
One can use this function only as a formatting facility, to support manually parsed placeholders (if any). Otherwise there is a decent chance to allow an injection.
Most people do not understand the meaning of this function. They imagine it is intended to protect their queries from injection. While it is not.
Assuming such a protection is your primary goal, you have to learn that it's prepared statement that does this noble job.
Most people do not understand the meaning of prepared statements too, confusing the general idea of a prepared statement with very limited implementation offered by some APIs.
One offered by mysqli is practically unusable, for whatever case that differs from silly manual example. Thus, one have to invent their own database library, build upon API (for which APIs actually intended but for some reason used in raw form everywhere, which is wrong).
So, here goes a safeMysql DBAL which you can learn proper usage of this function from, or just start using instead of ugly raw API calls.


text:
Q: EFCodeFirst - Initialize DB and create tables
Is there a way to create the tables through a SQL script when the database is initialized in EFCodeFirst approach. ( I mean, to avoid auto table creation and use my custom script instaead for table creation).
I've tried below approach, but it doesn't seem to be creating the table as per the SQL script. context.Database.ExecuteSqlCommand is supposed to work for DDL SQL as well as DML SQL.
class Class1
{

    public void InitializeDB()
    {
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

        var dbInitializer = new DbInitializer();
        Database.SetInitializer(dbInitializer);
        var target = new MyDbContext();
        target.Database.Initialize(true);
    }
}

public class DbInitializer : DropCreateDatabaseAlways<MyDbContext>
{
    private string CreateTableSQL = "CREATE TABLE [dbo].[UserLogins](" +
                         "[UserId] [int] IDENTITY(1,1) NOT NULL," +
                         "[UserName] [varchar](100) NOT NULL," +
                         "[FirstName] [nvarchar](200) NULL," +
                         "[LastName] [nvarchar](200) NULL )";

    public void InitializeDatabase(MyDbContext context)
    {
        context.Database.ExecuteSqlCommand(CreateTableSQL, string.Empty);
    }
}

A: If you inherit DropCreateDatabaseAlways you cannot change InitializeDatabase logic because that method is not virtual. Instead of inheriting DropCreateDatabaseAlways implement IDatabaseInitializer directly.


text:
Q: How to add xml to DOM with ReactJS component I want to put some xml in the DOM so that it can be accessed by another Component. But when I try to render it, I keep getting prop unknown errors, such as:

warning.js:36 Warning: Unknown prop colour on <category> tag. Remove this prop from the element. For details, see https://facebook.github.io/react/warnings/unknown-prop.html

I don't want React to interpret those attributes as props! It's just xml, not a react component!
This is the code I have:
class DefaultToolbox extends Component {
  render() {
    // static xml
    return (
      <xml id="toolbox" style={{display: "none"}}>
        <category name="Logic" colour="#5C81A6" />
        // ... etc etc
      </xml>
    );
  }
}

A: return (<span dangerouslySetInnerHTML={{ __html: `<xml ..> ... </xml>` }}/>);

for more information: https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml


text:
Q: Unable to select the wordrpess posts publish button by JQuery? I'm trying to disable the publish button and enable it only on when condition is met, but I can't seem to select the button by jQuery, my code does not work even though everything is fine, but when I try to directly write the code on console it does work just fine. also this problem happens only on Gutenberg editor not the classic editor.
I have tried to clear browsers cache but nothing seems to work. tried to select other element on the Gutenberg editor but no luck.
$('.editor-post-publish-panel__toggle').first().attr("disabled", true);

A: Since we have Gutenberg as an editor it has it's won ruleset.
You need to enqueue your javascript to Gutenberg editor
function myguten_enqueue() {
    wp_enqueue_script(
        'myguten-script',
        plugins_url( 'myguten.js', __FILE__ )
    );
}
add_action( 'enqueue_block_editor_assets', 'myguten_enqueue' );

Click here for reference


text:
Q: R delete last row in dataframe for each group I would like to delete the last row in a dataframe for each group in R based on max(start_date).
Example data:
id      start_date  end_date
1       2016-01-14  2016-02-14
1       2016-03-14  2016-08-05
2       2014-01-14  2014-02-14
2       2015-03-21  2015-05-21
2       2015-08-23  2015-09-23
2       2015-11-21  2016-01-03

Result:
id      start_date  end_date
1       2016-01-14  2016-02-14
2       2014-01-14  2014-02-14
2       2015-03-21  2015-05-21
2       2015-08-23  2015-09-23

The following does not work:
df <- df %>%
   group_by(id) %>%
   summarise(start_date != max(start_date))

Error: found duplicated column name: id
df <- sqldf("select * from df group by id having start_date != max(start_date)")

error in statement: duplicate column name: id
Any suggestions would be great.

A: We can use slice (assuming that the dates are already ordered)
df1 %>%
   group_by(id) %>%
   slice(-n())
#     id start_date   end_date
#   <int>      <chr>      <chr>
#1     1 2016-01-14 2016-02-14
#2     2 2014-01-14 2014-02-14
#3     2 2015-03-21 2015-05-21
#4     2 2015-08-23 2015-09-23

If the dates are not ordered, then arrange and slice
df1 %>%
   group_by(id) %>%
   arrange(start_date) %>%
   slice(-n())

Based on some previous benchmarks (couldn't find the link), the arrange/slice method would be faster than comparing start_date != max(start_date)


text:
Q: Do projections preserve closed subspaces Let $H$ be a Hilbert space and let $\pi \colon H \to H$ be an orthogonal projection. Let $E \subset H$ be a closed subspace of $H$.
My question: Is there any hope that one can conclude that $\pi(E)$ is closed?

A: This is not true. Let's take $H=L^2(\mathbb R)$ and $E=PW_1$ as the subspace of all $f$ whose Fourier transform is supported by $[-1,1]$ (the Paley-Wiener space). Let $\pi$ be the projection onto $L^2(-1,1)$.
Then $f=\chi_{(-1,1)}(x)$ is in $\overline{\pi(E)}$: this follows because
$$
\frac{\sin ax}{ax} = \frac{1}{2a}\int_{-a}^a e^{itx}\, dt \in E
$$
for all small $a>0$, and clearly these functions converge to $f$ uniformly on $(-1,1)$ as $a\to 0$.
However, $f\notin\pi(E)$ because the functions from $E$ are entire, but the holomorphic continuation of $f$ from $(-1,1)$ to $\mathbb R$ is identically equal to $1$ and thus not in $L^2(\mathbb R)$.


text:
Q: What does pending approval mean? I have submitted my profile online to the company for consideration of deal with me on my ideas and the company has mentioned online that  my profile is pending approval; what does pending approval mean for my profile?

A: The ability to automatically generate a profile (or add any content) on someone else's website will depend on controls that they have in place.
Some companies don't care about or monitor what goes onto their sites and leave it to the user to generate, and the computer system to upload them instantly and automatically.
However, in this case, the company obviously likes to maintain control over what goes onto their site, and so the system is set to require a manual (human) intervention before any profile is uploaded.
Yours is pending (waiting for that human intervention) approval.
HTH