text:
Q: Strategy for making an iPhone Facebook 3.0 like home page What would be your approach to creating a home page like the new facebook 3.0 app has to offer? There's a grid of 3x3 UIButtons it appears if you look here:
alt text http://cache0.techcrunch.com/wp-content/uploads/2009/08/img_0318.png
If you wanted to replicate a similar user interface, would you programmatically have 9 individual buttons that you place on the screen through some kind of loop? If so what would the loop look like?
Would you make one image and hard-code coordinates into an array to see where the user is typing and take an appropriate action?

A: http://github.com/joehewitt/three20/tree/master
Here's the open-source library that Joe Hewitt created in the process of making the iPhone Facebook 3.0 app. This is where I would start.

A: Joel's pointer to Three20 is the best advice - this is the library that Joe opensourced in the course of creating the Facebook.app.
In terms of how you would generally do it, here's my 2 cents:
You'd have a UIScrollView (note that there can be multiple pages of buttons), each hosting a YourAppButtonGridView. Each YourAppButtonGridView would just have an array of the buttons, and would lay them out in a grid (write this in the layoutSubviews method). Bonus points for using UITabBarItem, which have a similar look and feel.

A: For my Application Capsuleer I have a similar "home" screen.
http://capsuleer.evesuite.com/images/screenshots/mainmenu.jpg http://capsuleer.evesuite.com/images/screenshots/mainmenu.jpg
In my code I built a struct that contained the properties for each button.
Things like:

*

*Icon image name

*Title

*Pulse state (I use a pulsing background image instead of the badge feature to show somthing has changed)

I then created an array of these structs and initialized them with the details about each button.
My view code then loops over this array and builds the buttons (it sets up all the default properties - background images, fonts, etc.).
I don't currently have multiple pages, but as I expand my application and add more features I'll be filling up the currently unused boxes.  When I get to a point where I have more then fit on one screen, I just switch the backing view from a UIView to a UIScrollView and add a paging control.
All of this is done in code.  I don't use interface builder at all.
It works quite well for my purposes and all I have to change when I add new areas is adjust some lines of code where I initialize my array of structs and the existing code does the rest.
Hope that helps.
chris.

A: I had to do something similar.  I created a custom button class and then did this loop
for (int i=1;i <= [OGViewControllers numberOfControllers];i++) {

aButton = [[OGMoreButtonView alloc] initWithIcon:[OGViewControllers iconForViewControllerWithIndex:i]
                                        andTitle:[OGViewControllers titleForViewControllerWithIndex:i]];
aButton.frame = CGRectMake(((i-1)%4) * 80.0, ((i-1)/4) * 65.0, 80.0, 65.0);
aButton.tag = i;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemSelected:) name:@"AMoreButtonWasTouched" object:aButton];
[self.view addSubview:aButton];
[aButton release];

}
If you want the scroll affect with the page indicator throw it all in a scroll view that is 640 wide and turn paging on for the scroll view and set the delegate to self then do something like this
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int oldPage = [pageControl currentPage];
[pageControl setCurrentPage:(int)(([scrollView contentOffset].x/320)+0.5)];

if (oldPage != [pageControl currentPage]) [[NSNotificationCenter defaultCenter] postNotificationName:@"OGSwipeViewItemChanged"  object:nil];

}

A: I'm not familiar with the app but from looking at the image i'd say one approach would be to use Interface Builder to lay out 9 custom UIButtons (with your own UIImages in them) in the root view of your Navication Controller and then wire up the IBAction (touch up inside) of each of those to push a new view controller on the stack. Again, I don't use facebook so can't say for sure if that's how it's been wired together.

A: Start by using interface builder to get everything working. You can get most of the way to it working by just dragging and dropping stuff out of interface builder.
Then later on you can enhance user interface using other drawing techniques.
(NB: This answer was more relevant until the original poster changed their question)


text:
Q: Why does this recursive flatten array function gives me wrong result? Javascript I'm working on flatten array function. It takes an input like this
const input = [
  {
    "value": "value0",
    "children": []
  },
  {
    "value": "value1",
    "children": [
      {
        "value": "value2",
        "children": [
          {
            "value": "value3",
            "children": []
          }
        ]
      },
      {
        "value": "value4",
        "children": []
      }
    ]
  },
  {
    "value": "value5",
    "children": []
  },
  {
    "value": "value6",
    "children": []
  }
];

and return an array
[
  {"value":"value0"},
  {"value":"value1"},
  {"value":"value2"},
  {"value":"value3"},
  {"value":"value4"},
  {"value":"value5"},
  {"value":"value6"}
]

I have solved this problem. Here is my former wrong code and I was trying to debug it
function flatArray(input) {
  if(input.length === 0) return [];
  let res = [];
  input.forEach(i => {
    for(let key of Object.keys(i)) {
      if(key === 'value') {
        res.push({[key]: i[key]});
      } else {
        const arr = flatArray(i[key]);
        res.concat(arr);
        console.log(res);
      }
    }
  });
  return res;
}

PS: It's wrong because the misuse of concat
The output is weird. I got

I'm wondering why the first three are type of object? And why, like the first output, can get an array with 4 elements instead of getting an array with only {value: value0}?
I guess it has something to do with closures but I can't explain this thing. Can anyone help me?

A: Well, it looks like you answered yourself:

PS: It's wrong because the misuse of concat

The concat method won't change the existing arrays, but return a new one. So you have to assign its output to you res variable:
function flatArray(input) {
  if(input.length === 0) return [];

  let res = [];

  input.forEach(i => {
    for(let key of Object.keys(i)) {
      if(key === 'value') {
        res.push({[key]: i[key]});
      }
      else {
        const arr = flatArray(i[key]);
        res =  res.concat(arr);
      }
    }
  });
  return res;
}

A: If the order of objects in the output doesn't matter, I would structure this differently. Put the top array elements into input and traverse each object in input: for each object, remove the array valued-keys and concat them to input and push the non-array-valued object to res. Continue iteration until input is empty. You could output the same ordering by inserting each child list to the head of input for depth-first traversal. Sorry I didn't actually answer how to fix the recursive one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a transparent wrapper to terminal application? Wrapper should handle special control characters and do something but otherwise not interfere with the actual application. (trying to build a tmux like app)
So far I have the below modifying example in doc: https://docs.python.org/3/library/pty.html#example
import pty
import os

def handle_special_cmd(data):
    # TODO
    raise NotImplementedError

def inread(fd):
    data = os.read(fd, 1024)
    if b'\x02' in data: # ctrl B
        return handle_special_cmd(data)
    return data

def main():
    cmd="vim"
    pty.spawn(cmd, stdin_read=inread)

if __name__=='__main__':
    main()

The above code works but the vim opened does not cover the entire terminal window. It starts vim with reduced rows and columns
If I just type vim from the shell it works fine:

Why does this occur and how to fix it? My goal is not just fix the rows and columns but the wrapper should be truely transparent except trap the special ctrl character and do some stuff. whatever tty / colors and other settings the current shell has should be passed on to the actual executable. It should work as if I typed vim. (Linux specific solution is fine. Need not work in all posix. If it needs a c extension is also fine).

A: The window size is, uniquely, a property of the PTY itself. You can get and set it using the TIOCGWINSZ and TIOCSWINSZ ioctls:
import sys, fcntl, termios, struct

buf = bytearray(4)
fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, buf)
(h, w) = struct.unpack("HH", buf)
print("Terminal is {w} x {h}".format(w=w, h=h))

[...]

fcntl.ioctl(child_pty.fileno(), termios.TIOCSWINSZ, struct.pack("HH", h, w))


text:
Q: Swift: How to increment to get images for Collections Using Swift
I have a collections app to show over hundreds of items. In cellForItemAt I'm trying to show images so it matches with the name. For example, my images are called 0_0, 0_1, 0_2 to 0_723, etc. This is the code I have so far but it's not working.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Use arrayCount to for selecting Image | initalized as global as -1
    arrayCounter = arrayCounter + 1
    print(arrayCounter)

    // Set Image
    cell.imageCell.image = UIImage(named: "\(checkGroupChoice)_\(arrayCounter)")

    // Rounded Corners for Image Cell
    cell.imageCell.layer.cornerRadius = 10
    cell.imageCell.layer.masksToBounds = true

    return cell
}

I thought by doing this since it loops for every cell that I can just increment but what i didn't know is that it only increments to what the screen sees and once you scroll the numbers completely change and images stop showing.
So how can I increment arrayCount to the max of Items.count so I can use my images to the cells it belongs too.

A: The counter does not work, as the cellForRow function is called multiple times, not just once per cell.
What you should use instead is the indexpath of the cell. Specifically the indexpath.item. If you have multiple sections you have to correct it by the number of items in the previous sections.


text:
Q: Is it possible to add a privilege to the Standard User Token created for an admin user by Windows? This questions is a followup to
Why is SeCreateSymbolicLinkPrivilege ignored on Windows 8?
Given:

*

*The user is in the Administrators group

*Turning off UAC is not an option for me.

*Running elevated is not an option.

Question: Is it possible to add the SeCreateSymbolicLinkPrivilege to the Standard User Token created by Windows for an admin user?

