text:
Q: Is plugin_LTLIBRARIES a buildin variable like lib_LTLIBRARIES and noinst_LTLIBRARIES? Recently I read the source code of strongswan. And I found this piece of script in one Makefile.am. I didn't see plugin_LTLIBRARIES before. I searched on the internet. Most of the result is Makefile.am files. Is is a M4 macro or a buildin variable? What's the usage of it?
if MONOLITHIC
noinst_LTLIBRARIES = libstrongswan-socket-default.la
else
plugin_LTLIBRARIES = libstrongswan-socket-default.la
endif

A: Any automake variable of the form foo_PRIMARY installs to $(foodir). $(plugindir) might be set via AC_SUBST in configure.ac.
m4 isn't used in handling Makefile.am. They're parsed with automake, a perl program, because the logic involved in building the Makefile.in template is much more subtle than straight macro expansion.


text:
Q: How to pushViewController when more than one tableViewControllers (no storyboards) I don't know how to implement a detail view of a table view controller, when that table view controller comes up as a result of user interaction with a tab bar controller that is not the primary view for the app. I think I need to create a second UINavigationController but I don't know how to integrate it into the master and detail view controllers that will use it, though I have a navigation controller that works for my primary view controller (EdgewoodSecretsMasterViewController)
(I read PushViewController with tabBarController not working)
I'm not yet using storyboards.
My app's root view is a table view controller called EdgewoodSecretsMasterViewController  The user can select a row in the table it populates, display a detailed view, and return to the EdgewoodSecretsMasterViewController table view.
I also have a tab bar on the bottom of this main view. It has 3 choices. One is EdgewoodSecretsMasterViewController It comes up when the user starts the app. The user can select a row in the table, view info on a detail view about that choice and return to the table view.
In app delegate I create vcMaster , an EdgewoodSecrets class
 EdgewoodSecretsMasterViewController *masterViewController = [[EdgewoodSecretsMasterViewController alloc] initWithNibName:@"EdgewoodSecretsMasterViewController" bundle:nil];

 UINavigationController * vcMaster = [[UINavigationController alloc] initWithRootViewController:masterViewController];

The second tab bar choice is an informational view the author information page. The user can select it, and return to the original table view but clicking on the first tab bar choice
WhoIsAuthor* vcAu = [[WhoIsAuthor alloc] init];

These two choices work as I want them to.  But not the third tab.
Third tab is vcImportant
   ImportantMasterViewController* vcImportant = [[ImportantMasterViewController alloc] init];

   initWithNibName:@"ImportantMasterViewController"
   bundle:nil ];

Here I put all the tab choices into the tab bar controller
   UITabBarController *tabBar = [[UITabBarController alloc] init];

   NSArray* controllers = [NSArray arrayWithObjects:vcMaster, vcAu,vcImportant,
                         nil];

   tabBar.viewControllers = controllers;
  [[self window] setRootViewController:tabBar];

The third tab choice brings up another table view - ImportantMasterViewController. That table view populates with several choices, but when the user makes a choice, the pushViewController directive doesn't know anything about the original navigation bar controller. At the push point self.navigationController doesn't have a value. I think this is because the tab bar controller is the root view controller. So I think it's the highest level/in charge I don't know to say that.
In PushViewController with tabBarController not working
I see that Alok Singh responded "For each tab you need to create a separate navigation controller"
I can create a second UINavigationController object in my appDelegate. But I don't know how to use it beyond setting it up in the app delegate like this
 UINavigationController * ncImportant = [[UINavigationController alloc]
      initWithRootViewController:importantMasterViewController];

Seems like somewhere there must be one stack, that holds the last object that got pushed. It seems like I should be pushing all my view controllers on that stack.
In EdgewoodSecretsMasterViewController I push my detail view like this
 [self.navigationController pushViewController:self.detailViewController animated:YES];

The detail view comes up The user can go back and forth
In WhoIsAuthor I don't bring up a detailed subordinate view
In ImportantMasterViewController
I attempt to push my detail view like this
 [self.navigationController pushViewController:self.importantDetailViewcontrollers animated:YES];

The detail view does not come up.
I know that execution gets to this point.
I can also see that
     self.navigationController
doesn't have a value like it did in EdgewoodSecretsMasterViewController at this point
And that is - if I understand the other posting right - because it needs it's own navigation controller. But I don't know how to associate the navigation controller I create (ncImportant) in the app delegate with this push
I don't know how to think this through, or what to go and read to understand it.
Thank you
Laurel

A: You need put all the tab choices into the tab bar controller with ncImportant not vcImportant
UITabBarController *tabBar = [[UITabBarController alloc] init];

NSArray* controllers = [NSArray arrayWithObjects:vcMaster, vcAu,ncImportant,
                         nil];

tabBar.viewControllers = controllers;
[[self window] setRootViewController:tabBar];

A: *

*Make UITabBarController as your rootViewController.

*Add all the tabs, in each tab you can initialise it with either
a)  UINagivationController which in turn is initialised with a
UIViewController instance.
b) Or just your UIViewContollers

*On load of your app, you can always select a Specific Tab that should be shown up.

*Then further, you can use either a Push or a Modal methods to show up the OtherViewContollers1 as the details to your selected item in one of the TabBarController's item.
See this :

*

*This is my Root ViewController ( A Tab bar with Three Tabs in it)

*

*This is a DetailViewController which has a UITableView as instance in it. It is modally presented on t he TabBar when I click an item in the above table View.

*See how it is being presented Modally.

Hope that Helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RSPEC - ways to create Models with different parameters / avoid duplication I have 3 tests for a Model, and the main difference between them all is the number of parameters passed when each is created.  I'm pretty much running the same expectation on each version of the Model to boot, so there is a lot of duplication.  I was just wondering if there was a cleaner way of doing this.  Here is my code:
    describe Item do
  subject {Item.new( :report_id => 15 ,  :name => 'Gas' ,  :tax_id => 1 ,  :category_id => 15 ,  :sub_category_id => 1 ,  :job_id => 1 , :total => 20 )}
  let(:tax) {Tax.where(id: subject.tax_id).first}
  let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}

  it 'Calculate with just Total' do
    subject.name.should be == 'Gas'
    subject.set_nil_values
    sub_category.should_receive(:taxable).and_return(sub_category.taxable)
    tax.should_receive(:rate).and_return(tax.rate)
    sub_category.should_receive(:tax_adjustment).and_return(sub_category.tax_adjustment)
    subject.calculate_tax
    subject.calculate_cost
    subject.cost.should be_within(0.01).of(17.70)
    subject.tax_amount.should be_within(0.01).of(2.30)
    subject.save
  end

end

  describe Item do
    subject {Item.new(:report_id => 15 ,  :name => 'Gas' ,  :tax_id => 1 ,  :category_id => 15 ,  :sub_category_id => 1 ,  :job_id => 1 ,  :tax_override => 2.30 ,  :total => 20  )}
    let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}

    it 'Calculate with tax override' do
      @tax = Tax.find(subject.tax_id)
      subject.name.should be == 'Gas'
      tax = Tax.find_by_id(subject.tax_id)

      subject.set_nil_values
      sub_category.should_receive(:taxable).exactly(1).times.and_return(sub_category.taxable)
      tax.should_receive(:rate).exactly(1).times.and_return(tax.rate)
      sub_category.should_receive(:tax_adjustment).exactly(1).times.and_return(sub_category.tax_adjustment)
      subject.calculate_tax
      subject.calculate_cost
      subject.cost.should be_within(0.01).of(17.70)
      subject.tax_amount.should be_within(0.01).of(2.30)
      subject.save
    end

     describe Item do
        subject {Item.new(  :report_id => 16 ,  :name => 'Gas' ,  :tax_id => 1 ,  :category_id => 15 ,  :sub_category_id => 1 ,  :job_id => 1 ,  :tax_override => 1.15 ,  :unclaimed_tax => 1.15 ,  :total => 20
          )}
        let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first}

        it 'Calculate with Unclaimed Tax' do
          @tax = Tax.find(subject.tax_id)
          subject.name.should be == 'Gas'
          tax = Tax.find_by_id(subject.tax_id)

          subject.set_nil_values
          sub_category.should_receive(:taxable).exactly(1).times.and_return(sub_category.taxable)
          tax.should_receive(:rate).exactly(1).times.and_return(tax.rate)
          sub_category.should_receive(:tax_adjustment).exactly(1).times.and_return(sub_category.tax_adjustment)
          subject.calculate_tax
          subject.calculate_cost
          subject.cost.should be_within(0.01).of(17.70)
          subject.tax_amount.should be_within(0.01).of(1.15)
          subject.unclaimed_tax.should be_within(0.01).of(1.15)
          subject.save
        end
    end

A: You should use factories and FactoryGirl gem.
Also, please format your code appropriately, it's difficult to read.


text:
Q: GmailApp.search() seems to fail correct data I am trying to get no of emails for yesterday according to one particular subject.
Usually, what I do at midnight 1 o'clock I count the no of emails for a particular subject and send the mail through Google script. At 3 o'clock I trigger one delete trigger which starts deleting mail of previous day.
so by this, I ensure I don't have any mail for the previous day.
var yesterday = "2017/7/10";
  var today = "2017/7/11";
var query = "after:"+yesterday+" before:"+today+" subject: abcd";

To count no of emails I have written below function
function getEmailCount(query) {
  var threads = GmailApp.search(query, 0, 500);
  Logger.log(threads);
  var total = 0;

  for (var i = 0; i < threads.length; i++) {
    var messagesInThread = threads[i].getMessageCount();
    var msg = threads[i].getMessages()[0].getSubject()
    total = total + messagesInThread;
  }
  Logger.log(msg)
  Logger.log("Query %s", query);
  Logger.log("No. Of Threads %s", threads.length);
  Logger.log("No. Of Emails %s", total);
  return total;
}

When I check for emails in Gmail with above subject I get only 8 but my script is returning 25 mails. Any help will be highly appreacated .

A: It is interesting, GMailApp does return some emails within threads outside of the search parameters that the Gmail web app was not. I have a suspicion this was a time-zone related thing due to the nature of the specific emails I was looking at.
Some modifications to your code can add for a couple of checks that differentiate the raw results and some of the UX that the web app throws in for free. Additionally, this filters threads and messages that strictly adhere to the search criteria.
function getEmailCount(query) {
  var yesterday = "2017/06/07",
      today = "2017/06/08",
      yesterdayDate = new Date(yesterday),
      todayDate = new Date(today);

  query = query || "after:" + yesterday + " before:" + today + "";

  var threads = GmailApp.search(query).reduce(function(validThreads, thread, idx) {

    var messages = thread.getMessages().reduce(function(messages, message, idx) {
      var isChat = message.isInChats(),
          isDeleted = message.isInTrash(),
          sent = message.getDate();

      if (!isDeleted && !isChat && sent < todayDate && sent > yesterdayDate) {
        messages.push(message.getSubject());
      }

      return messages;
    }, []);

    if (messages.length > 0) { validThreads[idx] = messages; }

    return validThreads;
  }, {});

  var totalMessages = Object.keys(threads).reduce(function(count, thread) {
    return count += threads[thread].length;
  }, 0);

  Logger.log("Query: %s", query);
  Logger.log("No. Of Threads: %s", Object.keys(threads).length);
  Logger.log("No. Of Emails: %s", totalMessages);

  return totalMessages;
}


