text:
Q: How to query Array in MongoDB? i am new to MongoDB and I have documents as below
{ "_id" : ObjectId("604b7d62b19a72a2b89028e6"), "name" : "ram", "tags" : [ "mobile", "iphone", "india" ] }
{"_id" : ObjectId("604b7d83b19a72a2b89028e7"), "name" : "shyam", "tags" : [ "mobile", "iphone", "india" ] }
{ "_id" : ObjectId("604b7d9bb19a72a2b89028e8"), "name" : "ravi", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "windows", "usa" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "tech", "apple", "microsoft" ] }

How to write query so that if i query for following tags ["mobile", "android", "12", "pro"] i would get following result
{ "_id" : ObjectId("604b7d9bb19a72a2b89028e8"), "name" : "ravi", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7d62b19a72a2b89028e6"), "name" : "ram", "tags" : [ "mobile", "iphone", "india" ] }
{ "_id" : ObjectId("604b7d83b19a72a2b89028e7"), "name" : "shyam", "tags" : [ "mobile", "iphone", "india" ] }

A: Demo - https://mongoplayground.net/p/EMW8xgV1yrU
Use $in

The $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype:

db.collection.find({
  tags: { $in: [ "mobile", "android", "12", "pro" ] }
})


text:
Q: How can I set focus on text instead of button in SWT MessageDialog or MessageBox? I am currently developing a program for blind people. In my program, I have several dialogs which are implemented using SWT MessageDialog or MessageBox.
This works just fine for sighted people or blind people who use screen reading software. But blind people who use refreshable braille display (which is text only and has just one line of 40 characters) have problem reading text message in the dialog because the focus of the dialog is on the button, so the refreshable braille display shows the text of the button. The blind people have to scroll up to find the text message.
Sometimes the scrolling is so hard that they have to complain about that. It would be nicer if the focus is on the text message, and then they can scroll down during reading the text, and at then end is the button text.
How can I use SWT MessageDialog or MessageBox class to manage the focus to be at the text message?
I don't want to create my own MessageDialog class because I use several options of the SWT libraries already.

A: Except for the 'Message' part in their name, MessageBox and MessageDialog are fundamentally different.
MessageBox is part of SWT and uses the component of the native platform to show the dialog and thus its behavior cannot be changed by application code.
The MessageDialog is provided by JFace and can be customized. If you really need to change the default focus behavior, you should use MessageDialog only.
To give focus to the label showing the message, you may override create() like this:
class MyMessageDialog extends MessageDialog {
  @Override
  public void create() {
    super.create();
    if( usingBraille ) {
      messageLabel.forceFocus();
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert Entry> to Entry I am trying to store the header name and it's first value as an Entry into a list. I am not sure how to achieve this.
HttpHeaders headerNames = request.getHeaders();
List<Entry<String, String>> reqHeaders = new ArrayList<>();
for (Entry<String, List<String>> entry : headerNames.entrySet()) {
    reqHeaders.add(entry.getKey(), entry.getValue().get(0));   //This line is incorrect
}

A: Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object).
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
     reqHeaders.add(Map.entry(entry.getKey(), entry.getValue().get(0)));
}

For before Java 9, you can use AbstractMap.SimpleImmutableEntry or AbstractMap.SimpleEntry
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
    reqHeaders.add(new SimpleImmutableEntry<>(entry.getKey(), entry.getValue().get(0))); // immutable
    reqHeaders.add(new SimpleEntry<>(entry.getKey(), entry.getValue().get(0))); // mutable version
}

A: I tried something like this, but @azro answer is simpler.
        HttpHeaders headerNames = request.getHeaders();
        Map<String, String> headersMap = new HashMap<>();
        List<Entry<String, String>> requestHeaders = new ArrayList<>();
        for (Entry<String, List<String>> entry : headerNames.entrySet()) {
            headersMap.put(entry.getKey(), entry.getValue().get(0));
        }
        requestHeaders.addAll(headersMap.entrySet());


text:
Q: Is there a way to track disk space freed by a process? I'm familiar with various methods of tracking disk I/O, both as a rate (e.g. bytes/second) and cumulatively (e.g. bytes) for read and write operations, however I don't know of (and cannot find) any means of tracking the amount of disk space freed by a process.  I suspect this may have something to do with the complexities of defining when/how disk space is "freed".
For instance, rm file doesn't overwrite the contents of the file with some form of "nothing", but instead clears pointers and the like.  In other words, it basically deallocates the disk space associated with file.  But there are many other ways that disk space can be freed up.  For a pre-existing non-empty file, doing echo '' >file clears its contents.  Hard links and files that're opened by multiple processes potentially further complicate tracking disk usage since the definition of when/how the space is freed has some degree of ambiguity.

A: "Disk space freed by a process" is not a very useful concept because it's very fuzzy. If process A removes a file which is still open in process B, do you credit A for freeing the space when it removes the file (that's when the system commits to freeing the disk space), or B when it closes the file (that's when the space is actually freed)? If a file has two hard links and two processes each remove one at about the same time, is it really meaningful to credit the second one for the freed space and not at all the first one? If a process overwrites a segment of a file, does that count as freeing the overwritten data? (Does your answer change if the filesystem performs deduplication?) etc.
You could pick a definition and instrument the kernel code to keep track of it, but it would be a somewhat arbitrary choice and would have limited practical usefulness, which is why it isn't a commonly available feature. Every feature has a cost: programmer time to implement it, programmer time to maintain it later, risk of bugs that it introduces, memory and CPU consumption…
You can probably implement this (again, picking one particular definition) for common scenarios using existing debugging features such as Systemtap on Linux.


text:
Q: the login keyring did not get unlocked when you logged into your computer - Without Auto Login i know this is a repeated question but in may case Auto Login is not turned on.
instead i have enabled Fingerprint Login and enabled Fingerprint Authentication module using pam-auth-update.
so i use Fingerprint authentication for Login/Sudo.
is there any way i can stop this message from appearing repeatedly when i log in with Fingerprint Authentication.
no issue with Finger Print Auth setup in Fedora Workstation, i switched to Fedora from 18.04 as i was very annoyed by this issue earlier. It would frequently throw this message at me whenever i open a browser/App/login and had to enter the password manually.
pls suggest a fix for this issue if any as i Have installed Ubuntu 22.04 after a long time.
Thanks
Error Snap


text:
Q: How to perfectly scale the whole webpage so that it is compatible with all the browsers? I have a website which needs to be zoomed permanently with approx. 125%.
I tried:
body{
  zoom: 125%;
}

Also tried:
body{
  zoom: 125%;
  -moz-transform: scale(1.25);
  -moz-transform-origin: left top;
}

to be compatible with Mozilla Firefox.
It zooms. It was OK! But the webpage is shifted towards right i.e. its not zooming perfectly. Please help how can i fix this?

A: for body use
body{
-webkit-transition: opacity 1s ease;
-webkit-transform: scale(1.25);
-moz-transform: scale(1.25);
transform: scale(1.25);
zoom: 125%;
}

and for making center all content use any container like this (use max-width according to your need)
.container {
max-width: 1160px;
margin: 0 auto;
}


text:
Q: Use a Username in a Path to Route a Component (React-router-dom) I am having a hard time setting up my react-router so that when the path matches the user's username, the userProfile component will be routed and show individually. For example, when the URL is http://localhost:3000/myusername, the userProfile component will only show. I'm kind of confused on how it will work if someone just pastes the entire link instead of being directed to someone's page through the UI.

<Switch>
    <Route path="/" component={userProfile} />
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/test3" component={test3} />
</Switch>

Any help would be appreciated!

A: You can use this method and access to username in test3 component and handle getting data and showing this page
<Switch>
    <Route path="/" component={userProfile} />
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/:username" component={test3} />
</Switch>

A: I found that if you just use /:id in the path, then the path extension will pass automatically down to the userProfile component when you use the const {id} = useParams() function in the userProfile component. Then I passed the _id down as a prop from the userProfile component to the Info component so that it can be used to automatically fetch data in a useEffect() and redux dispatch() function. Oh and also, the <Route path="/:id" component={userProfile} /> needs to be an exact path and must go to the bottom of the Route Switch list so that it doesn't get picked first.

<Switch>
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/test3" component={test3} />
    <Route exact path="/:id" component={userProfile} />
</Switch>

const Profile = () => {
  const { id } = useParams();

  return (

       <Info _id={id} />

  );
};

export default Profile;

const Info = (props) => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getProfileInfo(props._id));
  }, []);

  return (

  );
};

export default Info;


text:
Q: Download and install latest deb package from github via terminal I would like to download and install the latest .deb-package from github (https://github.com/elbersb/otr-verwaltung/downloads to be exact).
How can I download the latest package (e.g. *otrverwaltung_0.9.1_all.deb*) automatically with a script from github?
What I have tried so far:
wget -O- -q --no-check-certificate https://github.com/elbersb/otr-verwaltung/downloads | grep -o -l -e 'otrverwaltung_[0-9.]*_all.deb'
#The filename should be saved in a variable OTRPACKAGE
sudo dpkg -i OTRPACKAGE

A: # Find the URL of the .deb file
url=$(wget -O- -q --no-check-certificate https://github.com/elbersb/otr-verwaltung/downloads |
       sed -ne 's/^.*"\([^"]*otrverwaltung_[^"]*_all\.deb\)".*/\1/p')
case $url in
  http://*|https://*) :;;
  /*) url=https://github.com$url;;
  *) url=https://github.com/elbersb/otr-verwaltung/$url;;
esac
# Create a temporary directory
dir=$(mktemp -dt)
cd "$dir"
# Download the .deb file
wget "$url"
# Install the package
sudo dpkg -i "${url##*/}"
# Clean up
rm "${url##*/}"
cd /
rmdir "$dir"

A: deb-get can do this for many popular applications and if yours is not yet in the repository you could add it yourself.


text:
Q: Drawing a dynamic button based on the width of a String So, I have been modding Minecraft for a while, and I saw how it generates its buttons. It takes a very wide image of a button, takes part of the left, takes part of the right side, and puts the two back together to form a smaller image.
I'm sorry, but I can't explain this well in words, so let me just show you with bad Paint.Net skills:

However, I cannot get it to work, as it turns out like this:

Here is part of my code:
public class ComponentToolbarButton extends JComponent implements MouseListener {

    private static final int HEIGHT = 40;

    // ... other methods here