Appendix
Non elevated admin user:
C:\dayforce\SharpTop>whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                          State
============================= ==================================== ========
SeShutdownPrivilege           Shut down the system                 Disabled
SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
SeUndockPrivilege             Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set       Disabled
SeTimeZonePrivilege           Change the time zone                 Disabled

C:\dayforce\SharpTop>

A regular user:
C:\Windows\system32>whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                          State
============================= ==================================== ========
SeShutdownPrivilege           Shut down the system                 Disabled
SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
SeUndockPrivilege             Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set       Disabled
SeTimeZonePrivilege           Change the time zone                 Disabled
SeCreateSymbolicLinkPrivilege Create symbolic links                Disabled

C:\Windows\system32>

Notice a regular user has the SeCreateSymbolicLinkPrivilege privilege, because I have enabled it in the Security Policy. But the admin user is screwed, because doing so does not affect its Standard User Token!

A: (this is a nonanswer to the actually-asked question, but it is an attempt at an answer for what I perceive to be the actual goal)
I feel your pain -- I've been looking for a way to permit an admin user running nonelevated to create Symbolic Links, without success ...

*

*I've investigated altering the process token (of "explorer" perhaps)
to add the SeCreateSymbolicLinkPrivilege privilege, but it appears
that there is no way to alter the privilege set of an existing token.
Even if your patch process runs as SYSTEM and/or has the
SeTcbPrivilege privilege.

*I've investigated using CreateRestrictedToken to create your "own"
nonelevated process, but with the SeCreateSymbolicLinkPrivilege
privilege left enabled.  But all anecdotes I've read about
CreateRestrictedToken suggests that the resulting token cannot be
made sufficiently similar to an "authentic" nonelevated token.  There
were insurmountable issues with the integrity level, or with the elevated flag
associated with the token.

*No matter what users you assign to the create-symlink user right in
security policy manager, if your process runs nonelevated (from a
user with admin), the SeCreateSymbolicLinkPrivilege privilege gets
removed.  This happens even if the only user added is "Everyone".
Microsoft really fouled us up on this one, there appears to be no good workaround.  There is a possibly hackish solution though ...
Now for the hackish solution - during logon of the user, start a background program (elevated) which will create symlinks on behalf of other processes.  This will need to use some sort of IPC, perhaps named pipes, to receive create-symlink-requests from the client process.  It's ugly, and probably slow, but other than running Elevated (or disabling UAC), or removing the user from the Administrators group, I don't see any other way.


text:
Q: Transform a code tokens list into valid string code I have written code to transform Python code into a list to compute BLEU score:
import re

def tokenize_for_bleu_eval(code):
    code = re.sub(r'([^A-Za-z0-9_])', r' \1 ', code)
    code = re.sub(r'([a-z])([A-Z])', r'\1 \2', code)
    code = re.sub(r'\s+', ' ', code)
    code = code.replace('"', '`')
    code = code.replace('\'', '`')
    tokens = [t for t in code.split(' ') if t]

    return tokens

Thanks to this snippet my code struct.unpack('h', pS[0:2]) is parsed properly into the list ['struct', '.', 'unpack', '(', 'h', ',', 'p', 'S', '[', '0', ':', '2', ']', ')'].
Initially, I thought I need simply to use the ' '.join(list_of_tokens) but it kills my variable names like this struct . unpack ('h' , p S [ 0 : 2 ] ) and my code is not executable.
I tried to use Regex to stick some variable names but I can't succeed to reverse my function tokenize_for_bleu_eval to find executable code at the end. Is someone get an idea, perhaps without regex which seems to be too complicated here?
EDIT: We can't just remove all spaces between element of the list because there are examples like items = [item for item in container if item.attribute == value] where the result of the backtranslation without space would be itemforiteminaifitem[0]==1 which is not valid.

A: I am trying to merge the tokens using this script
import re

def tokenize_for_bleu_eval(code):
    code = re.sub(r'([^A-Za-z0-9_])', r' \1 ', code)
    code = re.sub(r'([a-z])([A-Z])', r'\1 \2', code)
    code = re.sub(r'\s+', ' ', code)
    code = code.replace('"', '`')
    code = code.replace('\'', '`')
    tokens = [t for t in code.split(' ') if t]

    return tokens

def merge_tokens(tokens):
    code = ''.join(tokens)
    code = code.replace('`', "'")
    code = code.replace(',', ", ")

    return code

tokenize = tokenize_for_bleu_eval("struct.unpack('h', pS[0:2])")
print(tokenize)  # ['struct', '.', 'unpack', '(', '`', 'h', '`', ',', 'p', 'S', '[', '0', ':', '2', ']', ')']
merge_result = merge_tokens(tokenize)
print(merge_result)  # struct.unpack('h', pS[0:2])

Edit:
I found this interesting idea to tokenize and merge.
import re

def tokenize_for_bleu_eval(code):
    tokens_list = []
    codes = code.split(' ')
    for i in range(len(codes)):
        code = codes[i]
        code = re.sub(r'([^A-Za-z0-9_])', r' \1 ', code)
        code = re.sub(r'([a-z])([A-Z])', r'\1 \2', code)
        code = re.sub(r'\s+', ' ', code)
        code = code.replace('"', '`')
        code = code.replace('\'', '`')
        tokens = [t for t in code.split(' ') if t]
        tokens_list.append(tokens)
        if i != len(codes) -1:
            tokens_list.append([' '])

    flatten_list = []

    for tokens in tokens_list:
        for token in tokens:
            flatten_list.append(token)

    return flatten_list

def merge_tokens(flatten_list):
    code = ''.join(flatten_list)
    code = code.replace('`', "'")

    return code

test1 ="struct.unpack('h', pS[0:2])"
test2 = "items = [item for item in container if item.attribute == value]"
tokenize = tokenize_for_bleu_eval(test1)
print(tokenize)  # ['struct', '.', 'unpack', '(', '`', 'h', '`', ',', ' ', 'p', 'S', '[', '0', ':', '2', ']', ')']
merge_result = merge_tokens(tokenize)
print(merge_result)  # struct.unpack('h', pS[0:2])

tokenize = tokenize_for_bleu_eval(test2)
print(tokenize)  # ['items', ' ', '=', ' ', '[', 'item', ' ', 'for', ' ', 'item', ' ', 'in', ' ', 'container', ' ', 'if', ' ', 'item', '.', 'attribute', ' ', '=', '=', ' ', 'value', ']']
merge_result = merge_tokens(tokenize)
print(merge_result)  # items = [item for item in container if item.attribute == value]

This script will also remember each space from the input


text:
Q: Why doesn't my Bootstrap 3 row fill the parent width? I'm trying to use Bootstrap 3 to make a grid-based template for a modal (which I'm also using Bootstrap for). The modal appears, and all the content is there ... but the styling is off. It looks like the row classes don't fill their parent containers, even though there's no styling that should make that happen. Here's a screenshot - you can see that neither the row in the header nor the row in the body take the width of their parent. I've tried poking around other SO posts for information, but I can't seem to find anything on why a row wouldn't fill its parent width.
Update:
Here's a JSFiddle. It looks like it actually works on JSFiddle ... which means it's not a problem with the immediate template, so I'm looking into other possible causes. Thanks for the tip, calvin!
HTML

                Bombay Teen Challenge

                    <address>
                        1 Chium Village, Ambedkar Road

                        Bandra West

                        Mumbai 400052
                    </address>

                    e:  kkdevaraj@bombayteenchallenge.org

                    p:  +91 22 2604 2242

                         Prevention, Education, Teen

                         BombayTeenChallenge

                         @BombayTC

                                People:

                                Dr. Rama R. Rao

                                Monte Hackney

                                Partners:

                                None Available

LESS
.prevention-label {
  width: 24px;
  height: 24px;
  line-height: 24px;
  display: inline-block;
  background-color: #4ECDC4;
}

.ht-modal-header {
  a {
    &:hover, &:focus {
      color: white;
    }
    color: white;
  }

  color: white;
  background: linear-gradient(@ht-teal, darken(@ht-teal, 5%));
  background: -webkit-gradient(@ht-teal, darken(@ht-teal, 5%));
  background: -o-linear-gradient(@ht-teal, darken(@ht-teal, 5%));
  background: -moz-linear-gradient(@ht-teal, darken(@ht-teal, 5%));
}

A: If you nest rows in columns you must understand that inside a .col-lg-6 .row the whole thing starts new (at 100%) and for you you to fill it have to use .col-lg-12 inside of it.
This snippet should work for you

                People:

                Dr. Rama R. Rao

                Monte Hackney

                Partners:

                None Available


text:
Q: Replace json value by jsonpath we have such a json string:
{
"key1": {
    "key2": {
        "key6": true
    },
    "key6": {
        "key3": [
            {
                "key4": "1",
                "key5": "1"
            },
            {
                "key4": "1",
                "key5": "1"
            }
        ]
    }

},
"from": 0
}

we want to use below code to replace latter key6's value:
DocumentContext dContext = JsonPath.using(configuration).parse(objectString);
dContext.set("$.key6"+,"false"));