text:
Q: Using map and filter on multiple arrays in an object Using Wikipedia's API I got an object which looks like that:
obj = {["string", Array[10], Array[10], Array[10]]}

The first array contains titles, second is descriptions and third is links.
Some of the descriptions may be empty ("").
Example -

I would like to combine all three arrays into one array as follow:
[{title: obj[1][0], desc: obj[2][0], link: obj[3][0]}, ... , {title: array[1][9], desc: obj[2][0], link: obj[3][0]}]

But only combining if description is not empty - obj[2][i] !== ""
I managed to do it using for loop and if:
var arr = [];
for (var i = 0; i < data[1].length; i++) {
  if (data[2][i] !== '') {
    arr.push({title: data[1][i], desc:data[2][i], link: data[3][i]});
  }
}

Is there a way of achieving the same in a more elegant way using javascript's high order function? such as map and filter (maybe reduce?)
Thanks
EDIT:
The way I did it in the end was:
var resp = ["Football",
  ['Football', 'Soccer'],
  ['FootballDescription', 'SoccerDescription'],
  ['http://football.com', 'http://soccer.com']
];

// Mimic python's zip behavior -> assume arrays are of equal size
function zip(arrays) {
  return arrays[0].map(function(_, i){
    return arrays.map(function(array){
        return array[i];
    });
  });
}

// 1. Throw away the first string, e.g. "Football"
resp.shift();

// 2. Use zip to make an array of intersected arrays, i.e
// [
//   ['Football', 'FootballDescription', 'http://football.com'],
//   ['Soccer', 'SoccerDescription', 'http://soccer.com']
// ]
// and then use map to make each array into a nicely named object
var objects = zip(resp).map(function(x) {
    return ({ name: x[0], desc: x[1], link: x[2] });
});

console.log(objects);
/*
Output:
[ { name: 'Football',
    description: 'FootballDescription',
    link: 'http://football.com' },
  { name: 'Soccer',
    description: 'SoccerDescription',
    link: 'http://soccer.com' } ]
*/

A: You're about to learn an awesome new higher-order function, zip! To be honest, I very rarely run into situtations where it is useful, but your example happens to be perfect for it.
/*
 Example in ES6. In order to run, first install node and then go
  npm install -g babel
  npm install underscore
  babel thisfile.js | node
*/

let _ = require('underscore')

let resp = [
  "Football",
  ['Football', 'Soccer'],
  ['FootballDescription', 'SoccerDescription'],
  ['http://football.com', 'http://soccer.com']
]

// 1. Throw away the first string, e.g. "Football"
resp.shift()

// 2. Use zip to make an array of intersected arrays, i.e
// [
//   ['Football', 'FootballDescription', 'http://football.com'],
//   ['Soccer', 'SoccerDescription', 'http://soccer.com']
// ]
// and then use map to make each array into a nicely named object
let objects = _.zip(
  resp[0],
  resp[1],
  resp[2]
).map(x => ({
  name: x[0],
  desc: x[1],
  link: x[2]
}))

console.log(objects)
/*
Output:
[ { name: 'Football',
    description: 'FootballDescription',
    link: 'http://football.com' },
  { name: 'Soccer',
    description: 'SoccerDescription',
    link: 'http://soccer.com' } ]
*/

A: There's no need to involve another library if you don't want. Map and filter work here but I think they add a lot of length. I'd favor forEach.
Keep in mind that Array.prototype.forEach passes along up to three parameters to your callback function. In this case you can get by with two.
data[2].forEach(function(elem, index) {
  elem && arr.push({title: data[1][index], desc: elem, link: data[3][index]});
});

And a solution using map and filter might look like
data[1].map(function(elem, index) {
  return ({
    title: data[1][index],
    description: data[2][index],
    link: data[3][index]
  });
}).filter(function(elem) {
  return elem.description;
});

A: Looks like you need some lodash/underscore in your life…
http://underscorejs.org/
https://lodash.com/
They are libraries that do exactly that. Take Objects/Arrays and slice and dice them until they are what you want.  Super useful.
Or you could just do it in plain ol' reduce…
var crazyArray = ['title here', ['one', 'two', 'three'], ['four', 'five'], '', ['six']]
var reduced = crazyArray.reduce(function( last, cur ){
  if(cur) return last.concat(cur);
  return last;
}, []);
console.log(reduced) // [ 'title here', 'one', 'two', 'three', 'four', 'five', 'six' ]


text:
Q: How to rename all id in a cloned form (javascript)? I have a form (commonStuff) cloned this way (and an html page, designed in jquery mobile, where the form appears multiple times, cloned):
var commonClone = commonStuff.cloneNode(true);

and this function
function renameNodes(node) {
    var i;
    if (node.length) {
        for (i = 0; i < node.length; i += 1) {
            renameNodes(node[i]);
        }
    } else {
        // rename any form-related elements
        if (typeof node.form !== 'undefined') {
           node.id = currentPrefix + '_' + node.id;
           node.name = currentPrefix + '_' + node.name;

        // This assumes that form elements do not have child form elements!
        } else if (node.children) {
            renameNodes(node.children);
        }
    }
}

which add a prefix 'form1_', 'form_2' (the currentPrefix) to id and names of any element in the form and is applied to commonClone (and so recursively to his sons).
renameNodes(commonClone);

It work perfectly in case of text inputs like

        Age:
        <input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">

But it fails on radio buttons like

        <fieldset data-role="controlgroup" data-type="horizontal">
            <legend>Address:</legend>
                <input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />
                Address 1

                <input type="radio" name="radio-address" id="radio-address_male" value="2"  />
                Address 2
        </fieldset>

applying the renaming to the outer divs like 'fieldcontain' and 'controlgroup'. It works if i remove those two divs but the graphical effect is unacceptable...
As far as now, i got the problem is in the last 'else if' block for it doesn't care of siblings, but I don't really know how to fix this. Any idea?
EDIT: This code comes from this answer How to create a tabbed html form with a common div

A: As you use jQuery mobile, jQuery will be available.
I hope this code will point you in the right direction:
var i = 0;
$("form").each(function() {
  $(this).find("input, select").each(function() {
    $(this).attr("id", "form" + i + "_" + $(this).attr("id"));
    $(this).attr("name", "form" + i + "_" + $(this).attr("name"));
  });
  $(this).find("label").each(function() {
    $(this).attr("for", "form" + i + "_" + $(this).attr("for"));
  });
  i++;
});

EDIT:
I understand your current approach fails with labels. Consider to wrap your input elements inside the label tag. In that case, you won't need the for-attribute. This is in accordance with the docs: http://api.jquerymobile.com/checkboxradio/
Consider this:
HTML
<form>

    <fieldset data-role="controlgroup" data-type="horizontal">
      <legend>Address:</legend>
      <input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />Address 1
      <input type="radio" name="radio-address" id="radio-address_male" value="2" />Address 2
    </fieldset>

    <input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">Age:

</form>

jQuery
var i = 0, currentPrefix = "form";
$("form").each(function() {
  $(this).find("input, select").each(function() {
    $(this).attr("id", currentPrefix + i + "_" + $(this).attr("id"));
    $(this).attr("name", currentPrefix + i + "_" + $(this).attr("name"));
  });
  i++;
});

Workin fiddle: https://jsfiddle.net/EliteSystemer/8sx6rnwo/

A: Truly, this is far from elegant, but a solution, anyway. In any node, this searches manually for input and labels, changing id, names and 'for' attribute in case of labels.
 function renameNodes(node) {
    var i;
    if (node.length) {
        for (i = 0; i < node.length; i += 1) {
           renameNodes(node[i]);
        }
    } else {
        // rename any form-related elements
        if (typeof node.form !== 'undefined') {
           node.id = currentPrefix + '_' + node.id;
           node.name = currentPrefix + '_' + node.name;

           var inputs = node.getElementsByTagName('input');
           for (i = 0; i < inputs.length; ++i) {
                inputs[i].id = currentPrefix + '_' + inputs[i].id;
                inputs[i].name = currentPrefix + '_' + inputs[i].name;
           }
           var labels = node.getElementsByTagName('label');
           for (i = 0; i < labels.length; ++i) {
                labels[i].setAttribute('for', currentPrefix + '_' + labels[i].getAttribute("for"));
           }
        } else if (node.children) {
           renameNodes(node.children);
        }
    }
 }


text:
Q: How to ensure that row names and column names are in the same order for QAP analysis I am working with network adjacency matrices in R for a QAP regression. Currently, the matrices look like this (ignore 0s and 1s):
How can I make the column/row labels appear in the same order between time 1 and 2? I have sorted the initial edgelists (q1 and q2 in the code below), but something appears to get lost in translation when converting these to one mode adjacency matrices.
q1_2001<-graph.data.frame(q1, directed=FALSE)
q2_2002<-graph.data.frame(q2, directed=FALSE)
V(q1_2001)$type <- bipartite_mapping(q1_2001)$type
V(q2_2002)$type <- bipartite_mapping(q2_2002)$type
q1bp_2001<-bipartite.projection(q1_2001)
q2bp_2002<-bipartite.projection(q2_2002)
q1edge2001<-as_edgelist(q1bp_2001$proj1)
q1edge2002<-as_edgelist(q2bp_2002$proj1)
##Predictor Matrix (IV)
qap2001A<-get.adjacency(graph.data.frame(q1edge2001),sparse = FALSE)
qap2001A[order(decreasing = TRUE)]
##Response Matrix (DV)
qap2002B<-get.adjacency(graph.data.frame(q1edge2002),sparse = FALSE)

A: Assuming that the 2 matrices are of the dimensions and the column names and row names are the same (although they may appear in different order), you can get the desired result with the following:
Time2 = Time2[rownames(Time1), colnames(Time1)]

For example
set.seed(1)
Time1 = replicate(5, sample(0:1, 5, replace = T))
Time2 = replicate(5, sample(0:1, 5, replace = T))

colnames(Time1) = rownames(Time1) = c("22B", "13B", "999B", "11B", "03B")
colnames(Time2) = rownames(Time2) = c("22B", "999B", "11B", "13B", "03B")

> Time1
     23B 13B 999B 11B 03B
23B    0   1    0   0   1
13B    0   1    0   1   0
999B   1   1    1   1   1
11B    1   1    0   0   0
03B    0   0    1   1   0

> Time2
     22B 999B 11B 13B 03B
22B    0    0   1   1   1
999B   0    1   1   1   0
11B    0    0   0   1   0
13B    1    0   1   1   1
03B    0    1   0   1   1

# Notice that Time1 and Time2 are similar to your example but with different entries. The column names and row names are the same but in different order

Time2 = Time2[rownames(Time1), colnames(Time1)]

> Time2
     22B 13B 999B 11B 03B
22B    0   1    0   1   1
13B    1   1    0   1   1
999B   0   1    1   1   0
11B    0   1    0   0   0
03B    0   1    1   0   1