    private BufferedImage getImageBasedOnWidth(Graphics g) {
        BufferedImage finalImage = null;
        BufferedImage rawImage = null;

         // Try/catch block to initialize rawImage

         // Setting font and things here

        int compWidth = determineComponentWidth(g); // Returns the (should-be) width of the component

        if (compWidth != getWidth()) {
            setPreferredSize(new Dimension(compWidth, HEIGHT)); // Just making sure :)
        }

        finalImage = new BufferedImage(compWidth, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics finalImageGraphics = finalImage.getGraphics();

        // Draw left side:
        finalImageGraphics.drawImage(rawImage, 0, 0, 0, compWidth / 2, 0, 0, compWidth, HEIGHT, null);

        // Draw right side:
        finalImageGraphics.drawImage(rawImage, compWidth / 2, 0, compWidth, HEIGHT, rawImage.getWidth() / 2 - compWidth,
            0, rawImage.getWidth(), rawImage.getHeight(), null);

        return finalImage;
    }
}

Thanks in advance! (I tried to shorten the code as much as I could BTW)

A: Okay, after some thinking, I came up with this little hack to demonstrate how I believe it should work :P
public class TestMenu extends JComponent {

    protected static final int MAX_HEIGHT = 40;
    protected static final int LEFT_MARGIN = 5;
    protected static final int RIGHT_MARGIN = 5;

    protected static final ImageIcon BACKGROUND = new ImageIcon(TestMenu.class.getResource("/Menu.png"));

    private String text;

    public TestMenu() {

        setOpaque(false);
        text  = "This is some text";
        setFont(UIManager.getFont("Label.font"));

    }

    @Override
    public Dimension getPreferredSize() {

        FontMetrics fm = getFontMetrics(getFont());
        int width = fm.stringWidth(text) + LEFT_MARGIN + RIGHT_MARGIN;

        Dimension size = new Dimension(width, MAX_HEIGHT);

        return size;

    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        int width = getWidth() - 1;
        int height = getHeight() - 1;

        BufferedImage imgLeft = new BufferedImage(LEFT_MARGIN, MAX_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        BufferedImage imgRight = new BufferedImage(RIGHT_MARGIN, MAX_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        BufferedImage imgBody = new BufferedImage(width - LEFT_MARGIN - RIGHT_MARGIN, MAX_HEIGHT, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = imgLeft.createGraphics();
        g2d.drawImage(BACKGROUND.getImage(), 0, 0, this);
        g2d.dispose();

        g2d = imgRight.createGraphics();
        g2d.drawImage(BACKGROUND.getImage(), RIGHT_MARGIN - BACKGROUND.getIconWidth(), 0, this);
        g2d.dispose();

        g2d = imgBody.createGraphics();
        g2d.drawImage(BACKGROUND.getImage(), -LEFT_MARGIN, 0, this);
        g2d.dispose();

        g2d = (Graphics2D) g;

        g2d.drawImage(imgLeft, 0, 0, this);
        g2d.drawImage(imgBody, LEFT_MARGIN, 0, this);
        g2d.drawImage(imgRight, width - RIGHT_MARGIN, 0, this);

        FontMetrics fm = g2d.getFontMetrics();

        int x = (width - fm.stringWidth(text)) / 2;
        int y = ((height - fm.getHeight()) / 2) + fm.getAscent();

        g2d.setColor(Color.WHITE);
        g2d.drawString(text, x, y);

    }

}

First, one should never try and build all the image segments in the paint method, it will slow down the paint routine and consume to much memory, but for this example, I just wanted to demonstrate the idea.  Use a backing buffer instead (which I think is what you were trying to do anyway).
This will produce this:

A: Maybe the coordinates are mixed up in the calls to drawImage:
boolean Graphics.drawImage(Image img,
       int dstx1, int dsty1, int dstx2, int dsty2,
       int srcx1, int srcy1, int srcx2, int srcy2,
       ImageObserver observer);

The width and height dimensions are calculated according to: (dstx2-dstx1), (dsty2-dsty1).
Try this for the left side:
finalImageGraphics.drawImage(rawImage,
        0, 0, compWidth / 2, HEIGHT,
        0, 0, rawImage.getWidth() / 2, rawImage.getHeight(),
        null);

Drawing an Image is a good tutorial on the subject.


text:
Q: Load data from database on select box onchange event Can anyone guide me how to load data from a database when I change the value in the select box? I tried the following code, but when I try to get the "value" and log it says "undefined."
My Component.js
actions:{
 filterStudent(){
   let filterInputValue = this.get('value');
   console.log(filterInputValue);
   let filterAction = this.get('filter');
   console.log(filterAction);
   }
}

My Controller
   actions:
   {
     filterStudentResults(param)
     {
       if (param !== '')
       {
        return this.get('store').query('Students', { studentName: param });
       }
       else
       {
         return this.get('store').findAll('Students');
       }
     }
  }

My Component.hbs
<select name="newType" onchange={{action "filterStudent" value="target.value"}} class="form-control">
      <option value="" disabled selected>Please Select</option>
      {{#each model.Students as |newStudents|}}
         <option value="{{newStudents.studentId}}">{{newStudents.studentName}}</option>
      {{/each}}
</select>

Am calling the component in the Specific template as
{{bind-dropdown model=model Filter=filterStudentResults}}

Am a newbie to EmberJS and appreciate any help. Thanks in Advance :)

A: In My-Component.js, does not having value as property, You mean to get it from onchange={{action "filterStudent" value="target.value"}} then your action should receive param,
actions:{
 filterStudent(selectedValue){
   console.log(selectedValue);
   }
}

One more problem, I found upon sending action filterStudentResults to component.
The below one is wrong.
    {{bind-dropdown model=model Filter=filterStudentResults}}
As you have defined filterStudentResults in controller, you can create closure action and send it to component, so it should be like,
{{bind-dropdown model=model filter=(action 'filterStudentResults')}}

And it should be invoked with selectedValue from component action,
actions:{
     filterStudent(selectedValue){
       this.sendAction('filter',selectedValue);//this will call controller method with param
       }
    }

A: First you need to check the model is ready and you can do so inside route's afterModel(model) hook.
<select name="newType" onchange={{action "filterStudent" value="target.value"}} class="form-control">

Should be re-write to,
<select name="newType" onchange={{action "filterStudent"}} value={{target.value}} class="form-control">

A: My controller is not getting invoked from the component the sendAction method is not working.
MyController.js
 actions:
 {
    filterStudentResults(param)
    {
     if (param !== '')
     {
       return this.get('store').query('Students', { studentName: param });
     }
     else
     {
       return this.get('store').findAll('Students');
     }
   }
}

am calling the component from the template as follows
{{bind-dropdown model=model filter=(action 'filterStudentResults')}}

My Component js
actions:{
  filterStudent(selectedValue){
    this.sendAction('filterPartsResults',selectedValue)
 }

My Componet file name is bind-dropdown and my contollers name is studentsController. The template name is list-studentDetails.


text:
Q: Importing CSV table - Error I am new to LaTeX and am compiling a document right now using TeXworks. I am trying to create CSV tables into my document right now, and although I succeed in between I must have some small bug in the code which I just cannot spot (trust me I looked for hours).
My code is the following:
\documentclass[9pt]{article}

% Load packages

%************************************************************

\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{geometry}
    \geometry{verbose,tmargin=1in,bmargin=1in,lmargin=0.75in,rmargin=0.75in}
\usepackage{textcomp}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{rotating}
\usepackage{datatool} % Allows importing tables
\usepackage{enumerate} % Allows latin I option

\renewcommand{\tabcolsep}{2pt}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\DTLsetseparator{,}
\DTLloaddb{tarea}{table_test.csv}

\begin{table}
  \caption{Area}
  \centering
  \DTLdisplaydb{tarea}
\end{table}

\end{document}

Latex gives me the following errors:
Error 1
undefined
34
! Argument of \@dtl@trim has an extra }.
<inserted text>
                \par
l.34 \beginstable}

Error 2
undefined
?
LaTeX Warning: Unused global option(s):
    [9pt].

Error 3
undefined
?
Package geometry Warning: The marginal notes overrun the paper.
     Add 21.7975pt and more to the right margin.

A: May I suggest you to use pgfplotstable? It works great with CSV files and gives you a lot
of control. Here's a nice example:
\documentclass[oneside]{article}

\usepackage{pgfplotstable}
% recommended:
\usepackage{booktabs}
\usepackage{array}
\usepackage{colortbl}

\pgfplotstableset{col sep=comma}

\begin{document}

\begin{table}
\centering
\pgfplotstabletypeset[%
    % Sort the values
    sort, sort key=error2,
    %
    % The columns to be printed
    columns={dof,error1,{grad(log(dof),log(error2))}},
    %
    % Columns styles
    columns/error1/.style={
        % Name
        column name=$L_2$,
        % Notation and padding
        sci,sci zerofill, sci subscript,
        precision=3},
    columns/dof/.style={
        sci, sci sep align,
        column name=\textsc{Dof}},
    columns/{grad(log(dof),log(error2))}/.style={
        column name=slopes $L_2$,
        fixed, fixed zerofill,
        % Align decimal deparators
        dec sep align,
        precision=1},
    %
    % Some colors.
    every even row/.style={
        before row={\rowcolor[gray]{0.9}}},
    every head row/.style={
        before row=\toprule,after row=\midrule},
    every last row/.style={
        after row=\bottomrule},
        ]{data.csv}
\end{table}

\end{document}


text:
Q: Can I do this with autolayout/size classes? Can I  do this with autolayout and size-classes in xcode 6 , and, if so, how do I accomplish it ?
The view should have aspect ratio 7:6 and the 4 buttons should appear as is shown in below.

A: https://www.youtube.com/watch?v=p5wD8dvSDbM
its very easy, see the video :) Only you can do in iphone, for ipad no identify landscape or portrait orientation

A: Size classes are not based on a specific size (i.e. < 300 pts == compact), but rather devices and specific orientations.  Because of that, you won't have the fine grained control I assume you want.
However, if you're okay giving up some control, you simply change the simulated size class in interface builder, setup your constraints, and they just work at run-time.


text:
Q: Overcome onOpen() timeout using Google Apps Script Is there a way I can have an onOpen() function auto refresh the page before timing out, and pick up from where it got to when the onOpen() function runs again?
Bit of background on what I am trying to achieve;
Due to the lack of print area feature on google sheets I am using a GAS script that takes a range from each sheet in the spreadsheet and copies it to a another sheet labeled 'PRINT' within the same spreadsheet. This then allows me to just print the whole 'PRINT' sheet. Each range copied over is the equivalent to an A4 page so it then prints nicely from here.
The issue I have is I create several spreadsheets every day from a template so in order to run the script that carries out this function I have to go through accepting permission for every spreadsheet.
I have overcome this somewhat by having a cell in the spreadsheet that when changed to "print" is picked up by the "onOpen()" function and knows to run the 'PRINT' function. So for example I would decide I wanted to run my 'PRINT' script but instead of accepting the permissions I just change my watched cell to "print" and refresh the page. This seems to bypass not having accepted the required permissions but sometimes it will time out before finishing the function.

function onOpen() {
      var ws = SpreadsheetApp.getActiveSpreadsheet();
      if(ws.getSheetByName("Title Page").getRange("F14").getValue() == "Print"){
        var title = ws.getSheetByName("Title Page")
        var calcs = title.getRange("N1").getValue() // Get number of sheets to move
        for (var i=0; i<calcs; i++) {
          var sheet = title.getRange(3+i,11).getValue(); // Get list of sheet names
          var pages = ((title.getRange(3+i,13).getValue())-(title.getRange(3+i,12).getValue()))+1 //Gets number of pages on each sheet, some have more than one. Column 12 is page from, Column 13 is page to
          var cpystart = ws.getSheetByName(sheet).getRange("G1").getValue()
          var cpy = ws.getSheetByName(sheet).getRange(1,cpystart,50,7*pages);
          var pst = ws.getSheetByName("PRINT").getLastColumn()
          cpy.copyTo(ws.getSheetByName("PRINT").getRange(1,pst+1))
          var cpyvalues = cpy.getValues();
          ws.getSheetByName("PRINT").getRange(1,pst+1,50,7*pages).setValues(cpyvalues);
        }
        ws.getSheetByName("Title Page").getRange("F14").setValue("Done")
      }

}

A: I'm not sure if this will work for you but there are a lot of getValue().  You getRange(3+i,11).getValue() for consecutive rows so I moved it outside the loop and then access the values array.
function xxonOpen() {
  var ws = SpreadsheetApp.getActiveSpreadsheet();
  var title = ws.getSheetByName("Title Page");
  if( title.getRange("F14").getValue() == "Print" ) {
    var calcs = title.getRange("N1").getValue(); // Get number of sheets to move
    var sheets = title.getRange(3,11,calcs,3).getValues(); // Get list of sheet names
    for (var i=0; i<calcs; i++) {
      //Gets number of pages on each sheet, some have more than one. Column 12 is page from, Column 13 is page to
      var pages = sheets[i][2]-sheets[i][1]+1;
      var cpySheet = ws.getSheetByName(sheets[i][0]);
      var cpystart = cpySheet.getRange("G1").getValue();
      var cpy = cpySheet.getRange(1,cpystart,50,7*pages);
      var pstSheet = ws.getSheetByName("PRINT");
      var pst = pstSheet.getLastColumn();
      cpy.copyTo(pstSheet.getRange(1,pst+1));
      var cpyvalues = cpy.getValues();
      pstSheet.getRange(1,pst+1,50,7*pages).setValues(cpyvalues);
    }
    title.getRange("F14").setValue("Done")
  }
}


text:
Q: Is an operating system responsible to making the best use of system resources? Suppose I have a powerful desktop PC with a high performance CPU and GPU. Does my OS decide how it should use these resources? Can there be any notable differences between different operating systems when they run on this PC? For example if I install Windows on this PC and run Blender on it, can it be possible that Blender run better (faster, more efficient) than when I install Ubuntu on that PC? Has Windows fantastic 3D Games because it can interact better with these resources? Or it depends only on my Hardware? Please provide documentary evidence if possible.

A: If I was just answering to your headline, then answer is of course. The OS controls the hardware so definitely it is the only piece of software that is responsible.
If you consider the device drivers as separate from the OS then yes, it can get tricky as to which piece is controlling which resource.
Now to your individual questions.

*

*Yes.

*Yes, always due to different algorithms of each OS.

*Definitely, due to the differences across OS's and how they allocate resources.

*Technically it's not windows that interacts better with resources, though with various technologies like DirectX, Direct3D, windows allowed device drivers to optimize many calls, hence leading to better performance. This is more of a market issue because windows market is big so device driver writers can put more time and energy into optimizing their hardware. Linux driver support can be somewhat limited. Also the game developers have a larger market in windows, so they are naturally going to put a lot more effort into windows. That doesn't mean windows is a better operating system.

*No. See above answer.

I'm not really sure what documentary evidence you'll need. Existence of lack of existence of some games is a market factor and you can simply confirm that by searching the web for Games by OS.
However I can suggest a bit of reading..
For questions #1 and #2 you may read uo Windows Architecture, an interesting "opinions" discussion Who has faster multi-tasking and finally a summarized write up on different OS's multi tasking v/s single tasking and other details
For question #3 and #4 you might read up on DirectX and Direct 3D and links those lead you do.


text:
Q: Spring 4 websockets dynamic MessageMapping not executed I'm using Spring 4 websockets on Tomcat 8 and I have the following configuration:
<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/notify">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic" />
</websocket:message-broker>

My Spring controller has the following method:
@MessageMapping("/notify/{client}")
public void pushMessage(@DestinationVariable long client, String message) {
    System.out.println("Send " + message + " to " + client);
    template.convertAndSend("/topic/push/" + client, message);
}

So what I'm trying to do here is that if client 1 wants to send a message to client 2, he uses /app/notify/2. The Spring controller will then push the message to topic /topic/push/2.
I wrote the following code in my client:
var id = 1;
var sock = new SockJS('/project/notify');
var client = Stomp.over(sock);
client.connect({}, function() {
    client.subscribe('/topic/push/' + id, function(message) {
        console.log(message);
    });
});

The connection works perfectly, /project is just the context root of my application.
I also have the following code in my client to send a message:
client.send('/app/notify/' + id, {}, "test");

Both variables (client and id) are accessible, I'm not getting any errors from this part of the code and I can see in my console that the message is actually sent:
>>> SEND
destination:/app/notify/1
content-length:4

test

However, the System.out.println() statement in my controller is never executed, so I assume there is something wrong with my controller mappings or I'm not using the destination endpoints correctly (I don't understand why I have to specify the application prefix here, but not when connecting to that endpoint).

A: It seems it's unable to map when using a simple String message as payload. When I wrap the message in an object, then it works just fine.
EDIT: As stated in the comments, Spring already comes with a message wrapper called the TextMessage class.


text:
Q: Pylance autocompletion with subclasses The problem is that in the following situation, autocompletion in the SubFoo class does not work in Pylance. Pylance only recognize the methods and attributes of the Bar class inside SubFoo class, but not the methods and attributes of the SubBar class. Am I doing the right thing?
class Bar:

    def method1(self):
        # do stuff

class SubBar(Bar):

   def method2(self):
       # do stuff

class Foo:

    def __init__(self, arg: Bar):
        self.attr: Bar = arg

    def do_a(self):
       self.attr.method1()

class SubFoo(Foo):

    def __init__(self, arg: SubBar):
        super().__init__(arg)

    def do_b(self):
       self.attr.method1() # Pylance's autocopmletion recognizes method1()
       self.attr.method2() # Pylance's autocopmletion doesn't recognize method2()

A: You've declared the type of Foo.attr to be Bar. The fact that it happens to be assigned a SubBar at some point is not the type checker's concern. If you want to statically know the type of the field based on the subclass, then Foo should be generic.
from typing import TypeVar, Generic

_T = TypeVar("_T", bound=Bar)

class Foo(Generic[_T]):

    def __init__(self, arg: _T):
        self.attr: _T = arg

    def do_a(self):
       self.attr.method1()

class SubFoo(Foo[SubBar]):

    def __init__(self, arg: SubBar):
        super().__init__(arg)

    def do_b(self):
       ...

Now subclasses of Foo are required to report which subclass of Bar they expect their constructor to receive, and that type information becomes available statically.
You'll also want to consider making that type variable covariant, if your use case supports it.


text:
Q: Регистрация пользователя <?php
echo "
Регистрация
";
$submit = strip_tags($_POST['submit']);
$name = strip_tags($_POST['name']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['repeatpassword']);
$email = strip_tags($_POST['email']);
$date = date("Y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$ip = $_POST['ip'];
if ($submit)
{
 // check for existans
if($name&&$password&&$repeatpassword&&$email)
{

if ($password==$repeatpassword)
{

//check name
if(strlen($name)>15||strlen($name)<4)
{
echo "Логин должен быть от 4 до 15 символов!";
}
else
{
 //check password
if (strlen($password)>25||strlen($password)<6)
{
echo "Пароль должен быть от 6 до 25 символов";
}
else
{

if (isset($_POST['name']))
{
$name = $_POST['name'];
}

if (isset($_POST['password']))
{
$password = $_POST['password'];
}

if (isset($_POST['email']))
{
$email = $_POST['email'];
}

if (isset($_POST['date']))
{
$date = $_POST['date'];
}

if (isset($_POST['ip']))
{
$ip = $_POST['ip'];
}

 //encrypt password
$password =md5($password);
$repeatpassword =md5($repeatpassword);

//open database
$db = mysql_connect("localhost","root","vladon12");
mysql_select_db("testgame");
$result = mysql_query ("INSERT INTO `users` (name,password,email,date,ip) values('$name','$password','$email','$date','$ip')");

die ("Добро пожаловать в игру =) Нажми здесь для продолжения

");

}

}

}
else
echo "Пароли не совпадают!";

}
else
echo "Введите все поля";

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title><?php echo $config['title'];?></title>
<meta http-equiv = "content-type" content = "text/html; charset = <?php echo $config['coder'] ; ?>" />

<form action="index.php?page=register" method="post" name="form">

*Логин:
<input name="name" type="text" size="20" maxlenght="40">

*Пароль:
<input name="password" type="password" size="20" maxlenght="40">

*Пароль:
<input name="repeatpassword" type="password" size="20" maxlenght="40">

e-Mail:
<input name="email" type="text" size="20" maxlenght="40">

<input name="submit" type="submit" value="Зарегистрироваться">

<<назад

Не заносит пользователя в бд, что делать? Подскажите, пожалуйста.
A: $result = mysql_query ("INSERT INTO `users` (name,password,email,date,ip) values('$name','$password','$email','$date','$ip')");

Поменя на
$result = mysql_query ("INSERT INTO `users` (name,password,email,date,ip) values('$name','$password','$email','$date','$ip')") or die(mysql_error());

Что выведет?
A: Сделайте так:
$sql = "INSERT INTO `users` (name,password,email,date,ip) values('$name','$password','$email','$date','$ip')";
echo $sql;
$result = mysql_query ($sql);
if (!$result) echo mysql_error();

В результате чего увидите какой запрос отправляется в базу. Наверняка с ним что-то не так. А так же, если запрос не удался, то на выходе будет еще и ошибка. Т.е. будете знать где именно в запросе ошибка.


text:
Q: A mathematics nazi is part of the mathematical inquisition? I learned that a grammar nazi is someone who seems extremely authoritarian in compulsively correcting people's grammar mistakes and other errors while practicing languages. And today I learned another phrase: mathematical inquisition.

I've taken a bit of freedom with regards to the notation; if you're part of the mathematical inquisition then take a chill pill.

I wonder 1) if I can coin a phrase like mathematics nazi to represent someone who cannot bear any freedom with regards to mathematical notations? 2) Is there already such a phrase or word? 3) Can I append a nazi to anything to represent someone who is very restrictive on that?

A: I wonder if I can coin a phrase like mathematics nazi to represent someone who cannot bear any freedom with regards to mathematical notations?
Yes, this would be readily understood.  As a colloquialism it would probably be abbreviated to "math nazi" (US) or "maths nazi" (UK).  There is also some variation in practice regarding the word "nazi" - some people capitalise it (as almost everyone would when using it literally).
Is there already such a phrase or word?
Yes, by using a tool called "Google", I've been able to deduce that some people are already using "math nazi" and similar phrases.
Can I append a nazi to anything to represent someone who is very restrictive on that?
Potentially yes.  However, I'd inject a note of caution.  While the term "grammar nazi" may have become sufficiently widespread that people will understand that you are not being deliberately provocative (at least in informal contexts), this sort of metaphorical use of the term "nazi" could be seen as offensive, given that it might appear to be making light of a regime that murdered millions of people.


text:
Q: Passing Data to view - Undefined variable I'm new to the Laravel Framework and I somehow got an issue that bothers me for days now.
I just wanted to pass a simple variable to a blade view, but any version that I found in any documentation or question on this platform unfortunately didn't lead to a solution.
I created a route which looks like this:
Route::get('test', 'PageController@index');

The Code in the PageController looks like this:
public function index(){
   $datatopass='datahere';
   return view('admin.test', compact('datatopass'));
}

And then I got the View that looks like this:
@section('content')
{{$datatopass}}
@stop

The problem is that I get 2 Exeptions:

#ErrorException in d9e848d01f99ac2368ead804bd322152 line 3:
Undefined variable: datatopass (View: /home/vagrant/test/resources/views/admin/test.blade.php)

ErrorException in d9e848d01f99ac2368ead804bd322152 line 3:
Undefined variable: datatopass

I'm using homestead development environment which is set up in a VirtualBox.
Any ideas what I've done wrong?
I really tried every type of datapassing like
return view('test')->with('datatopass', $datatopass)`
//or
return view('datatopass', $datatopass)

and so on.
I'll be greateful for your help.

A: Try this::
return view('test')->with('datatopass', $datatopass);

And in View access it as
<?php echo $datatopass ?>


text: Q: How can I keep track of changes to files by specific programs? In Ubuntu, is it possible to keep track of all programs that are used to modify one file? For example, if I had a file called sampleText.txt, would it be possible to generate a list of every edit that had been made to that file, along with each program that had edited it?


text:
Q: Formatting: $\overline{X_1}$ or $\overline{X}_1$? To represent the means of a two random variables $X_1, X_2$, should the bar also cover the subscript, i.e.

should it be
$$\overline{X_1},\overline{X_2}$$
or
$$\overline{X}_1,\overline{X}_2$$

and why?
The first option seems to be the logical choice but the second option looks neater.

Addendum: If we decided that the first option is the appropriate one, what would the second option then represent?

A: In this situation, the first option certainly seems more "logical," i.e. you can interpret its meaning right away.
However, you can also justify the second by considering $X$ to be tuple of two random variables (with components $X_1$ and $X_2$) and the mean of the tuple to be the tuple $\overline{X}$ with components
$$
    \overline{X}_i = \overline{X_i}
$$
for every relevant index $i$ (i.e. $i \in \{1, 2\}$). This is what I would expect the second notation to denote – so the second would really be the same as the first.
After all, considering their visual similarity, it would almost seem malicious to use them for different things.

A: The notation $\overline{X_i}$ is more correct if you indicate $X_i=Y$ as a random variable.
Often you can find the notation $\overline{X}_n$ which means the sample average of the rv $X$ based on a $n$ size simple random sample.
This is taken from Mood Graybill Boes, McGraw Hill

In other words,
$$\overline{X_n}$$
indicates the sample mean of the rv $X_n$ but
$$\overline{X}_n$$
indicates the sample mean of the rv $X$ calculated on a $n$ sized random sample from $X$

A: $$\overline{X_n}=\frac1n\sum_{i=1}^nX_n$$ is the average of the samples $X_n$.
$$\overline X_n=\frac1m\sum_{i=1}^mX_{m,n}$$ is the average of the $n^{\text{}th}$ distribution.
In practice, both notations are probably used interchangeably (though illogically).


text:
Q: Is a path connected subspace of a simply connected space simply connected? This is sort of a lemma I'm trying to prove for a larger proof. It seems intuitively true: if a space has trivial fundamental group, any two loops based at a point are homotopic. A subspace of such a space should have the same property, since loops based at a point must lie in the same path component as the point. That path component is path connected, and any two loops in it are homotopic, so the path component is simply connected as well. I'm having trouble making the "path component has trivial fundamental group" part rigorous though. Can anyone give me a nudge in the right direction? My idea so far is to use the existence of paths connecting points on any two loops to make a homotopy between them but I'm not sure how to make that formal.

A: Take the unit sphere $S^1$ as a subspace of the simply connected space $\Bbb R^2.$
Note that $S^1$ is not a retract of $\Bbb R^2$. Otherwise, it had to be simply connected, too.

A: The question from the title was already answered, I will answer the question form the "body" of the post: we will show that path components of a space with trivial fundamental group have trivial fundamental groups.
Consider any path component $C$ of the space $X$, $x_0\in C$ and any loop $\omega$ based at $x_0$. Because the fundamental group is trivial, we have a homotopy $h:S^1\times [0,1]\to X$ between $\omega$ and the constant loop. Because $S^1\times [0,1]$ is path connected and images of path connected spaces are path connected, we conclude that $h(S^1\times[0,1])$ must lie in $C$ (do not intersect any other component of the space). Thus, the result follows.


text:
Q: How to extend the Size of my Ubuntu Partition I have Installed Ubuntu 13.04 on my pre-installed Windows8 sony laptop with HDD of 500Gb.
There are a few partitions present by default like recovery ,etc.
I have created a few other partitions of 200 GB and 100 GB on /dev/sda7 and /dev/sda8 respectively. My Windows 8 is installed on /dev/sda5 while I have installed Ubuntu on /dev/sda11 with swap on /dev/sda12.
Now, I want to shrink my Windows 8 drive which is 109 GB and extend the Ubuntu partition of 15 GB by using the unallocated space from the earlier drive.
I tried using GParted via LiveUSB and performing the SWAP-OFF but I was unsuccessful.
Please suggest me a way ASAP.
Thanks.

A: I think you should better be careful about the following:

*

*If you really need to shrink the Windows (7/8) operating system
partition, try and do this operation using its own Disk Management
Tool in order to avoid Windows booting problems.

*It seems you have a number of (max. 4) Primary Partitions, at least
1 of which is an Extended Partition, which in turn includes any
number of Logical Partitions, and this makes the things a little
more complicated if any one of the partitions you want to
shrink/expand is inside such an Extended Partition while the other
is outside. In such a case, you should carefully look at the order
of partitions in GParted to make sure that you create the
Unallocated Space at the correct end and then and move it at the
correct direction so that you can follow the correct route to get
into and out of the Extended Partition and then to join with the
other (Primary) partition or vice versa.


text:
Q: Proving divergence of $\int_1^{\infty}e^{-\arctan(x)}\ \mathrm{d}x$ I wish to show that the integral:
$$\int_1^{\infty}e^{-\arctan(x)}\ \mathrm{d}x$$
diverges.
I tried to use the different comparison tests but couldn't get to anything.
I would like to get a hint, and hopefully continue from there on my own.

A: The substitution $x=\tan t$ rewrites the integral as $$\int_{\frac{\pi}{4}}^{\frac{\pi}{2}}e^{-t}\sec^2(t)\ \mathrm{d}t\ge e^{-\pi/2}\int_{\frac{\pi}{4}}^{\frac{\pi}{2}}\sec^2(t)\ \mathrm{d}t=\infty.$$

A: Note that\begin{align}\lim_{x\to+\infty}e^{-\arctan x}&=e^{-\lim_{x\to+\infty}\arctan x}\\&=e^{-\frac\pi2}.\end{align}So, take $M>0$ such that $M<e^{-\frac\pi2}$. Then, compare your integral with $\int_1^{+\infty}M\,\mathrm dx$.


text:
Q: The return type 'Future' isn't a 'Widget', as required by the closure's context I'm sending login info to an api and getting a image id number that I send back to the api to get the image and i want to display the images in a grid but i'm getting a "The return type 'Future' isn't a 'Widget', as required by the closure's context." error.
the error is on the recentAlbumArt function
import 'package:flutter/material.dart';
import 'package:test_music_app/API/api_call.dart';

import 'package:test_music_app/API/auth.dart';

class RecentlyAddedAlbums extends StatefulWidget {
  @override
  _RecentlyAddedAlbumsState createState() => _RecentlyAddedAlbumsState();
}

class _RecentlyAddedAlbumsState extends State<RecentlyAddedAlbums> {
  Future<List<Album>> albums;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: FutureBuilder(
            future: fetchRecentlyAddedAlbums(),
            builder: (context, AsyncSnapshot<List<Album>> data) {
              switch (data.connectionState) {
                case ConnectionState.none:
                  return Text(
                    "none",
                    style: TextStyle(color: Colors.black),
                  );
                case ConnectionState.waiting:
                  return Center(
                      child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                  ));
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (data.hasData) {
                    List<Album> albums = data.data;
                    return ListView.builder(
                      itemCount: albums.length,
                      itemBuilder: (context, index) {
                        return FutureBuilder(
                            future: recentAlbumArt(albums[index].coverArt),
                            builder: (context, AsyncSnapshot data) {
                              switch (data.connectionState) {
                                case ConnectionState.none:
                                  return Text(
                                    "none",
                                    style: TextStyle(color: Colors.black),
                                  );
                                case ConnectionState.waiting:
                                  return Center(
                                      child: CircularProgressIndicator(
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                        Colors.black),
                                  ));
                                case ConnectionState.active:
                                  return Text('');
                                case ConnectionState.done:
                                  if (data.hasData) {
                                    return recentAlbumArt(
                                            albums[index].coverArt)
                                        .then((coverArtList) {
                                      return Image.network(coverArtList[index]);
                                    });
                                  }
                              }
                            });
                      },
                    );
                  }
              }
            }),
      ),
    );
  }
}

the two functions:
Future<List<Album>> fetchRecentlyAddedAlbums() async {
  try {
    var salt = randomToken(6);
    var token = makeToken("$password", "$salt");
    var uRL =
        "$server/rest/getAlbumList?u=$username&t=$token&s=$salt&v=$tapeOutVerison&c=$client$format&type=newest";
    var authresponse = await http.get(uRL);
    if (authresponse.statusCode == 200) {
      var jsondata = jsonDecode(authresponse.body);
      var data = apicallFromJson(jsondata);
      var aresponse = data.subsonicResponse.albumList.album;
      return aresponse;
    } else {
      return null;
    }
  } catch (e) {
    return null;
  }
}

//TODO: build the cover art fetching within the album list or build it outside
Future recentAlbumArt(String coverArtID) async {
  try {
    var salt = randomToken(6);
    var token = makeToken("$password", "$salt");
    var uRL =
        "$server/rest/getCoverArt/?u=$username&t=$token&s=$salt&v=$tapeOutVerison&c=$client$format&id=$coverArtID";
    var coverArtList = await http.get(uRL);
    return coverArtList;
  } catch (e) {
    print(e);
  }
}

A: There is a mistake in the use of your nested FutureBuilder. Rather than using the snapshot in the FutureBuilder builder, you are calling the recentAlbumArt again and returning that.
if (data.hasData) {
  return recentAlbumArt(//CALLING recentAlbumArt AGAIN HERE
    albums[index].coverArt)
      .then((coverArtList) {
        return Image.network(coverArtList[index]);
      });
}

Instead use the snapshot that the FutureBuilder provides.
if (data.hasData) {
  return Image.network((data.data)[index]);
}


text:
Q: Splitting a list into N parts to get a list of tuples I've a list in which I have to split it in 9 parts but I got a list of lists, and I want to get a list of tuples. I don´t know if I can do this on python.
data= [1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03, 2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03]

I tried this:
data = [data[i:i+9] for i in range(0, len(data),9)]

I got this:
data= [[1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03],[ 2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03]]

But, I want to get this:
data= [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03),(2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03)]

A: Your solution is almost finished, you can just convert to tuple:
data = [tuple(data[i:i+9]) for i in range(0, len(data),9)]
        ^                ^
        this will convert inner lists to tuples

>>> [tuple(data[i:i+9]) for i in range(0, len(data),9)]
[(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03'), (2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03')]

A: You can try this:
list_of_tuples = [tuple(item) for item in data]


text:
Q: What are Cassandra frozen collection size limits? I see info here on collection size limits in cassandra, but it includes this note: "The limits specified for collections are for non-frozen collections." I can't find limits on frozen collections defined anywhere.

A: Frozen collections are treated as blobs so there is no imposed limit on them (other than the overall size that you would want to have in partitions etc).
Frozen collections are useful if you want to use them in the primary key. Frozen collection can only be replaced as a whole, you cannot for example add/remove elements in a frozen collection.


text:
Q: Declaring XML in SQL Server issue I have a T-SQL issue, I am trying to do the following and I receive an error message when I try to run the SELECT statement, saying that I didn't declare the @Xml variable, any help would be appreciated, thanks.
DECLARE @Xml XML = N'
 <products>
 <product id="1" name="Adjustable Race" />
 <product id="879" name="All-Purpose Bike Stand" />
 <product id="712" name="AWC Logo Cap" />
 <product id="19910" name="Cozonac" />
 </products>';

SELECT
    xt.xc.value('@id', 'INT') AS ProductID,
    xt.xc.value('@name','NVARCHAR(50)') AS Name
FROM
    @Xml.nodes('/products/product') AS xt(xc);

A: Declaring and directly assigning a value to a parameter is new.
In previous versions of SQL Server, you should first declare and then as a seperate statement set the value of it.
Perhaps you can try
DECLARE @Xml XML
SET @Xml = N'...'


text:
Q: GDI Overall Clipping Bounds Does GDI have any method of setting an overall clipping area, in the same way the GDI+ Graphics object does?
Specifically:

*

*Graphics.DrawString uses GDI+ which includes the clipping bounds system.

*TextRenderer.DrawText uses GDI which does not.

My new scrollbar system automatically resizes the Graphics draw area as needed. While tidying up a control which uses it, I switched some inline string rendering calls over to my text layout class, which uses TextRenderer.DrawText. I can't quite remember why I used that instead of just Graphics.DrawString, but before I refactor that I wanted to check if there was some way of fixing the problem as it stands.
public class GraphicsClipExample : Form
{
    public GraphicsClipExample()
    {
        this.ClientSize = new Size(this.ClientSize.Width, 100);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // update the graphics clip area
        e.Graphics.Clear(Color.Cyan);
        e.Graphics.SetClip(new Rectangle(0, 0, e.ClipRectangle.Width, 50));
        e.Graphics.Clear(Color.Magenta);

        Font font = new Font("Calibri", 24);
        e.Graphics.DrawString("Testing", font, Brushes.Black, 10, 28);

        TextRenderer.DrawText(e.Graphics, "Testing", font, new Point(150, 28), Color.Black);
    }
}

This produces the following output:

Is there any way to provide a simple clipping area for GDI overall, or TextRenderer specifically?
Many thanks

A: Try using the PreserveGraphicsClipping format flag:
  TextRenderer.DrawText(e.Graphics, "Testing", font, new Point(150, 28),
                        Color.Black, Color.Empty,
                        TextFormatFlags.PreserveGraphicsClipping);


text:
Q: esb wso2 4.8.1 proxy service analysis soap xml error, the xml contain special char I have a sample,use api invoke proxy service, from the api transmission parameters contained in the special fields. then the proxy background parse error.
Sample API code:

<api xmlns="http://ws.apache.org/ns/synapse" name="eva_data" context="/kdmService/rest/2.0/evaluation/data/current/kksCodes">
   <resource methods="POST">
      <inSequence>
         <log level="full">
            <property name="kks=============" expression="$body/mediate/*[substring(name(),1,8)='kksCodes']"></property>
         </log>
         <property name="kks" expression="$body/mediate/*[substring(name(),1,8)='kksCodes']"></property>
         <header name="kksCodes" scope="transport" expression="get-property('kks')"></header>
         <call>
            <endpoint>
               <address uri="http://127.0.0.1:8280/services/searchMultiEvaData" format="pox"></address>
            </endpoint>
         </call>
         <respond></respond>
      </inSequence>
   </resource>
</api>

request address:
http://localhost:8080/kdmService/rest/2.0/evaluation/data/current/kksCodes

request parameters:
kksCodes[]="EB001HP1MEJ01ME029BL01J1CB001BB01"

Sample proxy code:

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="searchMultiEvaData"
       transports="https,http,local"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <log level="full">
            <property name="kksCode" expression="get-property('transport','kksCodes')"/>
         </log>
         <property name="uri.var.kksCodes"
                   expression="get-property('transport','kksCodes')"/>
         <property name="uri.var.isPathVariable" value="false"/>
         <call>
            <endpoint key="searchEvaKksAddressPoint"/>
         </call>
         <enrich>
            <source type="body" clone="true"/>
            <target type="property" property="_payload"/>
         </enrich>
         <log>
            <property name="payload1" expression="get-property('_payload')"/>
         </log>
         <property name="payload" expression="get-property('_payload')"/>
      </inSequence>
      <outSequence>
      </outSequence>
   </target>
   <description/>
</proxy>

when api invoke proxy service,background error. console output error:

[2016-04-15 11:34:47,144]  INFO - LogMediator To: /kdmService/rest/2.0/evaluation/data/current/kksC
odes, MessageID: urn:uuid:950bf641-c481-4527-8266-e535e906d6bf, Direction: request, kks============
= = EB001HP1MEJ01ME029BL01J1CB001BB01, Envelope: <?xml version="1.0" encoding="utf-8"?><soapenv:Env
elope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><mediate><kksCodes%5B%5
D>EB001HP1MEJ01ME029BL01J1CB001BB01</kksCodes%5B%5D></mediate></soapenv:Body></soapenv:Envelope>
[2016-04-15 11:34:47,151] ERROR - NativeWorkerPool Uncaught exception
org.apache.axiom.om.OMException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,19
]
Message: 元素类型 "kksCodes" 必须后跟属性规范 ">" 或 "/>"。
 at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:296)
 at org.apache.axiom.om.impl.llom.OMElementImpl.buildNext(OMElementImpl.java:653)
 at org.apache.axiom.om.impl.llom.OMElementImpl.getFirstOMChild(OMElementImpl.java:670)

parameters xml format:

 <?xml version="1.0" encoding="utf-8"?>
 <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
    <mediate>
     <kksCodes[]>EB001HP1MEJ01ME029BL01J1CB001BB01</kksCodes[]>
    </mediate>
   </soapenv:Body>
 </soapenv:Envelope>

I think is kksCodes[] analysis error,but i don't know solve it. help me! thanks!

A: You can enclose the <kksCodes[]> element within a CDATA block as follows.
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
 <soapenv:Body>
  <mediate>
   <![CDATA[
     <kksCodes[]>EB001HP1MEJ01ME029BL01J1CB001BB01</kksCodes[]>
   ]]>
  </mediate>
 </soapenv:Body>
</soapenv:Envelope>

Since the value within the CDATA block is not proper XML, you will not be able to extract the kksCodes using an xpath expression straight away.
To extract this you will have to perform a string manipulation using the script mediator in WSO2 ESB. [1]
Once the code is extracted you can set it as a property using the script mediator itself.
Thereafter you can set the kksCodes as a transport header and pass it on to the proxy service.

A: String manipulation in WSO2 ESB using the script mediator can easily be done by following this blog post. There is always the possibility to write your own custom mediator. This is a java program that gives you almost complete control but there are perhaps easier ways of getting the job done. IN this blog post example code how to do it.


text:
Q: 500 Internal Server Error on combining two functions in Rails I have two POST APIs :
def add_friend
   //do something
end

and
def delete_friend
   //do something
end

Both these APIs work correctly on POST requests. But when I combine these two functions and write one function which does both the jobs based on a POST request parameter, it gives 500 Internal Server Error.
What is wrong?


text:
Q: Report browser crash to server I want to add a feature to my web app which may cause the browser to run out of memory and crash for computers low on RAM. Is there any way that I can report when this happens to the server to determine how many users this happens to?
EDIT:
The specific problem is that the amount of memory used scales with the amount the user is zoomed in. To cope with this we will limit how much users can zoom in. We have an idea of how much to limit it based on in-house tests, but we want to know if the browser tab crashes for any users after we release this.
We could reduce the memory consumption with zooming, but doing so would entail a tremendous amount of refactoring, and would probably have negative, and possibly unacceptable performance losses.
Note that this is not "we know this happens, but we want to know how much", and more of "we don't think this will happen, but we want to know if it does."

A: There is no real way to get this information. If a server stops receiving data (sent by a websocket or such) via something such as a crash it has no way of telling what caused the stop. Either a browser tab being purposefully closed or a crash.
You could potentially check speed of a loop and report it to the server - such as frame-rate in a requestAnimationFrame - and check for trends if you are a fall before a close - but this is laden with pitfalls and potentially adds work to the client that may only add to your intensive code.


text:
Q: How to determine the number of edges in this graph? Let $Q_k$ be the graph whose vertex set corresponds to the set of all $01$-sequences of length $k$ with an edge between two vertices if the sequences differ in exactly one place.
Draw $Q_3$.(DONE)
Determine (with reasons) $e(Q_k)$ and show that $Q_k$ is bipartite.
My solution so far:
$d(G) = 2\cdot \frac{e(G)}{|G|}$ for a graph $G$.
So $e(Q_k)= \frac{1}{2} \cdot d(Q_k) \cdot |Q_k| $
Now  $|Q_k|  = 2^k$ since for a $01$ sequence of length $k$ we have two choices (0 or 1) for each position in the sequence, giving us
$|Q_k|  = 2 \cdot 2 \cdot ... \cdot2$ (k times) $=2^k$.
Now, I am not sure how to work out $d(Q_k)$, the average degree of $Q_k$. From drawing $Q_3$ which has $d(Q_3)=3$, I can guess $d(Q_k)=k$. But how would I go about proving this?
Also any hints on how to show  $Q_k$ is bipartite?
Note: If anything is unclear in the question or solution, please let me know and I will clarify it.


text:
Q: How do I stop the ambient light sensor from dimming my screen? The ambient light sensor (ALS) within the Intel Sensor Hub device on my Intel-branded Ultrabook keeps dimming my screen. It does not react to manual screen brightness changes. Is there a way to disable it?
I'm running Windows 8 RTM.

A: Go to the Metro Settings. General Tab. Scroll down and you will see automatic brightness. Just turn it off

A: Try to put some tape over the sensor?
Have you tried to disable the service?

*

*Run the services panel by typing in Win+R and running services.msc

*Find the Sensor Monitoring Service and go to the properties menu by right clicking

*In the general tab you should find an option to set the startup type field to disabled

*Restart and let us know how it went!


text:
Q: Elegant representations of graphs in R^3 If I have a graph of a reasonable size (e.g. ~100 nodes, ~40 edges coming out of each node) and I want to represent it in R^3 (i.e. map each node to a point in R^3 and draw a straight line between any two nodes which are connected in the original graph) in a way which would make it easy to understand its structure, what do you think would make a good drawing criterion?
I know this question is ill-posed; it's not objective. The idea behind it is easier to understand with an extreme case. Suppose you have a connected graph in which each node connects to two and only two other nodes, except for two nodes which only connect to one other node. It's not difficult to see that this graph, when drawn in R^3, can be drawn as a straight line (with nodes sprinkled over the line). Nevertheless, it is possible to draw it in a way which makes it almost impossible to see its very simple structure, e.g. by "twisting" it as much as possible around some fixed point in R^3. So, for this simple case, it's clear that a simple 3D representation is that of a straight line. However, it is not clear what this simplicity property is in the general case.
So, the question is: how would you define this simplicity property?
I'm happy with any kind of answer, be it a definition of "simplicity" computable for graphs, or a greedy approximated algorithm which transforms graphs and that converges to "simpler" 3D representations.
Thanks!
EDITED
In the mean time I've put force-based graph drawing ideas suggested in the answer into practice and wrote an OCaml/openGL program to simulate how imposing an electrical repulsive force between nodes (Coulomb's Law) and a spring-like behaviour on edges (Hooke's law) would turn out. I've posted the video on youtube. The video starts with an initial graph of 100 nodes each with approximately 1-2 outgoing edges and places the nodes randomly in 3D space. Then all the forces I mentioned are put into place and the system is left to move around subject to those forces. In the beginning, the graph is a mess and it's very difficult to see the structure. Closer to the end, it is clear that the graph is almost linear. I've also experience with larger-sized graphs but sometimes the geometry of the graph is just a mess and no matter how you plot it, you won't be able to visualise anything. And here is an even more extreme example with 500 nodes.

A: One simple approach is described, e.g., at http://en.wikipedia.org/wiki/Force-based_algorithms_%28graph_drawing%29 . The underlying notion of "simplicity" is something like "minimal potential energy", which doesn't really correspond to simplicity in any useful sense but might be good enough in practice.
(If you have 100 nodes of degree 40, I have some doubt as to whether any way of drawing them is going to reveal much in the way of human-accessible structure. That's a lot of edges. Still, good luck!)


text:
Q: Owerflow in python when I try to solve my equation I want to calculate this simple equation in python3
from math import e
N*e**(r*t)

where e is the neper number and the rest is integer variables.
when I run my script it complains OverflowError: (34, 'Numerical result out of range')
What went wrong?


text:
Q: Which blocks will mobs walk off of voluntarily? In version 1.10.x, what blocks will mobs voluntarily walk off of, thinking that they are solid blocks?

A: There are few blocks that they (I tested with Zombies lead to Villagers and a 2-block wide pit) will think that are full and aren't. Their AI also makes them not go where they think there isn't a route - that is, even if they could fall off some other types of blocks, their AI won't drive them that way.
Here are some blocks that they count as full-solid:

*

*Trapdoors (both kinds)

*Doors (All kinds)
I couldn't find more, no matter what I tried - from Signs through Brewing Stands to Stairs. Nothing more, I guess. On the other hand, watch out for blocks that are solid, but mobs think not - Carpets, Heads, ...


text:
Q: Rails Omniauth for Linkedin not working I'm trying to get the Linkedin access token by Omniauth, using Devise, Omniauth and omniauth-linkedin-oauth-2. Either with facebook and twitter, I can get the access token, but when I try it with linkedin, I'm getting the following error in the omniauth callback:
ERROR -- omniauth: (linkedin) Authentication failure! invalid_credentials: OAuth2::Error, invalid_request: missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}

The linkedin app id and secret authentication is working, as I'm getting the callback on omniauth, the thing is I can't realise what the problem is here.
Devise config below:
  config.omniauth :linkedin, ENV['LINKEDIN_APP_ID'], ENV['LINKEDIN_APP_SECRET']

Any ideas on what could be happening?

A: I had the same problem and I found a way to resolve that.
In your Gemfile put this:
#Contains a generic OAuth2 strategy for OmniAuth
gem 'omniauth-oauth2', '~> 1.3.1'

And finally do:
bundle update

I think it should work.
More info in:
https://github.com/intridea/omniauth-oauth2/issues/81


text:
Q: Laravel multiple where clause in a whereHas constrain on a hasMany relationship I have the following query...
$pgcs = PrivateGuard::with(['licences', 'state'])
        ->whereHas('licences', function($query){
          $query->whereDate('expiration_of_licence', '<', Carbon::today())
                ->where('renewal', 0);
        })
        ->where('status', 1)
        ->get();

I want to get $pgcs with licences that fulfill the above conditions, the whereDate works correctly, but where('renewal', 0) doesn't seem to work correctly.
The above query gets $pgcs with licences that have renewal that is = 1 as well, although same $pgc also have licences with renewal value of 0 and another with 1, I don't want a $pgc that has any licence with renewal value of 1 to be retrieved in this query. what do I do?

A: your cases are

*

*[1] pgc .. has two or more licences with renewal 0 , 1

*[2] pgc .. has two or more licences with renewal 0 , 0

*[3] pgc .. has two or more licences with renewal 1 , 1

right now your query is getting pgcs for cases [1],[2]
so you have to alter your query logic a little, to only get [2]
$pgcs = PrivateGuard::with(['licences', 'state'])
        ->whereHas('licences', function($query){
          $query->whereDate('expiration_of_licence', '<', Carbon::today())
                ->where('renewal', 0);
        })
        ->whereDoesntHave('licences', function($query){
          $query->where('renewal', 1);
        })
        ->where('status', 1)
        ->get();


text:
Q: How to get BigQuery storage size for a single table I want to calculate table wise cost for Google Big Query Storage, But i don't know how to view size of storage for each table individually.

A: You can do this with command line tool
bq show ds_name.table_name
It will show some info aboout the table, including "Total Bytes". Reference here https://cloud.google.com/bigquery/bq-command-line-tool

A: Or from the GUI, you can use the metadata internal table __TABLES__  , for example this will give you the size in GB:
select
  sum(size_bytes)/pow(10,9) as size
from
  <your_dataset>.__TABLES__
where
  table_id = '<your_table>'

A: Just use the command-line tool. You will see the table with columns such as Last-Modified, Schema, Total Rows, Total Bytes and so forth.

*

*For Single Table

bq show dataset_name.table_name

*For All Tables

bq show dataset_name.*

A: There are a couple of ways to do this, but be aware the size of the table in bytes property is unavailable for tables that are actively receiving streaming inserts.
A. Using the BQ command line tool, and the JQ linux library to parse JSON.
bq --format=json show publicdata:samples.gsod | jq '.numBytes | tonumber'

This outpus:
17290009238

B. Using the REST api to do a Tables:get call
GET https://www.googleapis.com/bigquery/v2/projects/projectId/datasets/datasetId/tables/tableId

this returns a full JSON, that you can parse and get the numBytes.
{
    "kind": "bigquery#table",
    "description": "This dataset contains weather information collected by NOAA, such a…",
    "creationTime": "1335916040125",
    "tableReference": {
        "projectId": "publicdata",
        "tableId": "gsod",
        "datasetId": "samples"
    },
    "numRows": "114420316",
    "numBytes": "17290009238",
    "etag": "\"Gn3Hpo5WaKnpFuT457VBDNMgZBw/MTQxMzkzNzk4Nzg0Ng\"",
    "location": "US",
    "lastModifiedTime": "1413937987846",
    "type": "TABLE",
    "id": "publicdata:samples.gsod",
    "selfLink": "https://www.googleapis.com/bigquery/v2/projects/publicdata/datasets…",
    "schema": {
        "fields": [
            {
                "description": "The World Meteorological Organization (WMO) / DATSAV3 station numbe…",
                "type": "INTEGER",
                "name": "station_number",
                "mode": "REQUIRED"
            },
            {
                "description": "The Weather-Bureau-Army-Navy (WBAN) station number where the data w…",
                "type": "INTEGER",
                "name": "wban_number",
                "mode": "NULLABLE"
            },
            {
                "description": "The year the data was collected in",
                "type": "INTEGER",
                "name": "year",
                "mode": "REQUIRED"
            },
            {
                "description": "The month the data was collected in",
                "type": "INTEGER",
                "name": "month",
                "mode": "REQUIRED"
            },
            {
                "description": "The day the data was collected in.",
                "type": "INTEGER",
                "name": "day",
                "mode": "REQUIRED"
            },
            {
                "description": "The mean temperature of the day in degrees Fahrenheit, accurate to …",
                "type": "FLOAT",
                "name": "mean_temp",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_temp.",
                "type": "INTEGER",
                "name": "num_mean_temp_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The mean dew point of the day in degrees Fahrenheit, accurate to on…",
                "type": "FLOAT",
                "name": "mean_dew_point",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_dew_point.",
                "type": "INTEGER",
                "name": "num_mean_dew_point_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The mean sea level pressure of the day in millibars, accurate to on…",
                "type": "FLOAT",
                "name": "mean_sealevel_pressure",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_sealevel_pressure…",
                "type": "INTEGER",
                "name": "num_mean_sealevel_pressure_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The mean station pressure of the day in millibars, accurate to one …",
                "type": "FLOAT",
                "name": "mean_station_pressure",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_station_pressure.…",
                "type": "INTEGER",
                "name": "num_mean_station_pressure_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The mean visibility of the day in miles, accurate to one tenth of a…",
                "type": "FLOAT",
                "name": "mean_visibility",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_visibility.",
                "type": "INTEGER",
                "name": "num_mean_visibility_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The mean wind speed of the day in knots, accurate to one tenth of a…",
                "type": "FLOAT",
                "name": "mean_wind_speed",
                "mode": "NULLABLE"
            },
            {
                "description": "The number of observations used to calculate mean_wind_speed.",
                "type": "INTEGER",
                "name": "num_mean_wind_speed_samples",
                "mode": "NULLABLE"
            },
            {
                "description": "The maximum sustained wind speed reported on the day in knots, accu…",
                "type": "FLOAT",
                "name": "max_sustained_wind_speed",
                "mode": "NULLABLE"
            },
            {
                "description": "The maximum wind gust speed reported on the day in knots, accurate …",
                "type": "FLOAT",
                "name": "max_gust_wind_speed",
                "mode": "NULLABLE"
            },
            {
                "description": "The maximum temperature of the day in degrees Fahrenheit, accurate …",
                "type": "FLOAT",
                "name": "max_temperature",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates the source of max_temperature.",
                "type": "BOOLEAN",
                "name": "max_temperature_explicit",
                "mode": "NULLABLE"
            },
            {
                "description": "The minimum temperature of the day in degrees Fahrenheit, accurate …",
                "type": "FLOAT",
                "name": "min_temperature",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates the source of min_temperature.",
                "type": "BOOLEAN",
                "name": "min_temperature_explicit",
                "mode": "NULLABLE"
            },
            {
                "description": "The total precipitation of the day in inches, accurate to one hundr…",
                "type": "FLOAT",
                "name": "total_precipitation",
                "mode": "NULLABLE"
            },
            {
                "description": "The snow depth of the day in inches, accurate to one tenth of an in…",
                "type": "FLOAT",
                "name": "snow_depth",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if fog was reported on this day.",
                "type": "BOOLEAN",
                "name": "fog",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if rain was reported on this day.",
                "type": "BOOLEAN",
                "name": "rain",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if snow was reported on this day.",
                "type": "BOOLEAN",
                "name": "snow",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if hail was reported on this day.",
                "type": "BOOLEAN",
                "name": "hail",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if thunder was reported on this day.",
                "type": "BOOLEAN",
                "name": "thunder",
                "mode": "NULLABLE"
            },
            {
                "description": "Indicates if a tornado was reported on this day.",
                "type": "BOOLEAN",
                "name": "tornado",
                "mode": "NULLABLE"
            }
        ]
    }
}

C. There are metatables called __TABLES__ and __TABLES_SUMMARY__
You can run a query like:
SELECT size_bytes FROM <dataset>.__TABLES__ WHERE table_id='mytablename'

The __TABLES__ portion of that query may look unfamiliar. __TABLES_SUMMARY__ is a meta-table containing information about tables in a dataset. You can use this meta-table yourself. For example, the query SELECT * FROM publicdata:samples.__TABLES_SUMMARY__ will return metadata about the tables in the publicdata:samples dataset. You can also do SELECT * FROM publicdata:samples.__TABLES__
Available Fields:
The fields of the __TABLES_SUMMARY__ meta-table (that are all available in the TABLE_QUERY query) include:

*

*table_id: name of the table.

*creation_time: time, in milliseconds since 1/1/1970 UTC, that the table was created. This is the same as the creation_time field on the table.

*type: whether it is a view (2) or regular table (1).

The following fields are not available in TABLE_QUERY() since they are members of __TABLES__ but not __TABLES_SUMMARY__. They're kept here for historical interest and to partially document the __TABLES__ metatable:

*

*last_modified_time: time, in milliseconds since 1/1/1970 UTC, that the table was updated (either metadata or table contents). Note that if you use the tabledata.insertAll() to stream records to your table, this might be a few minutes out of date.

*row_count: number of rows in the table.

*size_bytes: total size in bytes of the table.


text:
Q: File's owner thinking it is superclass Something very strange is going on with my interface builder. So I created an NSWindowController subclass in Xcode, with the create XIB option enabled. I started coding, and I successfully connected to file's owner.
But, when I run my app, I get the error :
Failed to connect (workspaceControl) outlet from (NSWindowController) to (NSSegmentedControl): missing setter or instance variable
Failed to connect (workspaceField) outlet from (NSWindowController) to (NSTextField): missing setter or instance variable
Could not connect action, target class NSWindowController does not respond to -changeNumberOfWorkspaces:

I don't know why this error is showing up as I have my code set up right:

And the File's owner is set to the right class (AddController):

So why does it try to connect my views to NSWindowController instead of my subclass?
EDIT:
Where I actually use the AddController in code:
AppDelegate.h

AppDelegate.m

It's in appdelegate because it is a menubar app. (In case anyone was wondering)

A: Because the actual object that is instantiated in your running program is an NSWindowController, not an AddController.  You've shown us that AddController is properly declared, and you've shown us that your nib's File's Owner is set to AddController; that's great, and is why you don't get a compile-time warning or error about things being wired up incorrectly.  But you haven't shown us where the controller object actually gets instantiated; and examining that would presumably reveal that it hasn't been changed to AddController.  So at runtime you've got an NSWindowController, in violation of what you promised to IB would be the case; and so you get runtime errors.


text:
Q: Run a specific Chef recipe on a node after all the recipe on other nodes are completed I am automating HDP Hadoop Cluster install using Chef on a 3 Node Cluster. I have following recipes,

*

*Ambari_Server

*Ambari_Agent

*Metastore

*Blueprint.

I want to run blueprint recipe(4) on a specific node only after all the recipe(1,2,3) are completed in all the nodes(3 servers). Looking for best option to do it here using chef.
Thanks in advance.

A: I would be very happy to be wrong about this but to the best of my knowledge there is no way to do orchestration like this with chef. Off the top of my head you could possibly set an attribute at the end of the run of each other recipe then have a guard at the start of your dependent recipe that checks to see if they are all true before running.
i.e.
Ambari_Server
...
node.set['Amari_Server']['installed'] = true

Ambari_Agent
...
node.set['Amari_Agent']['installed'] = true

Metastore
...
node.set['Metastore']['installed'] = true

Blueprint
...
if node['Amari_Agent']['installed'] and node['Armari_Server']['installed'] and node['Metastore']['installed']
# Do whatever blueprint does
...

This is hacky and would potentially require multiple converges.


text:
Q: java.util.concurrent.CancellationException while saving Datastore Entities I'm trying to process a big excel file with more than 20K rows. Each row should be saved as an Entity in Datastore. First, I get the excel file in my servlet using the Blobstore and then I queue a task using the Task Queue service. This task, reads the excel file, convert each line in an Entity and store it. As I said before, Excel file could have more than 20K rows. After a while I get this exception:
com.xxx.xxx.ProcessBlob doPost: |POST|ProcessBlob|Exception:Task was cancelled.|Msg:Task was cancelled.|Stack:java.util.concurrent.CancellationException: Task was cancelled.

    at com.google.common.util.concurrent.AbstractFuture.cancellationExceptionWithCause(AbstractFuture.java:796)
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:475)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:381)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:85)
    at com.google.appengine.tools.development.TimedFuture.get(TimedFuture.java:42)
    at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:63)
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:88)
    at com.google.appengine.api.datastore.Batcher$ReorderingMultiFuture.get(Batcher.java:131)
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:88)
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:88)
    at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:88)
    at com.google.appengine.api.datastore.FutureHelper.getInternal(FutureHelper.java:75)
    at com.google.appengine.api.datastore.FutureHelper.quietGet(FutureHelper.java:35)
    at com.google.appengine.api.datastore.DatastoreServiceImpl.put(DatastoreServiceImpl.java:56)
    at com.xxx.xxx.xxx.createEntity(EntityService.java:87)
    at com.xxx.xxx.ProcessBlob.doPost(ProcessBlob.java:145)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:254)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:527)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)

Caused by: java.util.concurrent.CancellationException: Future.cancel() was called.
    at com.google.common.util.concurrent.AbstractFuture.cancel(AbstractFuture.java:514)
    at com.google.appengine.tools.development.TimedFuture.cancel(TimedFuture.java:85)
    at com.google.common.util.concurrent.ForwardingFuture.cancel(ForwardingFuture.java:48)
    at com.google.apphosting.runtime.ApiProxyImpl$AsyncApiFuture.cancel(ApiProxyImpl.java:553)
    at com.google.apphosting.runtime.RequestManager.cancelPendingAsyncFutures(RequestManager.java:626)
    at com.google.apphosting.runtime.RequestManager.sendDeadline(RequestManager.java:399)
    at com.google.apphosting.runtime.RequestManager.sendDeadline(RequestManager.java:357)
    at com.google.apphosting.runtime.CloneControllerImpl.sendDeadline(CloneControllerImpl.java:201)
    at com.google.apphosting.sandbox.ModelClonePb$CloneController$ServiceParameters$3.handleRequest(ModelClonePb.java:1166)
    at com.google.net.rpc3.impl.server.RpcServerInternalContext.runRpcInApplication(RpcServerInternalContext.java:558)
    at com.google.net.rpc3.impl.server.RpcServerChannel$1.run(RpcServerChannel.java:871)
    at com.google.tracing.LocalTraceSpanRunnable.run(LocalTraceSpanRunnable.java:56)
    at com.google.tracing.LocalTraceSpanBuilder.internalContinueSpan(LocalTraceSpanBuilder.java:626)
    at com.google.net.rpc3.impl.server.RpcServerChannel.startRpc(RpcServerChannel.java:837)
    at com.google.net.rpc3.impl.server.RpcServerChannel.receivedMessage(RpcServerChannel.java:594)
    at com.google.net.rpc3.impl.server.RpcServerChannel.access$2700(RpcServerChannel.java:164)
    at com.google.net.rpc3.impl.server.RpcServerChannel$TransportCallback.receivedMessage(RpcServerChannel.java:2365)
    at com.google.net.rpc3.impl.wire.RpcBaseTransport.receivedMessage(RpcBaseTransport.java:457)
    at com.google.apphosting.runtime.udrpc.UdrpcTransport$ServerAdapter.receivedMessage(UdrpcTransport.java:707)
    at com.google.apphosting.runtime.udrpc.UdrpcTransport.dispatchPacket(UdrpcTransport.java:384)
    at com.google.apphosting.runtime.udrpc.UdrpcTransport.readPackets(UdrpcTransport.java:283)
    at com.google.apphosting.runtime.udrpc.UdrpcTransport$1.run(UdrpcTransport.java:100)
    at com.google.net.eventmanager.AbstractFutureTask$Sync.innerRun(AbstractFutureTask.java:260)
    at com.google.net.eventmanager.AbstractFutureTask.run(AbstractFutureTask.java:121)
    at com.google.net.eventmanager.EventManagerImpl.runTask(EventManagerImpl.java:594)
    at com.google.net.eventmanager.EventManagerImpl.internalRunWorkerLoop(EventManagerImpl.java:1011)
    at com.google.net.eventmanager.EventManagerImpl.runWorkerLoop(EventManagerImpl.java:892)
    at com.google.net.eventmanager.WorkerThreadInfo.runWorkerLoop(WorkerThreadInfo.java:161)
    at com.google.net.eventmanager.EventManagerImpl$WorkerThread.run(EventManagerImpl.java:1879)

Another "weird" thing is that, seeing the logs for the requests, the parameters "ms" and "cpu_ms" are nearly the same when it drops that exception. Maybe I'm going above the AppEngine limits or timeout limits?
[02/Mar/2015:21:11:32 -0800] "POST /tasks/ProcessBlob HTTP/1.1" 200 0 "http://xxx.appspot.com/upload" "AppEngine-Google; (+http://code.google.com/appengine)" "xxx.appspot.com" ms=599492 cpu_ms=32522 queue_name=default task_name=xxx instance=xxx app_engine_release=1.9.18

[02/Mar/2015:23:21:55 -0800] "POST /tasks/ProcessBlob HTTP/1.1" 200 0 "http://xxx.appspot.com/upload" "AppEngine-Google; (+http://code.google.com/appengine)" "xxx.appspot.com" ms=599420 cpu_ms=33262 queue_name=default task_name=xxx instance=xxx app_engine_release=1.9.18

A: Looks like you faced Task Queue limits, 599949ms == 10 minutes. As per doc:

Tasks targeted at an automatic scaled module must finish execution
  within 10 minutes. If you have tasks that require more time or
  computing resources, they can be sent to manual or basic scaling
  modules, where they can run up to 24 hours.

See docs: https://cloud.google.com/appengine/docs/java/taskqueue/overview-push#task_deadlines
I suggest to split task into few smaller tasks, say one task per 1000 records, maybe smaller


text:
Q: Spring AOP or AspectJ way for selecting parents of a given class I have a pointcut definition in Spring AOP, which selects a certain set of classes, let say A. Is there a possibility to select the parent classes of all classes in A? I would prefer a solution in Spring AOP, but I would be also thankful for a predicate definition in AspectJ that would do the job.

A: You can easily select A and all sub classes for A with A+ , but as class A might have many root classes (parent for parent for parent .... Object) I think you can't create selector for this case. But you can create general pointcup and check inside aspect's advice call,  if it's one of parent class for A . BUT it will reduce performance a bit as you add aspect's call / check. I don't know your requirements , but if it's acceptable try this.


text:
Q: Filtering packets in pcap dump file I'm writing network analyzer and I need to filter packets saved in file, I have written some code to filter http packets but I'm not sure if it work as it should because when I use my code on a pcap dump the result is 5 packets but in wireshark writing http in filter gives me 2 packets and if I use:
tcpdump port http -r trace-1.pcap

it gives me 11 packets.
Well, 3 different results, that's a little confusing.
The filter and the packet processing in me code is:
...
if (pcap_compile(handle, &fcode, "tcp port 80", 1, netmask) < 0)
...
while ((packet = pcap_next(handle,&header))) {
    u_char *pkt_ptr = (u_char *)packet;

    //parse the first (ethernet) header, grabbing the type field
    int ether_type = ((int)(pkt_ptr[12]) << 8) | (int)pkt_ptr[13];
    int ether_offset = 0;

    if (ether_type == ETHER_TYPE_IP) // ethernet II
        ether_offset = 14;
    else if (ether_type == ETHER_TYPE_8021Q) // 802
        ether_offset = 18;
    else
        fprintf(stderr, "Unknown ethernet type, %04X, skipping...\n", ether_type);

    //parse the IP header
    pkt_ptr += ether_offset;  //skip past the Ethernet II header
    struct ip_header *ip_hdr = (struct ip_header *)pkt_ptr;
    int packet_length = ntohs(ip_hdr->tlen);

    printf("\n%d - packet length: %d, and the capture lenght: %d\n", cnt++,packet_length, header.caplen);

}

My question is why there are 3 different result when filtering the http? And/Or if I'm filtering it wrong then how can I do it right, also is there a way to filter http(or ssh, ftp, telnet ...) packets using something else than the port numbers?
Thanks

A: So I have figured it out. It took a little search and understanding but I did it.
Wireshark filter set to http filter packets that have set in tcp port 80 and also flags set to PSH, ACK. After realizing this, the tcpdump command parameters which result in the same numbers of packets was easy to write.
So now the wireshark and tcpdump gives the same results
What about my code? well I figured that I actually had an error in my question, the filter
if (pcap_compile(handle, &fcode, "tcp port 80", 1, netmask) < 0)

indeed gives 11 packets (src and dst port set to 80 no matter what tcp flags are)
Now to filter the desired packets is a question of good understanding the filter syntax
or setting to filter only port 80 (21,22, ...) and then in callback function or in while loop get the tcp header and from there get the flags and use mask to see if it is the correct packet (PSH, ACK, SYN ...) the flags number are for example here


text:
Q: How do I use `render_template` from Flask in Angular? What I'm trying to accomplish is different routes for the different Angular Material tabs. I've tried calling Flask right from the template, as shown below, and I seem to be unable to call render_template from Angular. I've also tried escaping the {{ [stuff] }} to {{ "{{ [stuff] }}" }} Is there a way to do this that I haven't found? The affected code is:
$stateProvider
.state("dashboard", { abtract: true, url:"/dash", templateUrl: {{ render_template('partials/tabs/Dashboard.html') }} })
.state("dashboard.commands", { url: "/dash/commands", templateUrl: {{ render_template('partials/tabs/Commands.html') }} })
.state("dashboard.support", { url: "/dash/support", templateUrl: {{ render_template('partials/tabs/Support.html') }} })

A: You can't call a server-side function inside your AngluarJs script. Servers' API only work through GET/POST request on given URLs. templateUrl should probably just be an url, such as 'partials/tabs/Support.html' and then the Flask server, when being asked for the page, renders the template.
That, or I missed your request, in which case more detail is welcome.

A: Have you tried using flask's url_for method? It automatically generates correct URLs according to corresponding view functions. So what you probably need is the following:
$stateProvider
.state("dashboard", { abtract: true, url:"/dash", templateUrl: {{ url_for('show_dashboard') }} })
.state("dashboard.commands", { url: "/dash/commands", templateUrl: {{ url_for('show_commands') }} })
.state("dashboard.support", { url: "/dash/support", templateUrl: {{ url_for('show_support') }} })

In your views (views.py or whatever) you define these functions like that:
@app.route('/partials/tabs/Dashboard.html')
def show_dashboard():
    render_template('partials/tabs/Dashboard.html')

@app.route('/partials/tabs/Commands.html')
    def show_commands():
        render_template('partials/tabs/Commands.html')

@app.route('/partials/tabs/Support.html')
    def show_support():
        render_template('partials/tabs/Support.html')

etc.