But as key6 has been shown in the jsonstring twice, we got the wrong value replaced. The above json structure is just one example, the json path for "key6" is quite different in different json. We couldn't write the exact jsonpath for this kind of replacement.
How can we just replace the value of "key6" which has no child by java?
Thanks a lot.

A: Your only solution is to go to precise key, in your case, something like this:
dContext.set("$.key1.key2.key6"+,"false"));


text:
Q: How to change view's size from 4 side in Android? Is it possible to resize by pulling the matrix on the 4 side of the view? I can resize from a single point to a ratio like this.

The example above works as follows:
protected boolean onTouchDown(@NonNull MotionEvent event) {
  oldDistance = (float) Math.sqrt((midPoint.x-event.getX()) * (midPoint.x-event.getX()) + (midPoint.y-event.getY()) * (midPoint.y-event.getY()));
...
}

float newDistance = (float) Math.sqrt((midPoint.x-event.getX()) * (midPoint.x-event.getX()) + (midPoint.y-event.getY()) * (midPoint.y-event.getY()));
moveMatrix.set(downMatrix);
moveMatrix.postScale(newDistance / oldDistance, newDistance / oldDistance, midPoint.x,
        midPoint.y);
handlingSticker.setMatrix(moveMatrix);

But, for example, how can I make the process of expanding on the right side like below pictures with matrix?

A: You can try following. The idea is, if you have only horizontal or only vertical scale, then you must provide actual scale for desired axis and 1 for the other axis. Checking if the scale is horizontal or vertical is a bit tricky, you can check either:
1 The first touch was near the "vertical" border of your view. Than scroll is horizontal (x axis). Otherwise its vertical (y axis).
2 If you have buttons to drag from as in the screenshot, this makes things even easier: you just need to remember which buttons the scale was initiated with.
protected boolean onTouchDown(@NonNull MotionEvent event) {
  oldDistance = (float) Math.sqrt((midPoint.x-event.getX()) * (midPoint.x-event.getX()) + (midPoint.y-event.getY()) * (midPoint.y-event.getY()));
...
}

boolean isHorizonalScale = ... // Check if the drag has been started on the "vertical" side. If no, the scale is vertical.

moveMatrix.set(downMatrix);

if (isHorizonalScale) {
    float newDistance = (float) Math.abs(midPoint.x-event.getX());
    moveMatrix.postScale(newDistance / oldDistance, 1, midPoint.x, midPoint.y);
} else if (isHorizonalScale) {
    float newDistance = (float) Math.abs(midPoint.y-event.getY());
    moveMatrix.postScale(1, newDistance / oldDistance, midPoint.x, midPoint.y);
}
handlingSticker.setMatrix(moveMatrix);

A: moveMatrix.postScale(newDistance / oldDistance, 1, midPoint.x, midPoint.y);  change to
moveMatrix.preScale(newDistance / oldDistance, 1);


text:
Q: how to make responsive multi dimension grid same height in two colum I have layout similar to one show in below image, If images are same height then layout is fine but the moment image is of different dimension design breaks.

Design has two main columns with 50% width, First blog items takes 50% space and other 4 blog items use other 50% space in which i show other items.
can i make it same height so that all images fit without breaking design.
If i try one thing other thing break initially i had tried this using flex box both that had some issues so i moved to grids and now i face different issue her.  I have no control over image as they will be of different dimension
Code pen example https://codepen.io/KGuide/pen/xxPWxKj

Column 1

Some text..

Column 2

Some text..

Column 3

Some text..

Column 4

Some text..

Column 5

Some text..

A: Do you want something like this?

.column1 {
  grid-area: column1;
}

.column2 {
  grid-area: column2;
}

.column3 {
  grid-area: column3;
}

.column4 {
  grid-area: column4;
}

.column5 {
  grid-area: column5;
}

.row {
  width: 100%;
  height: 100% !important;
  display: grid;
  grid-template-areas: 'column1 column1 column2 column3' 'column1 column1 column2 column3'
  'column1 column1 column4 column5'
  'auto auto column4 column5';
}

.row div {
  text-align: center;
}

img {
  width: 100%;
}

Column 1

Some text..

Column 2

Some text..

Column 3

Some text..

Column 4

Some text..

Column 5

Some text..


text:
Q: Full GC in G1 GC Jstat tool gives stats regarding young gc time and full gc time along with other information. As far as I know, Full GC in G1 GC consists of following phases :
1) Concurrent Marking (not Stop the world)
2) Remarking (Stop the world)
3) Reclaimation of empty regions (Stop the world)
4) Reclaimation of partially empty old regions through mixed gc (Happens over the time)
Now, I want to know jstat full gc time measures time for which of the phases ?
If Phase 1 and 2 are not considered for full gc time measurement then, why is full gc time more compared to young gc? Because, just phase 2 and 3 themselves seem to be lightweight phases.
Also, mixed gc happens over next few young gc. So, young gc time would increase for next few young gc after a full gc. Am I right in assuming this?
I have just started learning about working of G1 GC