text:
Q: Changing pane color by using combo box, I have tried the method in code below but It didn't work I want to change a specific pane color by using combo box. Whenever I select a color, grey for example, It changes the color of the Pane. I tried this code but it didn't do anything.
    **@FXML
    private void Select(ActionEvent event) {

        String myColor = ColorBox.getValue();

        if (myColor.equalsIgnoreCase("blue")){
            Pane.setStyle(myColor);
        } else if(myColor.equalsIgnoreCase("white")){
            Pane.setStyle("fx-background-color: white");
        } else if(myColor.equalsIgnoreCase("grey")){
            Pane.setStyle("fx-background-color: grey");
        }**

    }

}

A: I solved it:
@FXML
private void Select(ActionEvent event) {
    String myColor = ColorBox.getValue();

    if (myColor.equalsIgnoreCase("white")){
        Pane.setBackground(new Background(new BackgroundFill(Color.WHITE,null,null)));


text:
Q: Cannot run container image even with image referenced on devcontainer.json I´m using the Remote Containers extension (version 0.59.0) on VS Code (version 1.35.0) on Ubuntu 18.04 and I got the following error (I removed the image id for mycustomimage-id) when I click on Remote-Containers: Reopen Folder in Container:
Setting up container for folder: /home/user/source/project
Run: docker exec mycustomimage-id test -d /root/.vscode-server
cannot exec in a stopped state: unknown
Run: docker exec mycustomimage-id test -d /root/.vscode-remote
Error response from daemon: Container mycustomimage-id is not running
Run: docker exec mycustomimage-id /bin/sh -c set -o noclobber ; mkdir -p '/root/.vscode-server/data/Machine' && { > '/root/.vscode-server/data/Machine/.writeMachineSettingsMarker' ; } 2> /dev/null
Error response from daemon: Container mycustomimage-id is not running
Run: docker exec mycustomimage-id /bin/sh -c (cat /etc/os-release || cat /usr/lib/os-release) 2>/dev/null
Error response from daemon: Container mycustomimage-id is not running
Run: docker exec mycustomimage-id test -d /root/.vscode-server/bin/553cfb2c2205db5f15f3ee8395bbd5cf066d357d
Error response from daemon: Container mycustomimage-id is not running
Installing VS Code Server for commit 553cfb2c2205db5f15f3ee8395bbd5cf066d357d
Run: docker exec mycustomimage-id mkdir -p /root/.vscode-server/bin/553cfb2c2205db5f15f3ee8395bbd5cf066d357d_1560180323972
Error response from daemon: Container mycustomimage-id is not running

My devcontainer.json is the following:
// See https://aka.ms/vscode-remote/devcontainer.json for format details.
{
    "name": "Load image",
    "context": "..",
    "image": "mycustomimage:20190531",
    "runArgs": [
        "--cap-add=SYS_PTRACE",
        "--security-opt",
        "seccomp=unconfined",
        "-e", "REPO_TOKEN=${env.REPO_TOKEN}",
        "-e", "BUILD_CONFIGURATION=Debug",
        "--entrypoint","/bin/bash"
    ],

    "extensions": ["ms-vscode.cpptools"],
    "workspaceFolder": "/src/remoteproj",
    "workspaceMount": "source=/home/user/source/project,destination=/src/remoteproj,type=bind"
}

I´ve tried with the running container and also when I don´t have any running container. How I ensure that the image referenced in the devcontainer.json is the same that the VS Code is trying to start?


text:
Q: How disable betterForm javascript I use exist-db with betterFORM to change xforms to HTML but betterFORM made a lot of javascript that I don't need it. Please help me to disable generate javascript in betterFORM.

A: This is a misunderstanding i think. The script is needed for betterFORM to work as all interaction is based upon AJAX requests happening under the hood. Therefore the script cannot be disabled.


text:
Q: Set custom variables to calEvent in jQuery weekcalendar I am working with the jQuery weekcalendar to show a web based calendar with appointments. Some build-in functions like setEventUserId store some variables in the calEvent.
What do I have to do to store custom variables in this calEvent object?
Something like:
setEventCategoryId: function(calendarId, calEvent, calendar) {
  calEvent.calendarId = calendarId;
  return calEvent;
},
getEventCategoryId: function(calEvent, calendar) {
  return calEvent.calendarId;
}

But when do I call this method? And is it enough to only have this piece of code to store the variable?
Any input is much appreciated.

A: The variables stored internally by the plugin are used internally by the plugin.  Your custom variables are not used internally by the plugin so it makes no sense to store them using the plugin.
You can store arbitrary data against elements using jQuery's .data() function.
http://api.jquery.com/data/
For example to set:
$(calEvent).data('calendarId', calendarId);

To retrieve:
var calendarId = $(calEvent).data('calenderId');


text:
Q: What is the difference between "keras", "tensorflow.keras" and "tensorflow.python.keras"? I found there are 3 types of keras when I want to import keras: "keras", "tensorflow.keras" and "tensorflow.python.keras".
I always use 'import keras' directly. But I want to know if I made some modifications on the tf.gradients, would my keras model be affected?
For example, I want to use a package named 'gradient-checkpointing' which need to replace the default tf_gradients by customized gradients:
from tensorflow.python.ops import gradients as tf_gradients
tf_gradients.gradients = gc.gradients_speed
But If I use 'import keras' to build model, would my keras-based model call the new gc.gradients_speed??
Update:
I know 'tf.keras' is recommended for normal user. I also know that 'tf.python.keras' is private and is just used by developmenters. But here I want to use my own customerzed gradients strategy which requires 'tf.python.ops.gradients'.
So my question is: if I use modified 'tf.python.ops.gradients', which 'keras' would be affected? 'tf.keras'? or 'keras' ? or 'tf.python.keras'? (I hope to choose one keras which calls 'tf.python.ops.gradients' so that I can verify if my customerzed gradient actually works.


text:
Q: Display all groups on a Sharepoint page I would like to display a list of all 365 groups on a sharepoint site, so users can simply scroll through them and request access to those they need.
However, I am unsure how to achieve this. When using the Sites-element, it only lets me add groups that I am a member of. Do I need to assign every single group to me?
Is there a workaround or a better way to do this? Searching for the exact URL or slug doesn't work either.


text:
Q: Scala "primitive" optimisation In several places I have seen a declaration similar to:
"The Scala compiler uses Java arrays, primitive types, and native arithmetic where possible in the compiled code"
(Programming in Scala book).
But in practise I am not seeing this, for example in the following code, the scala type is using more memory than the java type (which I calculated by using the totalMemory and freeMemory methods):
long[] la = new Array[java.lang.Long](1024 * 1024);
for(i <- 0 until la.length)
  la(i) = new java.lang.Long(0);

val La = new Array[Long](1024 * 1024);
for(i <- 0 until La.length)
  La(i) = 0l;

mem_used (java long):>> 28.811M
mem_used (scala long):>> 36.811M
I realise the scala Any type has additional overhead, but where is the optimisation happening?

A: Why bother with such a convoluted way of trying to find out what gets compiled to what? Just run javap on a class and you'll see exactly what it is.
C:\>type La.scala
class La {
    val La = new Array[Long](1024 * 1024);
}

C:\>javap La
Compiled from "La.scala"
public class La extends java.lang.Object implements scala.ScalaObject{
    public long[] La();
    public La();
}

A: As the documentation of Runtime.freeMemory says, the value returned depends on when the last gc was done. So the error is likely in your way of measuring.

A: It's really hard to measure memory usage in Java.  Anything you do that touches the memory subsystem will cause results to fluctuate wildly--and even if you do nothing, you can't be sure that the JVM isn't creating objects in order to run itself.  In particular, you should use while loops not for loops in order to fill the arrays (to avoid any creation of objects in the for).  Then again, the memory allocation that creates the array may trigger a garbage collection.  Your best bet is to run the jvm with -verbose:gc to make sure no garbage collections happen between your measurements, e.g.
println("Starting")
// Measure free memory
// Create some stuff
// Measure free memory
println("Ending")

and if you see the GC come in between Starting and Ending, ignore that run.


text:
Q: Hover tooltip in Shiny using pure ggplot2 solution The goal here is to render a tooltip on hover using a pure ggplot2 solution without any plotly of javascript hacks.
Here is a naive tentative solution (that does not work)
library(tidyverse)
library(shiny)
shinyApp(
  ui = fluidPage(
    plotOutput("plotCars", hover="hover", width=700,height=300),
    verbatimTextOutput("info")),

  server = function(input, output) {
    hovered <- reactive(nearPoints(mtcars, input$hover, maxpoints = 1) %>%
                           rownames_to_column("model"))

    output$plotCars <- renderPlot({
      ggplot(mtcars, aes(x=wt, y=mpg)) +
      geom_point() +
      geom_point(color="red",data=hovered()) +
      geom_label(aes(label=model),data=hovered(),
                 hjust="inward",vjust="inward",
                 size=4,color="red",alpha=0.5)+
      xlab("Weight(1000 lbs)")+ylab("Miles/gallon")
    })

    output$info <- renderPrint({
      hovered()
    })
})

The problem here is that as soon as the plot is re-rendered including the hover information (e.g. a label), the hover event is automatically reset to NULL, thus invalidating the plot.

In practice the above solution almost works, the tooltip for the hovered point is briefly shown, but immediately the input$hover event is invalidated by the new plot and the re-rendering of the plot removed the tooltip since a that point the hover event is now NULL. In fact the tooltip blinks once and then disappears.

A: The solution is to keep the previous value of the hovered data point avoiding the invalidation. This objective can be achieved using the observeEvent() method and a reactiveVal(). The solution works like this:

*

*the hovered point information is a reactive value (reactiveVal()), initialized with a zero-row tibble with the same columns as the plotted data set.
This initial value allow a smooth visualization in a ggplot2 layer, that would not be possible initializing it to NULL.

*the value is updated in response to an hover event, the function observeEvent() by default ignores when an event become NULL (ignoreNULL = TRUE), therefore when the input$hover is invalidated to NULL the value is not updated and remain the same as before

*in the plot rendering, the hovered() value is initially a zero-row tibble (but still having the right columns to be compatible with the plot default data) thus not showing anything, later when an hover near a point is performed it will contain the point information.
library(tidyverse)
library(shiny)
shinyApp(
  ui = fluidPage(
    plotOutput("plotCars", hover="hover", width=700,height=300),
    verbatimTextOutput("info")),

  server = function(input, output) {
    hovered <- reactiveVal(mtcars %>% filter(FALSE) %>% rownames_to_column("model"))
    observeEvent(input$hover, {
                 hovered(nearPoints(mtcars, input$hover, maxpoints = 1) %>%
                           rownames_to_column("model"))
    })

    output$plotCars <- renderPlot({
      ggplot(mtcars, aes(x=wt, y=mpg)) +
      geom_point() +
      geom_point(color="red",data=hovered()) +
      geom_label(aes(label=model),data=hovered(),
                 hjust="inward",vjust="inward",
                 size=4,color="red",alpha=0.5)+
        xlab("Weight(1000 lbs)")+ylab("Miles/gallon")
    })

    output$info <- renderPrint({
      hovered()
    })
  })


text:
Q: How to include a command line parameter when making a setup.exe with Installshield I'm building an installscript MSI project with InstallShield 2014 professional.
I'm trying to create a log file of the installation.
I've set the "Create MSI Logs" property to voicewarmup, and a log file is created in a random location in %temp%.
What I need though is to create the log file with a specific name in a specific location. With a basic MSI project you could just specify a location and prompt the user at the end of an installation to chose to view it. I don't have the same option with the installscript msi project.
I did manage to copy the log file to a specific location+name when running the setup.exe file via cmd:
setup.exe /verbose "filelocation\logname.log".
Is there a way to have installshiled build the setup.exe file with the commandline parameters "built in"? when I try to add the command to "MSI command-line arguments" in the "release" tab, it sends the command only when the .exe runs the .msi, and then I get an error saying the command is invalid.
Also if there's a way to create a log file for the user to pick after installation is complete (like in the basic MSI project) - I'd love to hear.
Appreciate your help.

A: In the release definition, you have a setup.exe tab.
The first line "MSI Command Line arguments" you can hardcode the location and name of the logfile that needs to be created during every setup run.
E.g /L*v %windir%\temp\logfile.log

Hope this helps


text:
Q: NanoHTTPD 2.0.5 issue with file upload with spaces in filename I have an android app that uses NanoHTTPD to serve HTML context.
I'm using NanoHTTP 2.0.5 in my App.
There's a problem with file uploads.
Suppose I upload a file named kr d.mp4; it gets uploaded but renamed to k (starting from one character before space till last char in filename including extension is removed).
Any file upload that has space shows this behaviour.
I tried other file name :
 ORIGINAL         GOT THIS
-----------------------------
NO_SPACE.TXT      NO_SPACE.TXT  (works as expected)
ABC DEF.txt       AB
AB1234 gf.txt     AB123
A D.txt           Failed to upload ???

How do I fix this issue ?

A: I got this working with help from IRC channel #android-dev by user : memoryleak. It was an encoding related issue.
To fix it do this when uploading on :
Client side (Javascript) :
formdata.append("filedata", file, encodeURIComponent(file['name']));

Server Side (NanoHTTPD) :
URLDecoder.decode(session.getParms().get(entry.getKey()), "UTF-8");


text:
Q: Checking screenSize is not working This is my code for checking screen sizes and changing the FrameLayout size.
    FrameLayout topLayout = (FrameLayout) findViewById(R.id.topLayout);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
    double screenInches = Math.sqrt(x + y);

    if (screenInches < 5) topLayout.setLayoutParams(new LinearLayout
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,170));
    if (screenInches >= 5 && screenInches < 7) topLayout
    .setLayoutParams(new LinearLayout
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200));
    else topLayout.setLayoutParams(new LinearLayout
    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 230));

I don't know why its not working.

A: You can use DisplayMetrics .

A structure describing general information about a display, such as
  its size, density, and font scaling.

   DisplayMetrics metrics = getResources().getDisplayMetrics();

   int DeviceTotalWidth = metrics.widthPixels;
   int DeviceTotalHeight = metrics.heightPixels;
   FrameLayout topLayout = (FrameLayout) findViewById(R.id.topLayout);

   topLayout.getLayoutParams().height= (DeviceTotalHeight/4); // Use Your Logic

Now you can use your screenInches logic simply .

A: DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)mContext)getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

A: in order to change layout parameter you have to do this:
topLayout.getLayoutParams().width = 100;
topLayout.getLayoutParams().height = 100;


text:
Q: Turn laravel error output to span instead of div? The following code:
{{ Form::error($errors->first('blah')) }}

Will produce:

My error.

I want it to produce:
My error.

How do you do that?

A: There is no Form::error() in Laravel, so you might be using a Macro:
Form::macro('error', function()
{
    return '
My error.
';
});

And you just have to change that code.


text:
Q: What prevents ACM from terminating TLS directly on EC2 instances? There are a handful of questions and answers (such as here and here) on StackOverflow explaining that while you can use ACM to terminate TLS on an EC2 load balancer, you can't use ACM to terminate TLS directly on an EC2 instance, and I'm struggling to understand what the underlying reason for that is. The given reason is because you can't export private keys from ACM but... why?
As can be seen in this list, Elastic Load Balancing is integrated with ACM while EC2 is not. What "integrated" in this context means is explained here. Basically, ACM uses AWS Key Management Service(KMS) to help protect the private key. The private key is never stored as plaintext and is encrypted using a KMS key. The encrypted private key is passed to the integrating service, which is temporarily allowed to view the KMS key and use it to decrypt the private key and use that to terminate TLS.
What isn't clear to me is why a) ACM doesn't integrate directly with EC2 or b) allow private key export (by decrypting the private key with the KMS key).
So my question is:
Is certificate export or EC2 instance integration simply not an offered service yet, or are there larger underlying issues that prevent ACM from offering either direct integration with EC2 instances or export of certificates?


text:
Q: Is it permitted to use 2 content providers per application? It's out of requirement of working on existing code base. Now I need to add my existing code to it. Basically its like merging 2 huge code bases, both having one content provider each.
Is it possible to have both workin together. When I tried, it crashed. But when i run it with just one at-a-time, it runs properly.
Any suggestions?


text:
Q: Office Online Server and SharePoint 2019 Upload Issues I have an issue where when my Office Online Server is turned on I cannot upload files larger than 150MB to SharePoint 2019 on premises. The file appears to upload as expected but eventually throws the following error.

I accidently discovered that if I turn off the Office Online Server (I am not talking about stopping the service, but actually shutting down the server) then I am able to upload the file because it uses an entirely different upload approach.
I am at a total loss as to why this is happening.  Up until about a week ago we could upload large files without issue.


text:
Q: Is the `JS engine` on `IOS` or `MaxOS's` Chrome browser `V8`?Or `JavaScriptCode`? Is the JS engine on IOS or MaxOS's Chrome browser V8?Or JavaScriptCode?

A: On MacOS, Chrome uses Blink and V8. On iOS, per Apple's policies, Chrome has to use WebKit and JavaScriptCore.


text:
Q: Flowtype – how to export and import types? I've followed https://flow.org/en/docs/install/, and flow is working fine when used in single files, like this:
 // @flow

type NumberAlias = number;

const n: NumberAlias = "123";

Flow will correctly point out that:
  5: const n: NumberAlias = "123";
                            ^^^^^ string. This type is incompatible with
  5: const n: NumberAlias = "123";
              ^^^^^^^^^^^ number

The problem arises when I try to export a type from moduleA and import that type in moduleB:
(moduleA.js)
// @flow

export type NumberAlias = number;

(moduleB.js)
// @flow

import type { NumberAlias } from './moduleA';

const n: NumberAlias = 123;

Flow complains:
src/moduleB.js:3
  3: import type { NumberAlias } from './moduleA';
                                      ^^^^^^^^^^^ ./moduleA. Required module not found

Isn't this exactly how it's described in https://flow.org/en/docs/types/modules/?
Folder structure is:
src/
    moduleA.js
    moduleB.js
.flowconfig
package.json

A: This worked as you'd expect when I set it up, using the two files provided sitting in a src folder under my project's root.  moduleB.js:

If I fail to put // @flow in Module A, the compiler treats NumberAlias as any, and fails to complain.  I initially forgot to add it, and this threw me for a few minutes.
The only way I could find to produce the "moduleA not found" error was to change the file extension (or file name) for moduleA.  For example, if the file is called moduleA.ts, ModuleA.js, or simply moduleA, the import will fail to resolve as above.

Incidentally, both
import type { NumberAlias } from './moduleA';

and
import type { NumberAlias } from './moduleA.js';

resolve just fine in my local environment.  You might try the second format?

Provided these conditions are met:

*

*Both files live in the same folder

*Both have a .js (or .jsx) extension

*The filenames match the import statements exactly

*Both contain the // @flow comment

The code you provided works using Flow 0.57.3 with Node 8.7.0.  In light of the error message, I'd suggest triple checking the filenames and extensions especially.

A: As a workaround, one can put all types into file anyname.js and put it into flow-typed directory. Then all the types would be exported automaticaly, without import.


text:
Q: Unambiguous gramar for let e1 in e2 I was trying to create an let grammar my idea was somthing like this
start : let
let : "let" ID ("=" let)? in let | atom
atom : ANYTHING | "(" let ")"
ID : /[a-z]+/

The idea is to parse expressions like this let A = B in C or let A in B or both mixed let f = let x in x + 1 in f(1). I also want to support parenthesis to disambiguate like let A = (let b in b + 1) in A(1) + 1
I'm using lark, whith LALR parser, but I was struggling with the grammar, and can't define an unambiguous grammar for this
I tried

from lark import Lark, Transformer as LarkTransformer

grammar = """
    start : expr
    expr : LET ID (EQUAL exprcont)? IN exprcont | exprcont
    exprcont : ANYTHING | LPAR expr RPAR | expr
    ANYTHING.0 : /.+/
    LET : "let"
    IN : "in"
    ID : /[a-z_][a-z0-9_]*/
    EQUAL : "="
    LPAR.10 : "("
    RPAR.10 : ")"

    %import common.WS
    %ignore WS
"""

let_parser = Lark(grammar, parser="lalr")

print(let_parser.parse("let a = 1 in let b = 2 in a + b").pretty())

But I got lot's of reduce reduce errors
Traceback (most recent call last):
  File "/Users/gecko/code/lampycode/letparser.py", line 55, in <module>
    let_parser = Lark(grammar, parser="lalr")
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/lark.py", line 339, in __init__
    self.parser = self._build_parser()
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/lark.py", line 373, in _build_parser
    return self.parser_class(self.lexer_conf, parser_conf, options=self.options)
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/parser_frontends.py", line 145, in __init__
    self.parser = LALR_Parser(parser_conf, debug=debug)
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/parsers/lalr_parser.py", line 17, in __init__
    analysis.compute_lalr()
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/parsers/lalr_analysis.py", line 304, in compute_lalr
    self.compute_lalr1_states()
  File "/Users/gecko/.pyenv/versions/lampy/lib/python3.9/site-packages/lark/parsers/lalr_analysis.py", line 279, in compute_lalr1_states
    raise GrammarError('\n\n'.join(msgs))
lark.exceptions.GrammarError: Reduce/Reduce collision in Terminal('$END') between the following rules:
    - <exprcont : expr>
    - <start : expr>

Reduce/Reduce collision in Terminal('IN') between the following rules:
    - <expr : exprcont>
    - <expr : LET ID IN exprcont>

Reduce/Reduce collision in Terminal('RPAR') between the following rules:
    - <expr : exprcont>
    - <expr : LET ID IN exprcont>

Reduce/Reduce collision in Terminal('$END') between the following rules:
    - <expr : exprcont>
    - <expr : LET ID IN exprcont>

Reduce/Reduce collision in Terminal('IN') between the following rules:
    - <expr : exprcont>
    - <expr : LET ID EQUAL exprcont IN exprcont>

Reduce/Reduce collision in Terminal('RPAR') between the following rules:
    - <expr : exprcont>
    - <expr : LET ID EQUAL exprcont IN exprcont>

Reduce/Reduce collision in Terminal('$END') between the following rules:
    - <expr : exprcont>

I have no idea how to define this grammar, the idea is so simple let : "let" ID ("=" let)? "in" let | atom any ideas?

A: I think the problem is
start : expr
    expr : ... | exprcont
    exprcont : ... | expr

This loop means that your grammar is ambiguous.
Can you get rid of the loop?