text:
Q: Using .NET Microsoft.Office.Interop to convert .DOC to XHTML I'm trying to convert the contents of a Microsoft Word (.doc) file into nicely formatted XHTML using C#, .NET 2.0 and the Microsoft.Office.Interop.Word namespace. This is just a little exe that I'm building, which I can hopefully integrate into our automated build process. The reason I'm doing this is because Word's built in "Save as Web Page" does a horrible job of the HTML generation. I'm using Microsoft Word 2003.
I've looked around for resources in this respect but beyond the MSDN reference (http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word%28office.11%29.aspx) and a few tutorials on how to create word docs (not read them in a manner that allows creation of another format) I'm coming up blank.
So far, I have a little app that will loop through all the paragraphs in the opened Word document and wrap their text in HTML paragraph tags and output this to an HTML file. It would appear that, in Word, everything is treated as a paragraph, so I'm finding that there's no way to determine if the current paragraph is a list, table, header, etc. There are separate collections for Tables, Lists, etc, but there doesn't seem to be a way (that I've found) to derive an order from the contents of the object model that the Microsoft.Office.Interop.Word namespace provides.
Firstly, is anyone aware of any good resources for using the Microsoft.Office.Interop.Word namespace to do what I'm trying to achieve?
Secondly, I am trying to reinvent the wheel here (foregoing my previous explanation as to why I'm not using the "Save as Webpage" feature) or barking up the wrong tree in terms of my choice of approach/technology/code library?
I know that MS Office 2007 and beyond have increasingly better support for the Office Open XML format (http://en.wikipedia.org/wiki/Office_Open_XML), so assuming thats any good an XML transform may be possible.
Also, there are apparently some good products out there for doing the type of thing I'm describing but there doesn't appear to be any good open source alternatives.

A: I hate Interop.  Interop feels like a cludge because it is a cludge.
Can you open the document in Word 2007, "Save As" -> "Other Formats", pick one of the XML formats, and process the resulting XML with System.XML?  Transforming from one XML document to another XML document is going to be a lot easier than mucking about with Interop.


text:
Q: Strange Video Display Issue w/SimpleModal in Firefox I have a very strange issue that ONLY happens in FireFox 4 (works fine in IE and FF3.6). When a user clicks a video link, it opens up a jquery/simplemodal box. The audio portion of the file begins just fine - however, the video portion does not display until the user makes some form of mouse movement/click (or hits the Alt Key). Can anyone explain what may cause this.
TIA for any help

A: I just found the answer - It is actually a KNOWN BUG w/FF4
https://bugzilla.mozilla.org/show_bug.cgi?id=651999


text:
Q: What should be the polarities of the op amp input terminals such that the system is stable?

simulate this circuit – Schematic created using CircuitLab
Ignore the - and + signs on the opamp (I couldn't erase it using the schematic), is it possible to determine the polarity of the op amp input terminals, using just the information of the resistors in this circuit, such that the System is stable?
By stability I am referring to a state where it doesn't oscillate.

A: At first, I assume using the term "stable" you intend to use such a circuit for linear amplifying purposes, correct? I further assume that the left nodes of R1 and R3 will be connected to common ground (as defined by the not shown double voltage supply) or to a voltage source.
Then, if the used opamp is universal-compensated (most opamps are) the circuit will operate in the linear region if the negative feedback overrides the positive feedback. For the resistor values as shown in your diagram this will be the case for the shown polarity of the opamps input terminals. The negative feedback factor is k(-)=0.5 and the positive feedback factor is k(+)=100/300=0.333.
There are three different alternative operational modes: Non-inverting gain (R1 grounded), inverting gain (R3 grounded), differential gain (R1 and R3 connected to voltage sources).


text:
Q: Stability of a matrix product Motivation: I am working on a research problem and have been stuck for a while. I hope someone can help, as it requires only linear algebra. :)
Let $H$ be a real, invertible and positive semi-definite matrix, in the sense that its symmetric part $S$ is positive semi-definite. Consider the matrix
$$ G = (I+\alpha H_d)H $$
for some $\alpha > 0$, where $H_d$ is the diagonal part of $H$ (obtained by setting all off-diagonal entries of $H$ to $0$). Prove or disprove that $G$ is stable for small enough $\alpha$, in the sense that its eigenvalues have non-negative real part.
I can neither prove this nor find a counter-example. It is definitely true for $2 \times 2$ matrices, and I think also for $3 \times 3$. In general, there are two special cases worth mentioning:

*

*If $H$ has no pure imaginary eigenvalues then its eigenvalues have positive real part, and so does $G$ for small enough $\alpha$. This holds in particular if $H$ is symmetric.

*If $H$ is antisymmetric then $H_d = 0$ so $G = H$, which has pure imaginary eigenvalues, with zero real part as required.

Note that $H$ is always stable and $(I+\alpha H_d)$ is always positive definite. Ideally I would have liked to use Sylvester's Law of Inertia to conclude, as suggested here, but neither $H$ nor $G$ are symmetric. I also tried some other sufficient conditions for stability like diagonal dominance, but this does not hold in general.

A: It's true for all $\alpha \ge 0$.  $G$ has the same eigenvalues as $(1+\alpha H_d)^{1/2} H (1+\alpha H_d)^{1/2}$, which is positive semidefinite.


text:
Q: C++ template constructor in .cpp file TestCase.h
class TestCase {
  public:
    template<size_t N> TestCase(int (&arr)[N]) {
      // Constructor code here, I iterate over the array of values.
    }
    // etc
  private:
    int var1;
    // etc
}

This is my header file for a class. The class takes in an array of any size using a template. This works great but I hate having the constructor code in the .h file. How can I move the constructor code into the .cpp file with the rest of the member functions? I can't use vectors or anything. Thanks :)


text:
Q: C++ Inheritance Issue, Errors LNK1120 & LNK2019 I'm trying to get a class working to represent complex numbers. I'm trying to derive everything from a base class, Number, and I make two inherited classes from it, Real and Complex. I'm trying to put virtual functions in the Number base class so that I can implement them in the derived classes.
The problem is, when I go to build an instance of a class, I get the following error messages:
Error   2   error LNK1120: 1 unresolved externals
Error   1   error LNK2019: unresolved external symbol "public: __thiscall Real::~Real(void)" (??1Real@@QAE@XZ) referenced in function _wmain
I've checked and I've seen that errors 1120 & 2019 can appear when your project linker subsystem is set to Windows instead of Console, but I've already made it as a Console Application. The errors above appear below when I try to create an instance of class Real. Thanks for any help.
    #include "stdafx.h"
    #include <iostream>
    #include <math.h>

    #define PI 3.14159

class Number
{
public:
    virtual void Add(double value)      { std::cout << "Add Numbers" << std::endl; }
    virtual void Sub(double value)      { std::cout << "Subtract Numbers" << std::endl; }
    virtual void Mult(double value)     { std::cout << "Multiply Numbers" << std::endl; }
    virtual void Div(double value)      { std::cout << "Divide Numbers" << std::endl; }
    virtual void SetVal(double value)   { std::cout << "Set Number Value" << std::endl; }
    virtual void PrintVal()             { std::cout << "Print Number Value" << std::endl; }
};

class Real : public Number
{
private:
    double real;

public:

    Real(double value)
    {
        Real::real = value;
    }

    ~Real();

     void Add(double value)
    {
        real += value;
    }

     void Sub(double value)
    {
        real -= value;
    }

     void Mult(double value)
    {
        real *= value;
    }

     void Div(double value)
    {
        real /= value;
    }

     void SetVal(double value)
    {
        real = value;
    }

     void PrintVal()
    {
        std::cout << "Number = " << real << std::endl;
    }
};

class Complex : public Number
{
private:
    double real;
    double complex;

    double FindAngle(double real, double complex)
    {
        if (real == 0 && complex > 0)
            return 0;

        else if (real == 0 && complex < 0)
            return PI;

        else if (real > 0 && complex == 0)
            return PI / 2;

        else if (real < 0 && complex == 0)
            return 3 * PI / 2;

        else
            return atan2(complex, real);
    }

public:

    Complex(double val1, double val2)
    {
        real = val1;
        complex = val2;
    }

    ~Complex();

     void Add(double val1, double val2)
    {
        real += val1;
        complex += val2;
    }
     void Sub(double val1, double val2)
    {
        real -= val1;
        complex -= val2;
    }

     void Mult(double val1, double val2)
    {
        double abs1, abs2, angle1, angle2;
        double absFinal, angleFinal;

        abs1 = sqrt(real*real + complex*complex);
        abs2 = sqrt(val1*val1 + val2 + val2);
        angle1 = FindAngle(complex, real);
        angle2 = FindAngle(val2, val1);

        absFinal = abs1 * abs2;
        angleFinal = angle1 + angle2;

        real = absFinal * cos(angleFinal);
        complex = absFinal * sin(angleFinal);

    }

     void Div(double val1, double val2)
    {
        double abs1, abs2, angle1, angle2;
        double absFinal, angleFinal;

        abs1 = sqrt(real*real + complex*complex);
        abs2 = sqrt(val1*val1 + val2 + val2);
        angle1 = FindAngle(complex, real);
        angle2 = FindAngle(val2, val1);

        absFinal = abs1 / abs2;
        angleFinal = angle1 - angle2;

        real = absFinal * cos(angleFinal);
        complex = absFinal * sin(angleFinal);
    }

     void SetVal(double val1, double val2)
    {
        real = val1;
        complex = val2;
    }

     void PrintVal()
    {
        std::cout << "Number = " << real << " + j" << complex << std::endl;
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    Real r = Real(3);
    system("PAUSE");
    return 0;
}

A: Your Real::~Real() is undefined, it's declared, but it isn't defined.


text:
Q: How to handle if @PatchMapping request is not valid I am using PATCH for one of my REST api. PATCH expects an existing entry for which the request is being made. How to handle the scenario if the data for which the request is being made does not exist?
I think an exception should be thrown if not existing data found. Since it's a PATCH request existing data is mandatory.
can you suggest which exception should be thrown  or any other idea?

A: This article specifies that a 404 (Resource Not Found) would be the appropriate response code.


text:
Q: Failing to install scikit-learn in windows 8 - too complicated error I have installed Python 3.9 and the newest version of pip suggested by the terminal.
I also installed NumPy, SciPy, Seaborn, MatPlotLib (and JupyterLab, Voila although those are irrelevant).
When I go to the path where the scripts of Python are (using cmd.exe) and try the command
pip install -U scikit-learn
I get an extremelly long error.
I also tried:
!pip install scikit-learn
from a Jupyter notebook, but I get the same result.
Using cached scikit-learn-0.23.2.tar.gz (7.2 MB)
 Installing build dependencies: started
 Installing build dependencies: finished with status 'error'

The error I get is the following:
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\στραβούλα\appdata\local\programs\python\python39\python.exe' 'c:\users\στραβούλα\appdata\local\programs\python\python39\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.28.5' 'numpy==1.13.3; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"' and platform_python_implementation == '"'"'CPython'"'"'' 'numpy==1.14.0; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"' and platform_python_implementation != '"'"'CPython'"'"'' 'numpy==1.14.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.6'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'scipy>=0.19.1'
       cwd: None
  Complete output (334 lines):
  Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX" and platform_python_implementation == "CPython"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX" and platform_python_implementation != "CPython"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.7" and platform_system != "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.6" and platform_system == "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version == "3.7" and platform_system == "AIX"' don't match your environment
  Ignoring numpy: markers 'python_version >= "3.8" and platform_system == "AIX"' don't match your environment
  Collecting setuptools
    Using cached setuptools-50.3.2-py3-none-any.whl (785 kB)
  Collecting wheel
    Using cached wheel-0.35.1-py2.py3-none-any.whl (33 kB)
  Collecting Cython>=0.28.5
    Using cached Cython-0.29.21-py2.py3-none-any.whl (974 kB)
  Collecting numpy==1.17.3
    Using cached numpy-1.17.3.zip (6.4 MB)
  Collecting scipy>=0.19.1
    Using cached scipy-1.5.4-cp39-cp39-win_amd64.whl (31.4 MB)
  Using legacy 'setup.py install' for numpy, since package 'wheel' is not installed.
  Installing collected packages: setuptools, wheel, Cython, numpy, scipy
      Running setup.py install for numpy: started
      Running setup.py install for numpy: finished with status 'error'
      ERROR: Command errored out with exit status 1:
       command: 'c:\users\στραβούλα\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Στραβούλα\\AppData\\Local\\Temp\\pip-install-1al5oc45\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Στραβούλα\\AppData\\Local\\Temp\\pip-install-1al5oc45\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-record-1qm0ngw_\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay' --compile --install-headers 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay\Include\numpy'
           cwd: C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\
      Complete output (308 lines):
      Running from numpy source directory.

      Note: if you need reliable uninstall behavior, then install
      with pip instead of using `setup.py install`:

        - `pip install .`       (from a git repo or downloaded source
                                 release)
        - `pip install numpy`   (last NumPy release on PyPi)

      blas_opt_info:
      blas_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      blis_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blis not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      Found executable C:\Perl64\site\bin\g77.exe
      gnu: no Fortran 90 compiler found
      gnu: no Fortran 90 compiler found
      customize IntelVisualFCompiler
      Could not locate executable ifort
      Could not locate executable ifl
      customize AbsoftFCompiler
      Could not locate executable f90
      Could not locate executable f77
      customize CompaqVisualFCompiler
      Could not locate executable DF
      customize IntelItaniumVisualFCompiler
      Could not locate executable efl
      customize Gnu95FCompiler
      Found executable C:\Strawberry\c\bin\gfortran.exe
      Using built-in specs.
      COLLECT_GCC=C:\Strawberry\c\bin\gfortran.exe
      COLLECT_LTO_WRAPPER=C:/Strawberry/c/bin/../libexec/gcc/x86_64-w64-mingw32/7.1.0/lto-wrapper.exe
      Target: x86_64-w64-mingw32
      Configured with: ../../../src/gcc-7.1.0/configure --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --prefix=/mingw64 --enable-shared --enable-static --disable-multilib --enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --enable-libstdcxx-filesystem-ts=yes --disable-libstdcxx-pch --disable-libstdcxx-debug --disable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-libiconv --with-system-zlib --with-gmp=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpfr=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpc=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-isl=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-pkgversion='x86_64-posix-seh, Built by strawberryperl.com project' CFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CPPFLAGS=' -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' LDFLAGS='-pipe -fno-ident -L/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/lib -L/opt/build/prerequisites/x86_64-zlib-static/lib -L/opt/build/prerequisites/x86_64-w64-mingw32-static/lib '
      Thread model: posix
      gcc version 7.1.0 (x86_64-posix-seh, Built by strawberryperl.com project)
        NOT AVAILABLE

      atlas_3_10_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      accelerate_info:
        NOT AVAILABLE

      C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\numpy\distutils\system_info.py:690: UserWarning:
          Optimized (vendor) Blas libraries are not found.
          Falls back to netlib Blas library which has worse performance.
          A better performance should be easily gained by switching
          Blas library.
        self.calc_info()
      blas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries blas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\numpy\distutils\system_info.py:690: UserWarning:
          Blas (http://www.netlib.org/blas/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [blas]) or by setting
          the BLAS environment variable.
        self.calc_info()
      blas_src_info:
        NOT AVAILABLE

      C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\numpy\distutils\system_info.py:690: UserWarning:
          Blas (http://www.netlib.org/blas/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [blas_src]) or by setting
          the BLAS_SRC environment variable.
        self.calc_info()
        NOT AVAILABLE

      'svnversion' is not recognized as an internal or external command,
      operable program or batch file.
      non-existing path in 'numpy\\distutils': 'site.cfg'
      lapack_opt_info:
      lapack_mkl_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries mkl_rt not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      openblas_lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      gnu: no Fortran 90 compiler found
      gnu: no Fortran 90 compiler found
      customize IntelVisualFCompiler
      customize AbsoftFCompiler
      customize CompaqVisualFCompiler
      customize IntelItaniumVisualFCompiler
      customize Gnu95FCompiler
      Using built-in specs.
      COLLECT_GCC=C:\Strawberry\c\bin\gfortran.exe
      COLLECT_LTO_WRAPPER=C:/Strawberry/c/bin/../libexec/gcc/x86_64-w64-mingw32/7.1.0/lto-wrapper.exe
      Target: x86_64-w64-mingw32
      Configured with: ../../../src/gcc-7.1.0/configure --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --prefix=/mingw64 --enable-shared --enable-static --disable-multilib --enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --enable-libstdcxx-filesystem-ts=yes --disable-libstdcxx-pch --disable-libstdcxx-debug --disable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-libiconv --with-system-zlib --with-gmp=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpfr=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpc=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-isl=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-pkgversion='x86_64-posix-seh, Built by strawberryperl.com project' CFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CPPFLAGS=' -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' LDFLAGS='-pipe -fno-ident -L/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/lib -L/opt/build/prerequisites/x86_64-zlib-static/lib -L/opt/build/prerequisites/x86_64-w64-mingw32-static/lib '
      Thread model: posix
      gcc version 7.1.0 (x86_64-posix-seh, Built by strawberryperl.com project)
        NOT AVAILABLE

      openblas_clapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries openblas,lapack not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      gnu: no Fortran 90 compiler found
      gnu: no Fortran 90 compiler found
      customize IntelVisualFCompiler
      customize AbsoftFCompiler
      customize CompaqVisualFCompiler
      customize IntelItaniumVisualFCompiler
      customize Gnu95FCompiler
      Using built-in specs.
      COLLECT_GCC=C:\Strawberry\c\bin\gfortran.exe
      COLLECT_LTO_WRAPPER=C:/Strawberry/c/bin/../libexec/gcc/x86_64-w64-mingw32/7.1.0/lto-wrapper.exe
      Target: x86_64-w64-mingw32
      Configured with: ../../../src/gcc-7.1.0/configure --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --prefix=/mingw64 --enable-shared --enable-static --disable-multilib --enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --enable-libstdcxx-filesystem-ts=yes --disable-libstdcxx-pch --disable-libstdcxx-debug --disable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-libiconv --with-system-zlib --with-gmp=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpfr=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-mpc=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-isl=/opt/build/prerequisites/x86_64-w64-mingw32-static --with-pkgversion='x86_64-posix-seh, Built by strawberryperl.com project' CFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' CPPFLAGS=' -I/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/include -I/opt/build/prerequisites/x86_64-zlib-static/include -I/opt/build/prerequisites/x86_64-w64-mingw32-static/include' LDFLAGS='-pipe -fno-ident -L/opt/build/x86_64-710-posix-seh-rt_v502/mingw64/opt/lib -L/opt/build/prerequisites/x86_64-zlib-static/lib -L/opt/build/prerequisites/x86_64-w64-mingw32-static/lib '
      Thread model: posix
      gcc version 7.1.0 (x86_64-posix-seh, Built by strawberryperl.com project)
        NOT AVAILABLE

      flame_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries flame not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      atlas_3_10_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries tatlas,tatlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
        NOT AVAILABLE

      atlas_3_10_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries satlas,satlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_3_10_info'>
        NOT AVAILABLE

      atlas_threads_info:
      Setting PTATLAS=ATLAS
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries ptf77blas,ptcblas,atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_threads_info'>
        NOT AVAILABLE

      atlas_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\lib
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in C:\
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack_atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries f77blas,cblas,atlas not found in c:\users\στραβούλα\appdata\local\programs\python\python39\libs
      <class 'numpy.distutils.system_info.atlas_info'>
        NOT AVAILABLE

      lapack_info:
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
        libraries lapack not found in ['c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\lib', 'C:\\', 'c:\\users\\στραβούλα\\appdata\\local\\programs\\python\\python39\\libs']
        NOT AVAILABLE

      C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\numpy\distutils\system_info.py:1712: UserWarning:
          Lapack (http://www.netlib.org/lapack/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [lapack]) or by setting
          the LAPACK environment variable.
        if getattr(self, '_calc_info_{}'.format(lapack))():
      lapack_src_info:
        NOT AVAILABLE

      C:\Users\Στραβούλα\AppData\Local\Temp\pip-install-1al5oc45\numpy\numpy\distutils\system_info.py:1712: UserWarning:
          Lapack (http://www.netlib.org/lapack/) sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [lapack_src]) or by setting
          the LAPACK_SRC environment variable.
        if getattr(self, '_calc_info_{}'.format(lapack))():
        NOT AVAILABLE

      c:\users\στραβούλα\appdata\local\programs\python\python39\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros'
        warnings.warn(msg)
      running install
      running build
      running config_cc
      unifing config_cc, config, build_clib, build_ext, build commands --compiler options
      running config_fc
      unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
      running build_src
      build_src
      building py_modules sources
      creating build
      creating build\src.win-amd64-3.9
      creating build\src.win-amd64-3.9\numpy
      creating build\src.win-amd64-3.9\numpy\distutils
      building library "npymath" sources
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
      ----------------------------------------
  ERROR: Command errored out with exit status 1: 'c:\users\στραβούλα\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Στραβούλα\\AppData\\Local\\Temp\\pip-install-1al5oc45\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Στραβούλα\\AppData\\Local\\Temp\\pip-install-1al5oc45\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-record-1qm0ngw_\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay' --compile --install-headers 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay\Include\numpy' Check the logs for full command output.
  ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\στραβούλα\appdata\local\programs\python\python39\python.exe' 'c:\users\στραβούλα\appdata\local\programs\python\python39\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Στραβούλα\AppData\Local\Temp\pip-build-env-w3wt_sg1\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.28.5' 'numpy==1.13.3; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"' and platform_python_implementation == '"'"'CPython'"'"'' 'numpy==1.14.0; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"' and platform_python_implementation != '"'"'CPython'"'"'' 'numpy==1.14.5; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.6'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version>='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'scipy>=0.19.1' Check the logs for full command output.

Thanks in advance to anyone reading it.
I am more than gratefull to any person with any ideas about it.


text:
Q: Is it possible to create a new python object with custom methods? So I've got a class in python representing an epidemic simulation.  So in many cases I have an 'S', 'I' and possibly 'R' states (susceptible, infected, recovered).  So I've got something crudely like this method in the class:
def S(self):
    return data['S']

So I can access the data with foo.S
but maybe I'm looking at some other simulation where I've got other statuses (let's say 'E' is also a status (exposed)).  I'd like to be able to automatically get the other data by a similar method: foo.E.  I want to be able to do any particular collection of statuses without having to change the class itself.
So I'm looking for a way to modify __init__ for MyClass so that I can define
foo = MyClass(status_list = ('S', 'I', 'E', 'R', 'someotherstatus'))

and then I can automatically access foo.someotherstatus.  With my current understanding, the only way I can do this is to go into the code of MyClass and explicitly define a method someotherstatus which will return data['someotherstatus'].

A: IIUC, try using setattr:
import pandas as pd

data = pd.DataFrame(columns = ['S', 'I', 'E', 'R', 'someotherstatus'])

class MyClass:
    def __init__(self, status_list):
        for i in status_list:
            setattr(self, i, data[i])

foo = MyClass(status_list = ('S', 'I', 'E', 'R', 'someotherstatus'))
foo.S

Output:
Series([], Name: S, dtype: object)

A: Maybe this gives you some ideas:
class MyClass:

    def get_status(self, status, other_param=None):
        if other_param:
            return self.data[status] + other_param
        else:
            return self.data[status]

    def __init__(self):
        self.data = {
            'S': 1,
            'someotherstatus': 2,
        }

        # without other params
        setattr(self, 'someotherstatus', self.get_status('someotherstatus'))

        # with an other param
        setattr(self, 'someotherstatus_with_param', lambda other_param: self.get_status('someotherstatus', other_param))

obj = MyClass()
print(obj.someotherstatus)  # 2
print(obj.someotherstatus_with_param(2)) # 4


text:
Q: Tinymce formatted content not displayed from database Hi I have many tinymce editor in single page. When I format the content in tinymce and save it into database. All tags are saved in mysql. But while editing I get data from database but some of the tinymce (not all) is not able to read tags and it shows content without formatting. My initialization is:
  tinymce.init({
        selector: "textarea", theme: "modern", width: "100%", height: 300,
        plugins: [
        "advlist autolink link image lists charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
        "table contextmenu directionality emoticons paste textcolor responsivefilemanager code",
        "paste"
        ],
        paste_retain_style_properties: "all",
        toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
        toolbar2: "| responsivefilemanager | link unlink anchor | image media | forecolor backcolor  | print preview code ",
        image_caption: true,
        image_advtab: true,
        external_filemanager_path: "<?php echo base_url(); ?>" + "tinymce/file_manager/filemanager/",
        filemanager_title: "Responsive Filemanager",
        external_plugins: {"filemanager": "<?php echo base_url(); ?>" + "tinymce/file_manager/filemanager/plugin.min.js"},
        document_base_url : "<?php echo base_url(); ?>",
          relative_urls : false,
          remove_script_host : false,
    });

A: There must be some sort of filtering or sanitizing.
You may have strip_tags used after you get the data from the database.


text:
Q: Reading a session variable inside a behavior in cakephp 2 I have a behavior which enables segregation of user data based on the user id stored in the session.  In CakePHP 1.3 you could do this:
App::import('Component', 'Session');
$session = new SessionComponent();
$session->read('Auth.User.id');

But in CakePHP 2, you can't instantiate a component like that in a behavior because the Component __construct requires the Controller's ComponentCollection as a parameter.
Is it possible to access a session variable inside a behavior in CakePHP 2?  What's the best way to do it?

A: In CakePHP 2.0 you can also simply call the Session-methods via the static CakeSession::method() without having to load anything... ;-)

A: If you look at the SessionComponent code, you will see that it is only a wrapper for the CakeSession class.
So you can do the following:
App::uses('CakeSession', 'Model/Datasource');
$user_id = CakeSession::read('Auth.User.id');


text:
Q: Send lists and dictionaries in Python requests GET I built a test FastAPI instance with a GET operation as follows:
import uvicorn
from fastapi import FastAPI
from typing import List, Dict

app = FastAPI()

@app.get("/result/")
async def root(d: Dict, l: List):
    keys = list(d.keys())
    for i in range(len(keys)):
        d[keys[i]] = d[keys[i]] + l[i]
    return d

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

After running the API, I would like to try to launch a request via requests.get() with the parameters d = {'a': 2, 'b': 3, 'c': 4} and l = [3, 5, 8], I would like to understand how to write the url in r = requests.get(...).

A: A clean way is to build a model for your expected inputs, as in https://fastapi.tiangolo.com/tutorial/extra-models/
And you have to use post instead of get.


text:
Q: Initialising nested classes in Python Let's say I want to create a class 'House' that has some attributes of its own, but also has a (nested?) 'Resident' class which has some attributes and has a mandatory attribute 'surname'. A house instance may exist though without any residents. How can create this so that I can eventually do the following?
myhouse = House()
residentX = myhouse.resident('Smith')

Currently I set this up as a nested class but run into trouble when I try and initialise myhouse given that it is requiring a surname at this point for the nested Resident class (which I don't necessarily have at this point)
class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self.resident = self.Resident()

    class Resident:
        def __init__(self, surname):
            self.surname = surname

I know I can restructure the code to not use nested classes and then explicitly tie any resident to a house in my code. However, I would like to use the dot notation here (myhouse.resident) to automatically tie a resident to a house.
Also, I understand that nested classes in python are somewhat frowned upon - I'm open to suggestions on how to do the above in a more pythonic manner.

A: I would break out the Resident class and use a property/setter for .resident
Like this:
class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self._resident = None

    @property
    def resident(self):
        return self._resident

    @resident.setter
    def resident(self, surname):
        r = Resident(surname)
        self._resident = r

class Resident:
    def __init__(self, surname):
        self.surname = surname

However, if you want .resident to be callable but also want to track the house's residents, you can still break out the Resident class, and use:
class House:
    def __init__(self):
        self.someattribute = <someattribute>
        self.residents = []

    def resident(self, surname):
        '''
        Add a resident to the house
        '''
        r = Resident(surname)
        self.residents.append(r)
        return r

class Resident:
    def __init__(self, surname):
        self.surname = surname


text:
Q: How to compare two string values within a threshold value in swift? I am trying to write a code where I have got two time[hh:min] data(String type). Need to just compare but the challenge is my code undergones some validations before returning the final values. so the assertion fails sometimes stating expected value is [17:04] but actual is [17:05]. Is there any way where we can use concept of Threshold that upto few minutes (say 2 mins) the comparison will still be valid?

A: Step one is do not store a thing as something that it is not. If these are times, they should be stored as times. Strings are for representation to the users; underlying storage is for reality.
So now let's store our times as date components:
let t1 = DateComponents(hour:17, minute:4)
let t2 = DateComponents(hour:17, minute:5)

Now it's easy to find out how far apart they are:
let cal = Calendar(identifier: .gregorian)
if let d1 = cal.date(from: t1),
    let d2 = cal.date(from: t2) {
        let diff = abs(d1.timeIntervalSince(d2))
        // and now decide what to do
}

A: You first need to seprate your string to an array, and then you can compare.
/* That two arrays are A1 and A2 */
let minute1 = Int(A1[0])*60+Int(A1[1])
let minute2 = Int(A2[0])*60+Int(A2[1])

This may help you. I think that @Sweeper did not understand that it is a time, not a date.

A: You can convert your string to minutes, subtract one from another and check if the absolute value is less than the threshold:
extension String {
    var time24hToMinutes: Int? {
        guard count == 5, let hours = Int(prefix(2)), let minutes = Int(suffix(2)), Array(self)[2] == ":"  else { return nil }
        return hours * 60 + minutes
    }
    func time24hCompare(to other: String, threshold: Int = 2) -> Bool {
        guard let lhs = time24hToMinutes, let rhs = other.time24hToMinutes else { return false }
        return abs(lhs-rhs) < threshold
    }
}

Testing:
"17:02".time24hCompare(to: "17:04")  // false
"17:03".time24hCompare(to: "17:04")  // true
"17:04".time24hCompare(to: "17:04")  // true
"17:05".time24hCompare(to: "17:04")  // true
"17:06".time24hCompare(to: "17:04")  // false


text:
Q: SELinux - mysql/ and httpdoc/ in same folder? Looks like my old faithful LAMP directory structure has come unstuck with SELinux. I prefer everything in the same place. CentOS 6.6 Apache 2.2.15 MySQL 6.5
/DATA/
/DATA/httpdocs/
/DATA/mysql/
/DATA/server-config.php
/DATA/httpd-error.logs...

If I do this then Apache works fine but mysql will not start.
chcon -R -t httpd_sys_content_t /DATA/
chcon -R -t mysqld_db_t  /DATA/mysql
chcon -R -t httpd_sys_content_t /DATA/httpdocs

If I do this then mysql will start but Apache will not start.
chcon -R -t mysqld_db_t /DATA
chcon -R -t mysqld_db_t  /DATA/mysql
chcon -R -t httpd_sys_content_t /DATA/httpdocs

I know this is related to the label I'm attaching to the root /DATA folder and they can not have two?
Yes all my problems go away if I disable SELinux but it is required for this project. The folders are chowned and chmodded fine.
For the mysql case the error is
2015-04-24 14:17:56 3391 [Warning] Can't create test file /DATA/mysql/WIK1.lower-test
2015-04-24 14:17:56 3391 [Warning] Can't create test file /DATA/mysql/WIK1.lower-test
/usr/sbin/mysqld: Can't change dir to '/DATA/mysql/' (Errcode: 13 - Permission denied)
2015-04-24 14:17:56 3391 [ERROR] Aborting

For the Apache case the error is.
Starting httpd: Warning: DocumentRoot [/DATA/httpdocs/] does not exist

I have tried adding this to /etc/selinux/targeted/contexts/files/file_contexts.local
/DATA/mysql(/.*)?       system_u:object_r:mysql_db_t:s0

But it does nothing.
Can anyone help me tame SELinux or is my only option a separate folder for mysql?
Thanks

Thanks, I tried this (also posting answer cause I could not format text in comment)
    cd ~
    setenforce Permissive
    service mysqld restart
    service httpd restart
    # interact with web app make it do things like file writes, db access, network and so on.
    grep 'mysqld_t\|httpd_sys_content_t' /var/log/audit/audit.log | audit2allow -M postgreylocal
    semodule -i postgreylocal.pp
    # check it exists...
    semodule -l
    chcon -R -t postgreylocal /DATA
    chcon -R -t postgreylocal /DATA/
setenforce Enforce

mysql still does not go. I think I do not know how to apply the policy postgreylocal?
In the log I have - /var/log/audit/audit.log
type=AVC msg=audit(1429892483.654:3036): avc:  denied  { read } for  pid=7089 comm="mysqld" name="DATA" dev=dm-3 ino=13 scontext=unconfined_u:system_r:mysqld_t:s0 tcontext=system_u:object_r:unlabeled_t:s0 tclass=lnk_file
type=SYSCALL msg=audit(1429892483.654:3036): arch=c000003e syscall=80 success=no exit=-13 a0=132b500 a1=10 a2=41000 a3=7fff4d3af8f0 items=1 ppid=6882 pid=7089 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=4294967295 comm="mysqld" exe="/usr/sbin/mysqld" subj=unconfined_u:system_r:mysqld_t:s0 key=(null)
type=CWD msg=audit(1429892483.654:3036):  cwd="/"
type=PATH msg=audit(1429892483.654:3036): item=0 name="/DATA/mysql/" nametype=UNKNOWN

If I chcon with SE Enforcing I get the following....
# chcon -R -t postgreylocal /DATA
chcon: failed to change context of `/DATA' to `system_u:object_r:postgreylocal:s0': Invalid argument

A: You can not attach two different security labels to the same directories. So, you had to select a single label and let the other process to read/write the files with that label.
Problem is that doing that you are effectively granting the second process read/write access to the files owned by the first process, which is exactly what you don't want to do.
Two solutions exists:

*

*you can mark all as httpd_sys_content_t and let mysql access files with that label. While this is remain somewhat insecure (mysql process can read/write http files), mysqld is usually a trusted process and so it is way better than the other way around (let http do access mysql files).

*you con assign to /DATA/ a different, shared label and modify your selinux policy in a way that grant permission to both httpd and mysqld to that shared label. Under /DATA/, leave the two directory types with their own lables (eg: /DATA/mysql with mysqld_db_t and /DATA/httpdocs with httpd_sys_content_t)

In both cases, for an easy policy edit, set selinux to permissive mode, the use the audit2allow utility to parse your /var/log/audit/audit.log file.
Here you can find more informations.


text:
Q: Using negative lookbehind and lookahead in html5 pattern I have tried looking over quite a lot of regex guides on how to use the negative lookbehind and lookahead in my regex function for html5 pattern.
I am trying to match the following pattern, where the string has to start and end with a [a-z] letter. The string can be up to 30 characters long. Can also include the symbol: -, however it can never have more than one - in a row.
Sooo, what I came up with so far is this:
^[a-z][a-z(?<!-(-)?!-)]{0,28}[a-z]$

Now I could not get the lookahead and lookbehind so work properly and I am not quite sure if I implemented the max 30 characters correctly. However, I have tried starting and ending with [a-z] and it works fine.
Some example strings:
'a-b' => true
'a-' => false
'-a' => false
'a--b' => false
'ab-cd' => true
'abc' => true
'a-b-c' => true

A: You need to use
^(?!.{31})[a-z]+(?:-[a-z]+)*$

See the regex demo
Note that in an HTML5 pattern attribute, the anchors are usually not required as the pattern is anchored on both sides by default.
Details

*

*^ - start of string

*(?!.{31}) - there cannot be 31 chars other than line break chars (this (?!...) is a negative lookahead that fails the match if its pattern is matched) (you may also use a positive lookahead - (?=.{1,30}$) - that requires 1 to 30 chars in the string)

*[a-z]+ - 1 or more lowercase ASCII letters

*(?:-[a-z]+)* - zero or more sequences of:

*

*- - a hyphen

*[a-z]+ - 1 or more lowercase ASCII letters

*$ - end of string.

A: You can use this pattern:
([a-z]|\b-\b){1,30}

The word boundaries prevent hyphens to be consecutive or to be at the string limits.
Note that ^ and $ are not needed in the pattern attribute since they are implicit.
demo


text:
Q: Ionic http post to external url Im trying to send a post to a url with Ionic using angular, but i have the response:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

I know that the external service is working, because i tested it by ajax and everything works perfectly...
Below the code used in AngularJS (Ionic) and Ajax:
Ionic:
var loginServiceUrl = 'http://url.com.br'; //It is not the real one
var loginServiceData = {
    email: email@email.com.br
    senha: 1234
};
$http.post(loginServiceUrl, loginServiceData).
then(function (res){
    console.log(res);
});

Ajax:
$.ajax({
    type: "POST",
    url : 'http://url.com.br', //It is not the real one
    data : {email: 'email@email.com.br', senha: '1234'},
    success: function(result) {
        $('html').text(JSON.stringify(result));
    }
});

Does anyone know why I get the post via ajax on my localhost and not with the ionic, also localhost?

A: Check this out. It is well explained how to handle issues like yours --> http://blog.ionic.io/handling-cors-issues-in-ionic/

A: Try to add headers in your POST request.
//example of DataToSend
   var DataToSend = {
                    userID: deviceID,
                    coordLat : pos.coords.latitude,
                    coordLon: pos.coords.longitude
   };

   $http({
            method: 'POST',
            url: 'http://url.com.br',
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            data: DataToSend
        })

A: CORS has nothing to do with your frontend.
Before sending the POST request, browser send a OPTIONS request to the server to check if call from your domain is allowed or not.
Since, you are getting  Status 404, that means your server is not handling the OPTIONS request
1. Allow the OPTIONS request (same as POST)
Now come to second part i.e " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' "
After allowing the OPTIONS request, now set the response header of OPTIONS request (Browser will check the response of OPTIONS request and then process the POST request only  if there is 'Access-Control-Allow-Origin' present in the OPTIONS response.
2. Set the response headers of OPTIONS request
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");

Example..
(In Java)
Router:
OPTIONS /*all
controllers.Application.preflight(all)

Controller Function:
public static Result preflight(String all) {
        response().setHeader("Access-Control-Allow-Origin", "*");
        response().setHeader("Allow", "*");
        response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
        response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Auth-Token");
        return ok();
    }

Hope this will solve your problem.
Cheers


text:
Q: Why does this Grammar work in LALR(1) but not LR(1) By all accounts, LR(1) should be more powerful in every way compared to LALR(1) since LR(1) builds a canonical collection of LR(1) items, and LALR(1) is just a better SLR(1) parser.
Then why does this grammar work successfully in an LALR(1) parser, but not in an LR(1) parser when I try this input:
int + int
For this grammar:
S' -> S
S -> Add

Add -> Mul
Add -> Add + Mul

Mul -> Const
Mul -> Mul * Mul

Const -> int
Const -> float

These are the JavaScript LR(1) and JavaScript LALR(1) parsers I used for this example:

http://jsmachines.sourceforge.net/machines/lr1.html
http://jsmachines.sourceforge.net/machines/lalr1.html

UPDATE
The JSmachine site is pretty buggy. I used this site instead https://zaa.ch/jison/try/usf/index.html from the University of South Florida, but I was advised to use Bison to ensure correctness.
As the top comment suggested, Mul -> Mul * Mul is pretty ambiguous so I updated the grammar accordingly
S' -> S
S -> Add

Add -> Mul
Add -> Add + Mul

Mul -> Const
Mul -> Mul * Const

Const -> int
Const -> float

adapted to BNF format:
%%
SS : S ;
S  : Add ;

Add : Mul
    | Add '+' Mul
    ;

Mul : Const
    | Mul '*' Const
    ;

Const : int
      | float
      ;

A: I'm not sure what you mean by "work" in your question. That online parser-generator reports shift-reduce conflicts for both the LR(1) and the LALR(1) algorithms, which is not suprising since your grammar includes the exponentially ambiguous
Mul -> Mul * Mul

Apparently, that site's LR(1) implementation handles errors with less grace than it's LALR(1) implementation. I'd say that it's a bug. But in any event, the grammar cannot produce either an LALR(1) or an LR(1) parser.


text:
Q: Why inserting into the table not working? I wonder why this piece of code is not working?
SqlCommand comand = new SqlCommand();
//string myConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=try;Integrated Security=True;Pooling=False";
SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Integrated Security=True;User Instance=True");
comand.Connection = conn;
conn.Open();

comand.CommandText = "INSERT INTO TableProduct (productID,productName) VALUES ('1','M')";

comand.ExecuteNonQuery();
conn.Close();

A: The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to

*

*install SQL Server Express (and you've already done that anyway)

*install SQL Server Management Studio Express

*create your database in SSMS Express, give it a logical name (e.g. mydatabase)

*connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=mydatabase;Integrated Security=True

and everything else is exactly the same as before...

A: Becasue you declared your SqlCommand as comando but you used it as comand?
Change
SqlCommand comando = new SqlCommand();

to
SqlCommand comand = new SqlCommand();


text:
Q: Add corresponding non-database class to entity framework object I am currently using EntityFrameworkCore 2.0.0.
The application I am creating is an online store product scraper. All stores are saved in the database, and each store has a scraper that implements IStoreScraper.
This is my store model:
public class Store
{
    public int Id { get; set; }
    public string Name { get; set; }

    [NotMapped]
    public IStoreScraper StoreScraper { get; set; }
}

I was wondering if it is possible to add the correct IStoreScraper object to the Store object when it is fetched from the database. Either by a value from the database or something else.
I also looked into injecting this in the constructor of the model, however, this violates the Dependency Injection pattern because each class has its own, already known, implementation.
Maybe I should even look at it from another perspective because this code should not be in a model class? Any ideas?

A: You can override the object materialized event and add it here, as mentioned in this answer;
How to Inject Helper Dependencies in Domain Model Entity Classes
However I would highly recommend against this. EF is meant to be your data model, you should have a business layer above this, which is the correct place to add dependencies like this.


text:
Q: Variance where the distribution depends on another distribution Let $X$ be the result of one roll of a $6$-sided unbiased die, and let $Y$ be the result of one roll of an $X$-sided die. How would I go about calculating the mean, variance and distribution of $Y$?

A: $X$ is uniformly distributed on $\{1,2,3,4,5,6\}$, and conditioned on $X=i$, $Y$ is uniformly distributed on $\{1,2,\ldots,i\}$. We may then compute
\begin{align}
\mathbb P(Y=k) &= \bigcup_{i=1}^k \mathbb P\left(\left\{Y=k \right\}\cap \left\{X=i\right\}\right)\\
&= \sum_{i=1}^k \mathbb P\left(\left\{Y=k \right\}\cap \left\{X=i\right\}\right)\\
&= \sum_{i=1}^k \mathbb P(Y=k\mid X=i)\mathbb P(X=i)\\
&= \frac16\sum_{i=1}^k \frac1i\cdot \mathsf 1_{\{1,2,\ldots,i\}}(k)\\
&= \frac16\sum_{i=k}^6 \frac1i.
\end{align}
This yields
\begin{align}
\mathbb P(Y=1) &= \frac16 \sum_{i=1}^6 \frac 1i = \frac{49}{120}\\
\mathbb P(Y=2) &= \frac16 \sum_{i=2}^6 \frac 1i = \frac{29}{120}\\
\mathbb P(Y=3) &= \frac16 \sum_{i=3}^6 \frac 1i = \frac{19}{120}\\
\mathbb P(Y=4) &= \frac16 \sum_{i=4}^6 \frac 1i = \frac{37}{360}\\
\mathbb P(Y=5) &= \frac16 \sum_{i=5}^6 \frac 1i = \frac{11}{180}\\
\mathbb P(Y=6) &= \frac16 \sum_{i=6}^6 \frac 1i = \frac1{36}.\\
\end{align}
It follows that
\begin{align}
\mathbb E[Y] &= \sum_{k=1}^6 k\cdot\mathbb P(Y=k)\\
&= \frac{49}{120} + 2\cdot\frac{29}{120} + 3\cdot \frac{19}{120} + 4\cdot \frac{37}{360}+5\cdot\frac{11}{180}+6\cdot\frac1{36}\\
&= \frac94
\end{align} and
\begin{align}
\mathbb E[Y^2] &= \sum_{k=1}^6 k\cdot\mathbb P(Y=k)\\
&= \frac{49}{120} + 2^2\cdot\frac{29}{120} + 3^2\cdot \frac{19}{120} + 4^2\cdot \frac{37}{360}+5^2\cdot\frac{11}{180}+6^2\cdot\frac1{36}\\
&= \frac{251}{36},
\end{align}
and hence
\begin{align}
\operatorname{Var}(Y) &= \mathbb E\left[Y^2\right] - \mathbb E[Y]^2\\
&= \frac{251}{36} - \left(\frac94\right)^2\\
&= \frac{85}{18}.
\end{align}


text:
Q: Attempting to convert a prefix command to a slash command - getting "This interaction failed." Basically, I'm converting one of my regular commands into a slash command. It's just an embedded response, but the issue is that it says "This interaction failed". I read on deferReply(), but deferReply doesn't work for me at all, it's supposed to say "bot is thinking.." but doesn't. It does the 3 second "Sending command..." then fails.
Code:
const { SlashCommandBuilder, EmbedBuilder } = require('@discordjs/builders');
const wait = require('node:timers/promises').setTimeout;

        let questions = [
            {
                title: "some array you got there!",
            },

        ]

        let suggest = ["some array you got there!",]
        let q = questions[Math.floor(Math.random()*(questions.length))];
        let s = suggest[Math.floor(Math.random()*(suggest.length))];

        module.exports = {
            data: new SlashCommandBuilder()
            .setName('topic')
            .setDescription('gives topics'),
        async execute(interaction, message) {
            interaction.deferReply()

            const user = message.mentions.users.first() || message.author;

        const embed = {
        title: `**${q.title}**`,
        author: {
            name: 'chat topic:',
            icon_url: user.avatarURL(),
            url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
        },
        footer: {
            text: `topic requested by: ${message.author.username} ${s}`,
            icon_url: '',
        },
        color: 0x7732a8,
    }

       interaction.editReply({ embeds: [embed] });

    }}

There's no issues in console, I tried to log, still nothing. Just "This interaction failed."


text:
Q: Using AJAX when submitting forms I'm very new to form submission with AJAX and have been following many tutorials on it's use, however I cannot seem to get it working in my current scenario.
I have a modal with a form inside of it linked to a PHP script and some JQuery AJAX.
When i submit the form the page appears white, I'm fairly sure this is because of the conditional logic in my PHP script.
So, where I have $stmt->rowCount() and the conditional logic it returns nothing as the script does nothing at this point.
Can I link this logic to AJAX success or failure or do I have to return a boolean from my script?
I know this is probably considered a silly question but some clarity would be of great use.
Form
<form id="userForm" method="post" action="test/process_data.php">

      First name:
      <input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>

      Surname:
      <input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>

      Email:
      <input type="email" class="form-control" name="email" id="email" placeholder="someone@example.com">

      Company:
      <input type="text" class="form-control" name="company" id="company" placeholder="Company name">

    <button type="submit" class="btn btn-primary">Submit</button>
    Just take me to the partner
  </form>

AJAX Script

PHP Script to handle data
if (empty($_POST["forename"]) ||
    empty($_POST["surname"]) ||
    empty($_POST["email"]) ||
    empty($_POST["company"]))
    {

    }
    else{

        $forename = $_POST['forename'];
        $surname = $_POST['surname'];
        $email_address = $_POST['email'];
        $company_name = $_POST['company'];
        $id = rand();
        $date_time = date('Y-m-d');

        try
            {
                // Construct the SQL to add a book to the database
                $sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
                VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
                // Prepare the SQL and bind parameters
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':forename', $forename);
                $stmt->bindParam(':surname', $surname);
                $stmt->bindParam(':email_address', $email_address);
                $stmt->bindParam(':company_name', $company_name);
                $stmt->bindParam(':id', $id);
                $stmt->bindParam(':date_time', $date_time);
                $stmt->execute();

                // If the statement affected the database
                if ($stmt->rowCount() > 0)
                {

                }
                else{

                }

            } catch(PDOException $e){
                echo "Error: " . $e->getMessage();
            }

    }

A: Use serialize() method on the form to define the data property in your ajax call. Also added error handling.
  $.ajax({
      url: "process_data.php",
      type: "POST",
      data:  $("#userForm").serialize(),
      success: function(data){
          //Successful
      },
      error: function (XMLHttpRequest, textStatus, errorThrown)
      {
           if (!window.console) console = { log: function () { } };
           console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
      }
  });

A: Use preventDefault(); before sending ajax request. Now when the form is done submitting you can do like this.