A: If you want to use a terminal like ANYTHING, don't use lalr. Use earley. (and even then it will still create problems)

But this is not actually what is creating these errors. The problem is the mutual recursion in expr and exprcont. You can just remove the expr in exprcont:
exprcont : ANYTHING | LPAR expr RPAR

But this still won't work. (Unless you use parser='earley' and lexer='dynamic_complete'. But that will be very slow). You have to redesign the grammar to not include an ANYTHING terminal.


text:
Q: R function to to search and replace text in a column #I'm seeking to write code that takes a column with character values (e.g. ALA3=VAL20) and converts it to a specific single letter corresponding to that three letter code (e.g. A3=V20). I attempted using the following function, but seem to be having trouble:
    substitute_codes <- function(data, col_name) {
  # Create a dictionary of the code substitutions
  code_dict <- c("ALA" = "A", "ARG" = "R", "ASN" = "N", "ASP" = "D",
                 "CYS" = "C", "GLU" = "E", "GLN" = "Q", "GLY" = "G",
                 "HIS" = "H", "ILE" = "I", "LEU" = "L", "LYS" = "K",
                 "MET" = "M", "PHE" = "F", "PRO" = "P", "SER" = "S",
                 "THR" = "T", "TRP" = "W", "TYR" = "Y", "VAL" = "V")

  # Apply the substitutions using gsub()
  data[[col_name]] <- gsub(paste(names(code_dict), collapse = "|"),
                           paste(code_dict, collapse = ""),
                           data[[col_name]])

  return(data)
}

But I get results like the following from ALA3=VAL20 to  ARNDCEQGHILKMFPSTWYV3=ARNDCEQGHILKMFPSTWYV20

A: As Darren Tsai points out in the comments, we can just use the cdoe_dict in str_replace_all():
library(stringr)

set.seed(123)
x <- sample(names(code_dict), 10)
y <- sample(names(code_dict), 10)
my_string <- paste0(x, sample(10), "=", y, sample(10))
my_string

#>  [1] "PRO4=PHE9"  "TYR1=CYS10" "PHE3=HIS2"  "ASN7=ASN7"  "ILE5=GLY3"
#>  [6] "ARG10=ILE4" "GLU8=GLN1"  "LEU2=PRO6"  "CYS9=TRP5"  "ASP6=THR8"

str_replace_all(my_string,
                code_dict)
#>  [1] "P4=F9"  "Y1=C10" "F3=H2"  "N7=N7"  "I5=G3"  "R10=I4" "E8=Q1"  "L2=P6"
#>  [9] "C9=W5"  "D6=T8"

For more complex replacements, we could a custom function inside str_replace_all() as replacement argument. The custom function below shorten_str just uses a classical lookup with base R's match(), but we could add any kind of complexity here.
library(stringr)

# our dictionary
code_dict <- c("ALA" = "A", "ARG" = "R", "ASN" = "N", "ASP" = "D",
               "CYS" = "C", "GLU" = "E", "GLN" = "Q", "GLY" = "G",
               "HIS" = "H", "ILE" = "I", "LEU" = "L", "LYS" = "K",
               "MET" = "M", "PHE" = "F", "PRO" = "P", "SER" = "S",
               "THR" = "T", "TRP" = "W", "TYR" = "Y", "VAL" = "V")

# let's create a toy string
set.seed(123)
x <- sample(names(code_dict), 10)
y <- sample(names(code_dict), 10)

my_string <- paste0(x, sample(10), "=", y, sample(10))
my_string
#>  [1] "PRO4=PHE9"  "TYR1=CYS10" "PHE3=HIS2"  "ASN7=ASN7"  "ILE5=GLY3"
#>  [6] "ARG10=ILE4" "GLU8=GLN1"  "LEU2=PRO6"  "CYS9=TRP5"  "ASP6=THR8"

# custom function to replace string
shorten_str <- function(abr) {
  code_dict[match(abr, names(code_dict))]
}

# implementation with `str_replace_all()`
str_replace_all(my_string,
                paste(names(code_dict), collapse = "|"),
                shorten_str)
#>  [1] "P4=F9"  "Y1=C10" "F3=H2"  "N7=N7"  "I5=G3"  "R10=I4" "E8=Q1"  "L2=P6"
#>  [9] "C9=W5"  "D6=T8"

Created on 2023-02-16 by the reprex package (v2.0.1)


text:
Q: Changing synchronous xmlhhtprequest to asynchronous promise gives different result I was having trouble while converting a synchronous function to asynchronous.
the existing code is like below
$scope.getTask = function (input, id) {
                    var result = '';
                    if (condition) {
                        // Get all tasks.
                        var tasks = $scope.getAllTasks(id);
                        if (!angular.isUndefined(tasks)) {
                            var result = 'Failed';
                            for (var i = 0; i < tasks.length; i++) {
                                if (condition) {
                                    result = 'Success';
                                    break;
                                }
                            }
                        }
                    }
                    else if (condition) {
                        result = 'Failed';
                    }
                    else {
                        if (input != null || input != '') {
                            result = input.toLowerCase();
                        }
                    }
                    return result;
                }

                $scope.getAllTasks = function (id) {
                    var xhr = new XMLHttpRequest();
                    var url = "/api/workflow/" + id;
                    xhr.open("GET", url, false);
                    xhr.send();
                    return JSON.parse(xhr.responseText);
                }

But now i need to make this async , so i have tried using promises but that didnt help.
It is not resolving properly. Please find what i have tried
$scope.getStatus = function (input, id) {
                        return new Promise((resolve, reject) => {
                        var result = '';
                        if(condition){
                            getAllTasks(id).then(function(response){
                                var tasks = response.data;
                                if (!angular.isUndefined(tasks)) {
                                    var status = 'Failed';
                                    for (var i = 0; i < tasks.length; i++) {
                                    if (condition) {
                                        result = 'Success';
                                        break;
                                    }
                                }
                                }
                                resolve(result);
                                return result;
                            });

                            resolve(result);

                        }
                        else if (condition) {
                            result = 'Failed';
                        }
                        else {
                            if (input != null || input != '') {
                               result = input.toLowerCase();
                            }
                        }
                    resolve(result);
                            return result;
                        });
                    }

                    var getAllTasks = function (id) {
                            const url = "/api/workflow/" + id;
                             return $http({method: 'GET', url})
                                .then((response) => {
                                    return resolve(response)
                                });
                    }

But this is always returning [object promise].
I need to return the value as string like ' Failed' 'Success'.
Suggest what i am missing here.
I know promise will return a promise object from docs, but how to handle this.
$scope.getStatus is used in directives  to fill the columns in jquesry datatable.
Code snippet is below
 'sTitle': "<strong>" + $translate("list.StatusColumn") + "</strong>",
                                    'mData': function (data, type, val) {
                                        return $scope.getStatus(data.input, data.id);
                                    },
                                    'width': "16%",
                                    'defaultContent': ""

A: Do this:
first,Dont handle your http request here if you are handling it in your other promise:
var getAllTasks = function (id) {
                            const url = "/api/workflow/" + id;
                             return $http({method: 'GET', url});
                    }

second: stop returning anything from this promise's callback function as you are returning result that you are also setting in resolve and you can get it in success handler of then function like this:
$scope.getStatus = function (input, id) {
                        var result = '';
                        if(condition){
                            getAllTasks(id).then(function(response){
                                var tasks = response.data;
                                if (!angular.isUndefined(tasks)) {
                                    result = 'Failed';
                                    for (var i = 0; i < tasks.length; i++) {
                                    if (condition) {
                                        result = 'Success';
                                        break;
                                    }
                                }
                                }

                                return result;
                            });

                            return result;

                        }
                        else if (condition) {
                            result = 'Failed';
                        }
                        else {
                            if (input != null || input != '') {
                               result = input.toLowerCase();
                            }
                        }

                            return result;

                    }

console.log($scope.getStatus());


text:
Q: MariaDB and MySQL versions equivalence Is there any kind of equivalence between MariaDB versions and MySQL versions?
Obviously the 2 DBMS are different, but I was hoping the MariaDB team to "catch up" with MySQL when starting a new major version (like 10.2, 10.3...).
Equivalence in

*

*errors, issues, bugs, ...

*syntax,

*features and behavior

On this MariaDB page all MariaDB versions are listed. Is there a way to know for each major version which MySQL release is the closest?

A: MariaDB-10.2.2 InnoDB merged from 5.7.14
MariaDB-10.2.35 Merge new release of InnoDB 5.7.32
Lots of miscellany features have been merged at random times.
MySQL 8.0 and MariaDB 10.5 are quite different.  Still, you may not notice any differences unless you reach into rarely-used features.
The two play leapfrog.  For example.
MariaDB had CTEs and Windowing functions in 10.2, long before they were added in MySQL 8.0.
On the other hand, MySQL led the way with JSON and some functions (eg ST_distance_sphere).
Better links:
https://mariadb.com/kb/en/function-differences-between-mariadb-and-mysql/
https://mariadb.com/kb/en/mariadb-vs-mysql-features/
And there maybe more.  Note: it is in MariaDB's best interest to list the differences; MySQL prefers to mostly ignore the existence of MariaDB.
Errors, issues, bugs -- They look at each other's bug list, then add fixes as they see fit.
Syntax - Not much difference (except for CTEs, see above)
Features and behavior - MariaDB moved toward standards more aggressively than MySQL.  For example, in a subquery with an ORDER BY, the ordering became ignored in MariaDB long before in MySQL.  ONLY_FULL_GROUP_BY is another point of difference.  In both of these examples, the "new" version is "more correct", though incompatible.
The Optimizers have diverged.  I deal with performance a lot, but I would say only a few percent of queries show a noticeable difference between the products.  And the difference could be in favor of either product.
If you are just starting, don't worry about which one you pick; you have a long learning curve before you get into the esoteric things I have listed.


text:
Q: Как с помощью Keras строить нейронную сеть с несколькими выходными слоями для задач многоклассовой многозначной классификации? Например, есть картинка, на которой изображены три элемента, первый элемент может принадлежать к одному из 100 классов, другой элемент к одному из 30 классов, третий к одному из 10 классов. Сначала с помощью
model = Sequential()

model.add(Conv2D(16, 3, padding = 'same', activation = 'elu', input_shape = (32, 32, 1)))
model.add(MaxPool2D())

model.add(Conv2D(32, 3, padding = 'same', activation = 'elu'))
model.add(MaxPool2D())

model.add(Flatten())

model.add(Dense(400, activation = 'elu'))

мы строим начало сверточной нейронной сети, и теперь хотим добавить к dense-слою три других слоя, каждый из которых будет задачу классификации для первого, второго и третьего элементов картинки. Как это можно сделать?

A: Во всяком случае, это лучше делать не через последовательную модель, а через функциональную:
  input_x = Input(X_train.shape[1:], name = 'inp')

  x = Dense(94, name = 'Dense_1')(input_x)
  x = LeakyReLU(name = 'LReLU_1')(x)
  x1 = Dropout(dropout_rate, name = 'Dp_1')(x)
  x2 = Dense(67, name = 'Dense_2')(x1)
  x2 = LeakyReLU(name = 'LReLU_2')(x2)
  x3 = Dense(60, name = 'Dense_2')(x1)
  x3 = LeakyReLU(name = 'LReLU_2')(x3)
  x = concatenate(x2, x3)
  x = Dropout(dropout_rate, name = 'Dp_2')(x)
  x = Dense(1, name = 'Dense_3')(x)
  x = LeakyReLU(name = 'LReLU_3')(x)

  model = Model((input_x), x)

В середине я сделал разветвление на ветки x2 x3, потом объединил их. А можно не объединять, подавать на разные выходы. У меня таких задач пока не было, но читал, что градиент по обучению всё же делают на один выход, и возможно модель придётся разбивать с помощью layers, output, и обучать отдельно разные выходы, возможно фиксируя веса с помощью trainable. Старайтесь чётче представить свою задачу. Желаю успеха в поисках.


text:
Q: Check number not a sum of 2 ints on a list Given a list of integers, I want to check a second list and remove from the first only those which can not be made from the sum of two numbers from the second. So given a = [3,19,20] and b = [1,2,17], I'd want [3,19].
Seems like a a cinch with two nested loops - except that I've gotten stuck with break and continue commands.
Here's what I have:
def myFunction(list_a, list_b):
    for i in list_a:
        for a in list_b:
            for b in list_b:
                    if a + b == i:
                        break
                    else:
                        continue
                    break
                else:
                    continue
            list_a.remove(i)
    return list_a

I know what I need to do, just the syntax seems unnecessarily confusing. Can someone show me an easier way? TIA!

A: You can do like this,
In [13]: from itertools import combinations
In [15]: [item for item in a if item in [sum(i) for i in combinations(b,2)]]
Out[15]: [3, 19]

combinations will give all possible combinations in b and get the list of sum. And just check the value is present in a
Edit
If you don't want to use the itertools wrote a function for it. Like this,
def comb(s):
    for i, v1 in enumerate(s):
        for j in range(i+1, len(s)):
            yield [v1, s[j]]

result = [item for item in a if item in [sum(i) for i in comb(b)]]

A: Comments on code:

*

*It's very dangerous to delete elements from a list while iterating over it. Perhaps you could append items you want to keep to a new list, and return that.

*Your current algorithm is O(nm^2), where n is the size of list_a, and m is the size of list_b. This is pretty inefficient, but a good start to the problem.

*Thee's also a lot of unnecessary continue and break statements, which can lead to complicated code that is hard to debug.

*You also put everything into one function. If you split up each task into different functions, such as dedicating one function to finding pairs, and one for checking each item in list_a against list_b. This is a way of splitting problems into smaller problems, and using them to solve the bigger problem.

Overall I think your function is doing too much, and the logic could be condensed into much simpler code by breaking down the problem.
Another approach:
Since I found this task interesting, I decided to try it myself. My outlined approach is illustrated below.
1. You can first check if a list has a pair of a given sum in O(n) time using hashing:
def check_pairs(lst, sums):
    lookup = set()

    for x in lst:
        current = sums - x
        if current in lookup:
            return True
        lookup.add(x)

    return False

2. Then you could use this function to check if any any pair in list_b is equal to the sum of numbers iterated in list_a:
def remove_first_sum(list_a, list_b):
    new_list_a = []

    for x in list_a:
        check = check_pairs(list_b, x)
        if check:
            new_list_a.append(x)

    return new_list_a

Which keeps numbers in list_a that contribute to a sum of two numbers in list_b.
3. The above can also be written with a list comprehension:
def remove_first_sum(list_a, list_b):
    return [x for x in list_a if check_pairs(list_b, x)]

Both of which works as follows:
>>> remove_first_sum([3,19,20], [1,2,17])
[3, 19]
>>> remove_first_sum([3,19,20,18], [1,2,17])
[3, 19, 18]
>>> remove_first_sum([1,2,5,6],[2,3,4])
[5, 6]

Note: Overall the algorithm above is O(n) time complexity, which doesn't require anything too complicated. However, this also leads to O(n) extra auxiliary space, because a set is kept to record what items have been seen.

A: You can do it by first creating all possible sum combinations, then filtering out elements which don't belong to that combination list
Define the input lists
>>> a = [3,19,20]
>>> b = [1,2,17]

Next we will define all possible combinations of sum of two elements
>>> y = [i+j for k,j in enumerate(b) for i in b[k+1:]]

Next we will apply a function to every element of list a and check if it is present in above calculated list. map function can be use with an if/else clause. map will yield None in case of else clause is successful. To cater for this we can filter the list to remove None values
>>> list(filter(None, map(lambda x: x if x in y else None,a)))

The above operation will output:
>>> [3,19]

You can also write a one-line by combining all these lines into one, but I don't recommend this.

A: you can try something like that:
a = [3,19,20]
b=  [1,2,17,5]

n_m_s=[]
data=[n_m_s.append(i+j) for i in b for j in b  if i+j in a]

print(set(n_m_s))

print("after remove")

final_data=[]
for j,i in enumerate(a):
    if i not in n_m_s:
        final_data.append(i)

print(final_data)

output:
{19, 3}
after remove
[20]


text:
Q: Showing that (T,*) is a semigroup where T is the trace and * is defined inside Let $D$ be a $D−class$ of a semigroup $S$. The Trace of $D$ is $T = D ∪ {0}$ where $0$ is a symbol not in $D$. Define a binary operation $∗$ on $D$ by:
$a ∗ b = ab$ for $a, b ∈ D$ and $ ab ∈ R_a ∩ L_b$
$a*b = 0$ otherwise
Show that $(T, ∗)$ is a semigroup.
I am having issues showing associativity for this! Any help would be much appreciated.

A: Hint. Use the fact (due to Miller and Clifford 1956) that $ab \in R_a \cap L_b$ if and only if $R_b \cap L_a$ contains an idempotent.


text:
Q: Giving velocity to an object based on rotation I'm using Cocos-Creator, currently there is no physics implemented so I kinda want to create my own. Here I try to move an object based on its rotation:
    properties: {

       speed: 200,
},

update: function (dt) {
    this.node.x += Math.cos(this.node.rotation) * this.speed;
    this.node.y += Math.sin(this.node.rotation) * this.speed;
},

But the problem is that the object is not behaving as intended to, it's moving in random directions.
Update:
The code now is:
update: function (dt) {
        var vX = Math.cos(this.node.rotation * Math.PI / 180) * this.speed;
        var vY = Math.sin(this.node.rotation * Math.PI / 180) * this.speed;
        this.node.x += vX * dt;
        this.node.y += vY * dt;
    },

Still the same problem.


text:
Q: Accessing a inherited static member without specifying the scope
Followup to: Enabling a static member conditionally without changing the member scope

I have got a static class member which is conditionally enabled when both template variables R and C are equal.
Now I want to access it without having to specify the scope beforehand - just like with any direct static member.
One can pull variables into the derived classes scope using a using A::variable; statement. But as the variable is not available for all Foo types, this using declaration will fail when R != C.
struct EmptyBase { };
template<int R, int C> class Foo;

template<int R, int C>
class _Foo_Square
{
public:
    static Foo<R, C> ID;
};

template<int R, int C>
class Foo : public std::conditional<R == C, _Foo_Square<R, C>, EmptyBase>::type
{
public:
    static Foo SECOND;
    /* other members and functions */

    void A()
    {
        Foo a = ID; //error because of inheritance
        Foo b = Foo<R, C>::ID; //works

        Foo test = SECOND; //works everytime
    };
};

int main()
{
    Foo<3, 3> foo;
    foo.A();
}

Accessing ID directly in the member function does not work as expected.


text:
Q: Weight enumerator of the Hamming code Let $H_r$ be the usual Hamming code of length $2^r-1$. What is the weight enumerator of $H_r^\perp$? Using this find an expression for the weight enumerator of $H_r$. (we are in binary case)

A: Hints:

*

*The duals of the Hamming codes are the Simplex codes. The Simplex codes are "constant weight codes", since all nonzero codewords have the same weight. Can you find the weight enumerator of the Simplex codes from this information?

*The weight enumerators of the primal and the dual code are related by the MacWilliams identities. Use this to translate the weight enumerator of the Simplex codes into the weight enumerator of the Hamming codes.


text:
Q: PriorityQueue with lambda expression Im trying to understand how lambda functions work with heaps in Java. the function below is to create a max heap
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);

Can someone tell me what (x, y) -> y - x) does?
Im told that "The lambda function will take two Integers as input parameters, subtract them from each other, and return the arithmetic result."
so if I do
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
pq.add(9);

pq.add(5);

System.out.println(pq.peek());

Output is 9 since its a max heap but should I not get 4 as an output since (9-5=4)?

A: 9-5=4 is the priority of 9, and pq.peek() returns the value, not the priority
new PriorityQueue<>(comparator); uses (x, y) -> y - x to compare and determine which value should be next to be peeked.
So 9-5=4 is greater than 5-9=-4
So the value 9 will be the first one.

A:
I'm trying to understand how lambda functions work with heaps in Java.

Lambda Expression has nothing to do with Heap Data Structure, per se.

*

*Lambda Expression - is a language feature, acting like an anonymous function, which you can use/pass as a value;

*Heap - is a Data Structure, originally defined in Mathematics, and nowadays heavily used in the Computer Science domains.

Can someone tell me what (x, y) -> y - x) does?

That is your comparator, to wit, a lambda expression which implements a Comparator<T>, and which you pass as an argument into your priority queue constructor.
PriorityQueue<T> then makes use of that comparator, and utilizes int compare(T o1, T o2) method, each time you fetch (poll/peek) an element from it.
PriorityQueue<T> relies on a contract, that:

int compare(T o1, T o2) Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So, in your code:
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
pq.add(9);
pq.add(5);
System.out.println(pq.peek());

Two numbers are enqueued in the Heap/PQ, and when you .peek(), 9 and 5 are passed into x and y respectively. As 9-5>0 true is returned.

Output is 9 since its a max heap but should I not get 4 as an output since (9-5=4)?

9-5=4 is only relevant for the comparator, to decide whether the comparison of two elements end up in 0, positive, or negative number, as already explained above.


text:
Q: Racket list syntax seems inconsistent The syntax for list seems mysterious
'(1 2) and (list 1 2) are the same:
> (equal? '(1 2) (list 1 2))
#t

BUT these are not the same???
(equal? '('(1 2)) (list (list 1 2)))
#f

also
>  (list (list 1 2))
'((1 2))

> '( '(1 2))
'('(1 2))

A: Yep, those are different. The answer here is that quote is much more powerful than you think it is.
Specifically, quote puts you into a "data language"; in this data language, every pair of parentheses introduces a nested list, and every identifier is treated as a symbol.
So, for instance,
'(a (b c) d "e" ((g)))

is the same as
(list 'a (list 'b 'c) 'd "e" (list (list 'g)))

Note how much shorter the first one is, than the second.
When you put a quoted term inside of a quoted term, you're going to get surprises; this is because 't is actually a shorthand for (quote t).  So '('(1 2)) is short for (quote ((quote (1 2)))), which is the same as (list (list 'quote (list 1 2))).
Short version: don't put quote inside of quote, and remember that quote enters a "data language". Things get even more interesting with quasiquote!


text:
Q: TypeError: getClientById is not a function when using useEffect in one component I am having an issue I can't seem to figure out, in one component I get an error when trying to run an action function from within useEffect.
As far as I can see it is set up the same as my other components that have a similar function, and if import I use one the actions that are used in another component I get the same result. This makes me think that the issue is with how I am implementing useEffect, but I cannot see what I am doing wrong.
Error:

TypeError: getClientById is not a function
(anonymous function)
/components/clients/Client.js:10
   7 | const Client = getClientById => {
   8 |   let { id } = useParams();
   9 |   useEffect(() => {
> 10 |     getClientById(id);
  11 |   }, [getClientById]);
  12 |
  13 |   return
test
;

Code:

import React, { useEffect } from "react";
import PropTypes from "prop-types";
import { useParams } from "react-router-dom";
import { connect } from "react-redux";
import { getClientById } from "../../actions/client";

const Client = getClientById => {
  let { id } = useParams();
  useEffect(() => {
    getClientById(id);
  }, [getClientById,id]);

  return
test
;
};

Client.propTypes = {
  getClientById: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  client: state.client,
  auth: state.auth
});

export default connect(mapStateToProps, { getClientById })(Client);

Code for getClientById

import { GET_CLIENT, POST_ERROR, ADD_CLIENT } from "./types";
import axios from "axios";

// Get profile by ID
export const getClientById = clientId => async dispatch => {
  try {
    const res = await axios.get(`/api/client/${clientId}`);

    dispatch({
      type: GET_CLIENT,
      payload: res.data
    });
  } catch (err) {
    dispatch({
      type: POST_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

Thanks in advance for any assistance.
D

A: The argument to a functional component is the props object. You probably mean:
const Client = props => {
  let { id } = useParams();
  useEffect(() => {
    props.getClientById(id);
  }, [props.getClientById,id]);

  return
test
;
};

Or you can destructure the props object and get access to it directly:
const Client = ({ getClientById }) => {


text:
Q: Unexpected Redshift support for the ISNULL() function. Is this documented? As far as I know, the ISNULL() function is only compatible with T-SQL.
Yet, I am working on a Redshift cluster, using Datagrip, that accepts the ISNULL() function and returns results without error. I'm even getting the contextual helptext on it in the IDE.
I have found zero Redshift documentation and zero PostgreSQL documentation that even refers to the ISNULL() function, let alone confirms support of it. Is there documentation out there for support of ISNULL()? Is this function unofficially supported, since it works, but I can't find any documentation?
Redshift environment info:
DBMS: Redshift (ver. 8.0.2)
Driver: Redshift JDBC Driver (ver. 2.0.0.3, JDBC4.2)
Effective version: Amazon Redshift (ver. 1.0.35480)

A: I think redshift recognize ISNULL() to COALESCE() like alias.


text:
Q: XML validating with XSD failing due to 'refname' not declared despite refname not allowed for schemas I am trying to validate an XML via an XSD in c# code. However it keeps throwing an XmlSchemaValidationException, namely "The 'refname' attribute is not declared.".
The code doing the validation:
XmlReaderSettings xmlSettings = new XmlReaderSettings();
            xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
            xmlSettings.Schemas.Add(null, @"\\[Network-drive path]\KVSchemaMod.xsd");
            xmlSettings.ValidationType = ValidationType.Schema;
            xmlSettings.DtdProcessing = DtdProcessing.Parse;
            xmlSettings.ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
            xmlSettings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema;
            xmlSettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
            XmlReader reader = XmlReader.Create(@"\\[Network-drive path]\KV_Article.xml", xmlSettings);

            // Parse the file.
            while (reader.Read()) ;

The XSD (with repetitous parts removed):
<?xml version="1.0" encoding="iso-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xs:annotation>
    <xs:appinfo>
        <sql:relationship name="ProductIdentifier"
        parent="tblKVProduct"
        parent-key="record_reference"
        child="tblKVProductIdentifier"
        child-key="record_reference" />
... (More SQL-mappings)
<xs:element name="ONIXMessage" sql:is-constant="1">
    <xs:complexType>
        <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="unbounded" name="Product" sql:relation="tblKVProduct">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="1" maxOccurs="1" name="RecordReference" sql:field="record_reference" >
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:minLength value="0"/>
                                    <xs:maxLength value="32"/>
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:element>
...(More elements under Product)

The XML to be validated (ONIX-standard):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ONIXMessage SYSTEM "http://www.editeur.org/onix/2.1/reference/onix-  international.dtd">
<ONIXMessage>
<Product>
    <RecordReference>0786606274</RecordReference>
    <NotificationType>03</NotificationType>
    <ProductIdentifier>
        <ProductIDType>01</ProductIDType>
        <IDTypeName>Kustantajan tuotenumero</IDTypeName>
        <IDValue>95535</IDValue></ProductIdentifier>
    <ProductIdentifier>
        <ProductIDType>02</ProductIDType>
        <IDValue>0786606274</IDValue></ProductIdentifier>
    <ProductIdentifier>
        <ProductIDType>03</ProductIDType>
        <IDValue>9780786606276</IDValue>
    </ProductIdentifier>
...(And more Product-fields)

The XML also has a Header tag as the first child of ONIXMessage (followed by all Product tags that as also childrens of ONIXMessage), but since none of the fields there are referenced in the schema I don't see how they could cause this particular error.
As I googled the error I read up on the XmlSchemaElement.RefName property (MSDN Definition) it even explicitly says that "The value cannot be set if the containing element is the schema element."
Since that is the case for the XSD I don't understand why it throws an error about it not being declared.
I've been trying to find out if this could be related to the lack of namespace, but in my mind that shouldn't be a problem since there is none in neither the XML nor the XSD. Or does one need to force a namespace onto the root-element in order to validate the XML?
The validating code does work with another set of XML/XSD (very different build-up on those though), could that just be a fluke though and the error actually in the way I validate?
Just for completion's sake, the Header tag in the XML:
<Header>
    <FromCompany></FromCompany>
    <FromPerson></FromPerson>
    <FromEmail></FromEmail>
    <AddresseeIdentifier>
        <AddresseeIDType></AddresseeIDType>
        <IDTypeName></IDTypeName>
        <IDValue></IDValue>
    </AddresseeIdentifier>
    <ToCompany></ToCompany>
    <ToPerson></ToPerson>
    <MessageNumber></MessageNumber>
    <SentDate></SentDate>
    <MessageNote></MessageNote>
</Header>

A: It's not possible to reproduce your problem, given that you haven't provided a complete example.  If you want answers based on anything other than speculation, you need to cut down your schema and your data to the smallest example that illustrates the problem, so question answerers can reproduce the problem and study it in more detail.  It will often happen, of course, that your problem dissolves in the process because you come to see what's going wrong in the process of finding a small example of the problem.  But that's just a risk you have to take.
That said, however, I'll go ahead and speculate.  The RefName property on the XMLSchemaElement object is almost certainly a red herring.  The message makes it sound much more as if the XML you are attempting to validate has an attribute named refname somewhere (in the bit you elided), and your XSD schema has no definition for it.  Certainly the XSD fragment you provide has no definition for it.
The vocabulary defined at http://www.editeur.org/onix/2.1/reference/onix-international.dtd (which you point to in your XML), however, does define refname as an attribute on many elements (probably all of them, though I haven't checked each one individually).  So it's not at all implausible that an ONIXMessage element might contain a descendant with a refname attribute.
Actually, it's not just not implausible; it's certain.
The DTD pointed to by your XML supplies a default value for the refname attribute on all elements (at least, all the ones I've seen), for which your XSD schema declaration appears not to be prepared.  That is, the first start-tag of your document seen by the schema validator is not <ONIXMessage> but <ONIXMessage refname="ONIXMessage" shortname="ONIXmessage">.
If you're not using the XSD available from www.editeur.org, the simplest way forward is probably to reconsider that decision and use the schema from editeur.org instead of rolling your own.  It includes declarations for the refname and shortname attributes.  If you are using that schema, or rather trying to use it, something has gone badly wrong and your validator is not finding or reading it.  In that case, your best way forward is to figure out why your system is not finding the correct schema documents.


text:
Q: A Nonrectifiable Curve Do Carmo's book Page 11.
Let $\alpha : [0,1] \to \mathbb{R}^2$ be given as $$\alpha(t)=
\begin{cases}
(t,t \sin (\pi/t)) & \text{ for } t \ne 0\\
(0,0) & \text{ for } t=0 \,.
\end{cases}$$ Show that the arc length of the portion of the curve corresponding to $\dfrac{1}{n+1} \leq t \leq \dfrac{1}{n}$ is at least $2/(n+1/2)$. Use this to show that the length of the curve in the interval $1/N \leq t \leq 1$ is greater than $2 \sum_{n=1}^N 1/ (n+1)$.
For the first part, I considered the distance between $\bigl(\alpha(1/n), \alpha(2/(2n+1))\bigr)$ and $\bigl(\alpha(2/(2n+1)), \alpha(1/(n+1))\bigr)$ and proved that it should be at least $2/(n+1/2)$.
In the second part, we can see that
\begin{align}
[1/N, 1] & = [1/N, 1/(N-1)]\cup [1/(N-1), 1/(N-2)]\cup \dots \cup [1/2,1] \,.
\end{align}
Therefore,
\begin{align}
|\alpha(1)-\alpha(1/2)|+ \dots + |\alpha(1/(N-1))-\alpha(1/N)| & \geq \sum_{n=1}^{N-1}\dfrac{2}{n+1/2} \,,
\end{align} and that won't give the desired solution. I don't know where I have made a mistake.

A: Everything you have is correct. All that's remaining is to show that your lower bound is at least as large as the desired lower bound. Equivalently, we need to show that
$$\sum_1^{N-1} \frac{1}{n+0.5} - \sum_1^N \frac{1}{n+1} > 0 \,.$$
We have the following.
\begin{align*}
\sum_1^{N-1} \frac{1}{n+0.5} - \sum_1^N \frac{1}{n+1}
&= \sum_1^{N-1} \frac{1}{n+0.5} - \sum_1^{N-1} \frac{1}{n+1} - \frac{1}{N+1} \\
&= \sum_1^{N-1} \biggl(\frac{1}{n+0.5} - \frac{1}{n+1}\biggr) - \frac{1}{N+1} \\
&= \sum_1^{N-1} \biggl(\frac{n+1}{(n+0.5)(n+1)} - \frac{n+0.5}{(n+0.5)(n+1)}\biggr) - \frac{1}{N+1} \\
&= \sum_1^{N-1} \frac{n+1-n-0.5}{(n+0.5)(n+1)} - \frac{1}{N+1} \\
&= \sum_1^{N-1} \frac{0.5}{(n+0.5)(n+1)} - \frac{1}{N+1} \\
&= \sum_1^{N-1} \frac{1}{(2n+1)(n+1)} - \frac{1}{N+1}
\end{align*}
The final term is approximately equal to $0.07$ for $N=4$ and is an increasing function in $N$, so the claim holds for all $N \geq 4$.
This doesn't necessarily show the statement is false for $N \leq 3$ but doesn't prove it true either.


text:
Q: jQuery, break or reset after click event I may be going about this wrong, but I am trying to have jQuery tell an HTML element to do xyz on click.  I am able to get xyz to work, but I would like the functions to restart after a new click has been initiated.
In this example, I am have a main image, which has thumbnails.  When a thumb nail is clicked, the featured image changes and has some effect.  The problem is with my current code, when you click multiple thumbnails, it adds the click event to a que to be processed in order.
$("div.thumb").click(function() {
    var primary_image = $(this).attr("rel");
    $('div.main-image').effect( "blind", {direction: "left" }, 500, function() {
        $('div.main-image').html('');
    });
    $('div.main-image').show( "blind", {direction: "left" }, 200 );
});

What is the ideal way to accomplish this?

JS Fiddle

A: According to documentation, the queue parameter is set to true by default. Setting it to false should solve the issue
Note that I am passing the animation options as an object
$("div.thumb").click(function() {
    var primary_image = $(this).attr("rel");

    $('div.main-image').effect({
        effect : "blind",
        direction: "left",
        duration: 500,
        complete: function() {
            $('div.main-image').html('');
        },
        queue: false
    });
    $('div.main-image').show( "blind", {direction: "left" }, 200 );
});

A: Check this:

$(document).ready(function() {
  $(".thumb").click(function() {
    var primary_image = $(this).attr('rel');
    $('.main-image').effect({
      effect: "blind",
      direction: "left",
      duration: 500,
      queue: false,
      complete: function() {
        $('.main-image').html('').show("blind", {
          direction: "left"
        }, 500);
      }
    });
  });
});
.main-image {
  text-align: center;
}

.thumb-wrapper {
  display: flex;
  margin-top: 13px;
}

.thumb {
  flex-grow: 1;
  text-align: center;
}


text:
Q: adding variables in the case of symmetric TSP I have to implement a symmetrical TSP. When I go to add the variables:
x = m.addVars (Costs.Keys (), vtype = GRB.BINARY, obj = Costs, name = 'x')
It gives me the error:
'list' object has no attribute 'Key '.
I have the data saved in a list, is there a way to add the variable or do I necessarily have to save the data in a dictionary?

A: Seems like Costs is a list. Typically, use a dictionary of distances, indexed by the edge pairs i,j. See the Gurobi tsp.py example code for an illustration.


text:
Q: ¿Como renderizar el contenido de una variable en la vista? Tengo una variable como la siguiente en un controlador de angular:
$scope.dato = "
MI TITULO
";

Quiero que se muestre en el html, pero renderizado... algo así como lo siguiente:
MI TITULO
En la vista pongo así: {{dato}}, pero lo que muestra es el valor con los tag html

A: Lo que sucede es que le estás pasando todo lo que va renderizar como cadena de texto, por eso ignora la estructura semántica de HTML.
Lo que debes hacer es, en tu HTML utilizar esa variable dentro de la etiqueta h1
Ejemplo:
HTML

{{dato}}

Mientras que en tu JS:
$scope.dato = "Mi título";

¡Saludos!

A: Al final logre solucionar el problema.
La pregunta la han hecho en varias partes pero en ingles.
Di con la solución con respuestas a esas preguntas y principalmente con esta pregunta en la segunda respuesta.
Utilice ng-bind-html en la vista, $sce.trustAsHtml en el controlador, incluí la librería angular-sanitize.js y en el modulo agregue ngSanitize.

A: Marck Vit. No uses el ng-bind-html. Es una muy mala práctica, además expones tu app para ataques al poder inyectar código. Está disponible, pero para usar en casos muy obligatorios. Una etiqueta H1 es una tontería.


text:
Q: Error to Execute a Mutation with GraphQL in Google App Script I managed to use similar code below for query GraphQL using Google App Script.
However, it's not working when I changed to use on mutation (code below).
Error code is 400 with text: {"errors":[{"message":"GraphQL operations must contain a non-empty query or a persistedQuery extension.","extensions":{"code":"INTERNAL_SERVER_ERROR"}}]}
I just started to learn Google App Script & Javascript, not sure how to resolve this issue after search few hours on the net. Some help would be appreciate. Thanks in advance.

function get_auth_headers(){
  email = "test@mail.com"
  password ="test"

  var query = "mutation={ \
                userLogin(input:{email:\"" + email + "\",password:\"" + password + "\"}){ \
                  token \
                } \
              }";

  Logger.log(query)
  var url1 = "https://server.matters.news/graphql?";
  url = encodeURI(url1 + query)
  Logger.log(url)
  var response = UrlFetchApp.fetch(url, {muteHttpExceptions: true });
  Logger.log("code: " + response.getResponseCode());
  Logger.log("text: " + response.getContentText());
  var response = UrlFetchApp.fetch(url,{method: 'GET', headers: {'Content-Type': 'application/json'}});
  var lists = JSON.parse((response.getContentText()));
  Logger.log(lists);
}

A: Managed to get answer from https://speckle.guide/dev/js-app-script.html
Refers code below for your reference if you have same issue.

function get_auth_headers() {
  //email = "test@gmail.com"
  //password ="test"

  let url = "https://server.matters.news/graphql";
  let graphql = JSON.stringify({
    query: `mutation($input: UserLoginInput!) {userLogin(input: $input) {token}}`,
    variables: {
      input: {
        email: email,
        password: password,
      },
    },
  });

  let params = {
    method: "POST",
    payload: graphql,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer YOUR_PERSONAL_TOKEN",
    },
  };

  var response = UrlFetchApp.fetch(url, params);
  var lists = JSON.parse((response.getContentText()));
  //Logger.log(lists['data']['userLogin']['token']);
  return lists['data']['userLogin']['token'];
}


text:
Q: Length of longest stretch of NAs in a column of data-frame object I want to write a code that finds the length of longest continuous stretch of NA values in a column of a data-frame object.
>> df
      [,1] [,2]
[1,]    1    1
[2,]   NA    1
[3,]    2    4
[4,]   NA    NA
[6,]    1    NA
[7,]   NA    8
[8,]   NA    NA
[9,]   NA    6
# e.g.
>> longestNAstrech(df[,1])
>> 3
>> longestNAstrech(df[,2])
>> 2
# What should be the length of longestNAstrech()?

A: Using base R we could create a function
longestNAstrech <- function(x) {
  with(rle(is.na(x)), max(lengths[values]))
}

longestNAstrech(df[, 1])
#[1] 3

longestNAstrech(df[, 2])
#[1] 2


text:
Q: Django dropdown filter in querylist how can I list the query list with a dropdown filter? with button or dynamicly, thank u!
views;
def kibana(request):
    kibana_list = kibanalar.objects.all()
    paginator = Paginator(kibana_list, 1000000000000000)
    page = request.GET.get('page')
    try:
        kmembers = paginator.page(page)
    except PageNotAnInteger:
        kmembers = paginator.page(1)
    except EmptyPage:
        kmembers = paginator.page(paginator.num_pages)
    return render(request, 'kibanalar.html', {'kmembers': kmembers})

models.py;
class kibanalar(models.Model):
    datacenter = models.TextField(max_length=100, null=True)
    dashboardtipi = models.TextField(max_length=100, null=True)
    isim = models.TextField(max_length=100, null=True)
    link = models.TextField(max_length=100, null=True)
    kullaniciadi = models.TextField(max_length=100, null=True)
    sifre = models.TextField(max_length=100, null=True)

A: I'm not sure that I fully understand your question, but it looks like you're trying to display the results of the query kibana_list = kibanalar.objects.all() in a dropdown list?
I'm also not sure why you're using pagination if you intend to have 1000000000000000 items on each page... I think their might be a typo or misunderstanding here...
There are several ways you could accomplish a drop-down, depending on your objective.
You could create a forms.py and use a forms.ChoiceField
Example forms.py:
from django import forms
from path\to\models.py import kibanalar

class MyForm(forms.Form):
My_Dropdown = forms.Choicefield(choices=createChoicesTuple(), required=False)

def createChoicesTuple():
    value = list(kibanalar.objects.values_list('field_you_want', flat=True))
    display_name = list(kibanalar.objects.values_list('another_field_you_want', flat=True))
    data = tuple(zip(value,display_name))
    return data

Another option would be to return the results you want via JsonResponse and insert the response into your HTML via Javascript.


text:
Q: Homology between a loop and a constant loop Two paths $f:I\to X$ and $g:I\to X$ are path homotopic. Does it follow that the loop $f*\bar{g}$ and the constant loop are path homotopic?

A: I assume that $\overline{g}$ is the path defined by $\overline{g}(t)=g(1-t)$ and $*$ is a classical path composition. In that case yes. It follows from the fact the fundamental group $\pi_1(X)$ is well, a group, with following properties:
$$[f][g] = [f*g]$$
$$[f]^{-1} = [\overline{f}]$$
where $[.]$ denotes homotopy class. Now for a constant path $c$ you have
$$[c]=1=[f][f]^{-1}=[f][g]^{-1}=[f][\overline{g}]=[f*\overline{g}]$$

Right, the proof above is for loops only. But the similiar proof can be given in general case.
First of all if $f$ and $g$ are homotopic via $H$ then $\overline{f}$ and $\overline{g}$ are homotopic via $H'(x, t)=H(x, 1-t)$. Now since the homotopy behaves well on composition of paths then
$$[f*\overline{g}]=[f*\overline{f}]=[c]$$
So all you need to know is that if $f_1\sim f_2$ and $g_1\sim g_2$ then $[f_1*g_1]=[f_2*g_2]$ (assuming compatible ends) and $[f*\overline{f}]=[c]$ where $c$ is constant.


text:
Q: guard-minitest does not find tests to execute when class under test changes I created a Gem project and added minitest and guard to the dependencies :
  spec.add_development_dependency "minitest", "~> 5.0.7"
  spec.add_development_dependency 'guard-minitest'

I'm using minitest-spec so all code under test resides in the lib directory and all tests in spec.
I created a Guardfile with the corresponding setup :
guard :minitest do
  # with Minitest::Spec
  watch(%r{^spec/(.*)_spec\.rb})
  watch(%r{^lib/(.+)\.rb})         { |m| "spec/#{m[1]}_spec.rb" }
  watch(%r{^spec/spec_helper\.rb}) { 'spec' }
end

Each time I modify a spec (say spec/shell/remote_shell_spec.rb) the test executes properly.
# Running:

.......

Fabulous run in 0.064205s, 109.0261 runs/s, 529.5554 assertions/s.

7 runs, 34 assertions, 0 failures, 0 errors, 0 skips

The issue is that when I modify the code under test (say lib/shell/remote_shell.rb) guard detects the change but no test is executed :
# Running:

Finished in 0.000824s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

A: Looking at your linked source code, I see that your code is placed in lib/electric_sheeps/shell/remote_shell.rb and not in lib/shell/remote_shell.rb as indicated, thus your spec must be placed in spec/electric_sheeps/shell/remote_shell_spec.rb so the mapping works.
You could also rewrite the watcher so it ignores the module folder
guard :minitest do
  # with Minitest::Spec
  watch(%r{^spec/(.*)_spec\.rb})
  watch(%r{^lib/electric_sheeps/(.+)\.rb})         { |m| "spec/#{m[1]}_spec.rb" }
  watch(%r{^spec/spec_helper\.rb}) { 'spec' }
end

but then the mapping for lib/electric_sheeps.rb would not work.