text:
Q: Remote Transport Control does not show up for radio stream SwiftUI app with AVPlayer I am developing simple app in SwiftUI for one internet radio. It uses AVPlayer for play the stream available at given url. And that works perfectly. I have also set up AVSession in AppDelegate, so the app plays in background, stops playing while the call is incoming and resumes playing after the call. This all works fine. However, I wasn't able neither to bring the remote control on lock screen nor showing app in Player tile in Control Center.
The app is written using SwiftUI, I am also moving from traditional completion blocks and targets into Combine. I have created separate class Player, which is ObservableObject (and observed by ContentView), where I set up AVPlayer, AVPlayerItem (with given URL for stream).  And all works fine. App updates the state on change of player state. I am not using AVPlayerViewController, since I don't need one. On initialization of that Player object I am also setting up Remote Transport Controls using this method (I moved from setting targets to publishers).
func setupRemoteTransportControls() {

        let commandCenter = MPRemoteCommandCenter.shared()

        commandCenter.publisher(for: \.playCommand)
            .sink(receiveValue: {_ in self.play() })
            .store(in: &cancellables)

        commandCenter.publisher(for: \.stopCommand)
            .sink(receiveValue: {_ in self.stop() })
            .store(in: &cancellables)
    }

Either I use the original version of that method provided by Apple, or my own version (as shown above) the Remote Control doesn't show up, and the Control Center tile player is not updated.
Of course I use the method provided by Apple for updating NowPlaying
func setupNowPlaying() {
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Radio"

        if let image = UIImage(systemName: "radio") {
            nowPlayingInfo[MPMediaItemPropertyArtwork] =
                MPMediaItemArtwork(boundsSize: image.size) { size in
                    return image
            }
        }

        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player?.currentItem?.currentTime().seconds ?? ""
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = player?.currentItem?.asset.duration.seconds ?? ""
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = isPlaying ? 1 : 0

        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }

I don't know where is the problem. Is it the way I set up Remote Transport Controls? The flow is like this:
Observable Player object with AVPlayer and setup for Remote Transport Controls and NowPlaying -> observed by -> Content View.
Here is full listing for Player class:
import Foundation
import AVKit
import Combine
import MediaPlayer

class Player: ObservableObject {
    private let streamURL = URL(string: "https://stream.rcs.revma.com/ypqt40u0x1zuv")!

    @Published var status: Player.Status = .stopped
    @Published var isPlaying = false
    @Published var showError = false
    @Published var isMuted = false

    var player: AVPlayer?

    var cancellables = Set<AnyCancellable>()

    init() {
        setupRemoteTransportControls()
    }

    func setupPlayer() {
        let item = AVPlayerItem(url: streamURL)
        player = AVPlayer(playerItem: item)
        player?.allowsExternalPlayback = true
    }

    func play() {
        handleInterruption()
        handleRouteChange()
        setupPlayer()
        player?.play()
        player?.currentItem?.publisher(for: \.status)
            .sink(receiveValue: { status in
                self.handle(status: status)
            })
            .store(in: &cancellables)
    }

    func stop() {
        player?.pause()
        player = nil
        status = .stopped
    }

    func mute() {
        player?.isMuted.toggle()
        isMuted.toggle()
    }

    func handle(status: AVPlayerItem.Status) {
        switch status {
            case .unknown:
                self.status = .waiting
                self.isPlaying = false
            case .readyToPlay:
                self.status = .ready
                self.isPlaying = true
                self.setupNowPlaying()
            case .failed:
                self.status = .failed
                self.isPlaying = false
                self.showError = true
                self.setupNowPlaying()
            default:
                self.status = .stopped
                self.isPlaying = false
                self.setupNowPlaying()
        }
    }

    func handleInterruption() {
        NotificationCenter.default.publisher(for: AVAudioSession.interruptionNotification)
            .map(\.userInfo)
            .compactMap {
                $0?[AVAudioSessionInterruptionTypeKey] as? UInt
            }
            .map { AVAudioSession.InterruptionType(rawValue: $0)}
            .sink { (interruptionType) in
                self.handle(interruptionType: interruptionType)
            }
            .store(in: &cancellables)
    }

    func handle(interruptionType: AVAudioSession.InterruptionType?) {
        switch interruptionType {
        case .began:
            self.stop()
        case .ended:
            self.play()
        default:
            break
        }
    }

    typealias UInfo = [AnyHashable: Any]

    func handleRouteChange() {
        NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification)
            .map(\.userInfo)
            .compactMap({ (userInfo) -> (UInfo?, UInt?) in
                (userInfo, userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt)
            })
            .compactMap({ (result) -> (UInfo?, AVAudioSession.RouteChangeReason?) in
                (result.0, AVAudioSession.RouteChangeReason(rawValue: result.1 ?? 0))
            })
            .sink(receiveValue: { (result) in
                self.handle(reason: result.1, userInfo: result.0)
            })
            .store(in: &cancellables)
    }

    func handle(reason: AVAudioSession.RouteChangeReason?, userInfo: UInfo?) {
        switch reason {
        case .newDeviceAvailable:
            let session = AVAudioSession.sharedInstance()
            for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
                DispatchQueue.main.async {
                    self.play()
                }
            }
        case .oldDeviceUnavailable:
            if let previousRoute = userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
                for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
                    DispatchQueue.main.sync {
                        self.stop()
                    }
                    break
                }
            }
        default:
            break
        }
    }
}

extension Player {
    enum Status {
        case waiting, ready, failed, stopped
    }
}

extension Player {
    func setupRemoteTransportControls() {

        let commandCenter = MPRemoteCommandCenter.shared()

        commandCenter.publisher(for: \.playCommand)
            .sink(receiveValue: {_ in self.play() })
            .store(in: &cancellables)

        commandCenter.publisher(for: \.stopCommand)
            .sink(receiveValue: {_ in self.stop() })
            .store(in: &cancellables)
    }

    func setupNowPlaying() {
        var nowPlayingInfo = [String : Any]()
        nowPlayingInfo[MPMediaItemPropertyTitle] = "Radio"

        if let image = UIImage(systemName: "radio") {
            nowPlayingInfo[MPMediaItemPropertyArtwork] =
                MPMediaItemArtwork(boundsSize: image.size) { size in
                    return image
            }
        }

        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player?.currentItem?.currentTime().seconds ?? ""
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = player?.currentItem?.asset.duration.seconds ?? ""
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = isPlaying ? 1 : 0

        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }
}

A: It appeared that I need to add in AppDelegate in application(:didFinishLaunchWithOptions) one line of code:
UIApplication.shared.beginReceivingRemoteControlEvents()
That solved the problem. Now remote controller is visible on lock screen and it also works in Control Center.
Once additional fix. Changing targets to publisher in setupRemoteTransportControls() in my Player object didn't work. So I switched back to setting targets like this.
func setupRemoteTransportControls() {

        let commandCenter = MPRemoteCommandCenter.shared()

        // Add handler for Play Command
        commandCenter.playCommand.addTarget { event in
            self.play()
            return .success
        }

        // Add handler for Pause Command
        commandCenter.pauseCommand.addTarget { event in
            self.stop()
            return .success
        }
    }


text:
Q: "Bananagrams" under black light? There is a game called "Bananagrams" which includes a bunch of pieces with a letter on each. It seems when I shine a black light flashlight on the letters, the "M" letters glow, but no other pieces do.
All the pieces appear the same under normal lights (except of course the letters on each piece). Why would only the M's glow, can someone explain what may be happening here?

A: The blocks with the M came from a different batch than the others. There is no way to know why without more information.
It could have been that a previous batch of M blocks was defective (e.g. incomplete letters due to a defective M die) and had to be replaced, but that is pure speculation and there could be many other explanations.

A: Well, obviously either the 'M' pieces are made of some different material which flouresces, or they are painted / coated with some material that does while the other pieces are not.
I would be tempted to mail the makers and say, basically, 'I found this interesting thing' and ask them if they know: they look like they are fairly small and you might therefore get to talk to someone who actually knows about the manufacturing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting parameter from dropdown and passing to controller with value from model I have tried searching this out but can't seem to land on a fix for this probably simple problem I'm having with when creating a web app. Currently, I'm using an Actionlink but it is not a requirement. A button would also be fine. I'm trying to pass two parameters from a row in a table which removes a name from a group in Active Directory:
        @foreach (var r in Model)
        {
        ...etc
         <td>
           Html.ActionLink("Remove", "Remove", new { r.Sam, \\group name from ddl })
         </td>

In the Actionlink is the SamAccountName (r.Sam) which works but GroupName needs to come from a dropdown called "dllGroups" and both parameters are passed to:
public ActionResult Remove(string id, string GroupName)
It works if I hard code GroupName but passes null each time when trying getting both parameters filled via code. If I go to function using Ajax which I believe should be the correct method (using onclick grpName in the Actionlink), I'm stuck with not knowing how to get the SamAccountName from the model.
An example of the function I'm trying:
    function grpName(id) {
        $.ajax({
            type: "GET",
            url: "/Home/Remove",
            data: {
                id: id,
                GroupName: $('#dllGroups').val(),
            },
            datatype: "HTML",
            success: function (data) { },
            error: function (data, status, error) { }
        });
    }

Thanks for any assistance. As you probably have guessed I'm pretty new still but working hard on learning it.


text:
Q: Why did all my cool power armors turn into rusty T-45's? I had 5 sets of power armor in Sanctuary, and before I saved and stopped playing, I took out all the cores. However, when I started playing again there were pieces missing and paint jobs had been reset back to default state.
My Sanctuary is well guarded, with a 198 defense, and good happiness levels. I deleted my character, and started a new one, but the same thing happened again.
Why does this happen? How do I fix this?

A: This is part of the cell reset bug. The current work around is to only use power armor FRAMES that you BUY. Not the ones that you find out in the world. Those are essentially containers that get 'reset' when the cell reloads, randomizing whatever the contents were (i.e., Super Duper Flame Painted T-60 parts) into basic rusty T-45 parts.
For what I gather, using console commands to set yourself as the 'owner' of a found frame may prevent this (FYI, the command is setownership and IIRC the player's ID is 14). But better safe than sorry: KELO sells frames at Goodneighbor (just don't forget to take it home ;).
Another stop-gap is for it to always be worn when you save, either you or your current companion (they will exit it at some point, should you ever dismiss them, so keep that in mind).
I can't recall if this bug is present in the vanilla game, or if this happens to me because I've got mods installed. However, I can confirm that using purchased frames will keep you safe. On the plus side, you've got a few frames sitting around that will spawn free fusion cores for you.


text:
Q: Is saying 'who cares' rude or maybe even disrespectful? Two people are talking about what tasks should be finished on time, and what tasks should be put off until later. The conversation was like below:

A: I don't think those tasks are important. We can put it off for a month. Let's focus on the remaining tasks, they are the most important!
  B: Hang on. If we don't finish those tasks, some customers will not be satisfied with our software.
  A: How many users?
  B: Roughly 200 - 300.
  A: 300? Who cares? It is less than 0.001% of all customers we have. Let's focus on 99% and we will deal with those 300 later.

The second situation is about culture — picking your nose.

A: Why are you picking your nose in public?
  B: I have boogers in my nose.
  A: You should go to a restroom and do whatever you want. It's socially unacceptable.
  B: Who cares?

the third maybe:

A.'Oh, yesterday the funniest thing happened!'
    B. 'Yeah, what happened?'
    A. 'Ummm, sorry i wasn't talking to you.'
    B. 'Oh well, who cares anyways!'

I think that 'Who cares?' is rude or impolite, as the person who was talking cares about it but the person who is saying this phrase is being disrespectful and maybe is implying she/he was wrong.
Is saying "who cares?" OK or commonly used in everyday conversation?

A: It is commonly used in everyday conversation, and in most uses it is disrespectful to somebody (not necessarily the person spoken to).

A: "Who cares?" means rhetorically "It doesn't matter". It is more informal than the latter.
In your first example, The speaker who uses it is trying to say that the particular number doesn't matter because it is so much smaller than the what it is being compared to that it is negligeable.
In the second example, the speaker is trying to say that his nose-picking doesn't affect anybody.
Pragmatically, the phrase is short in the direction of being rude, but is not nearly in the 'slappable' scale. It is not ignorant to use, but because of its informality, might be considered an unthought-out reaction. In both examples, a more thoughtful response would be less confrontational. "Booger-picking doesn't compromise the health of other people, so I'd prefer to save time and effort by doing it here and now".
The distinction I'm trying to draw is that one might say "I am terribly sick" and if the response is "It doesn't matter", then that would be considered pretty rude.
In the end though, "who cares?" is often used confrontationally. It is nowhere near as rude as an epithet, and can be just as rude as a statement of facts. Hoever, you are right that there is some bit of negative affect to the usage.

A: In the simulated conversations the person saying "Who cares?" is doing so to dismiss an otherwise legitimate criticism that the second person is offering. This is in itself impolite or boorish. Since the conversations appear to be between intimates, the use of the phrase "Who cares?" is not in itself a sign of impoliteness. In formal encounters, however, it is to be avoided.

A: The statement "Who cares?" is often seen as extremely rude and even arrogant. Let's look at a more specific case: consider George W. Bush's response to journalist Bill Hangley at a press event in 2001:

Because I had serious misgivings about the president's performance to that point, my own involvement in the whole operation had left me feeling a bit like a pseudo person, so when I had the chance to shake Bush's hand, I said, "Mr. President, I hope you only serve one term. I'm very disappointed in your work so far."
His smiling response was swift: "Who cares what you think?"

This is a very small thing for a man in a position of importance to say. Although Hangley had criticized the president to his face, a man who was more sure of himself might have replied generously, even magnanimously: "I'm sorry you feel that way," perhaps, or "I am doing my best to change your mind." That sort of thing. Instead, what came out was rude to the point of arrogance. It is the statement of someone in power to someone who is powerless.
Granted, "Who cares what you think?" is more specific and pointed, but the general "Who cares?" amounts to the same thing.
But the statement is not always rude. It may also be a weak response to an accusation:

A: You know smoking will kill you, right? Yet you do it anyway.
B: Who cares? We all have to die of something.

That usage suggests a forced insouciance, a resignation in the face of the perceived powerlessness of the person to quit smoking.
It can also be triumphant and expansive, even exultant in a way that is not at all rude:

A: The weather report is saying heavy snow is expected next week.
B: Who cares? You and I will be at the conference in Hawaii that week!

A: In the way you are describing it, its usage varies, from bluntly honest to rude and careless. I have never heard it used politely.

A: It is sarcastic and caustic.
Whether it is impolite and disrespectful would depend on the situation and relationship between the mutual communicants. However, being sarcastic, it will have an object of scorn in any situation - as illustrated in the following hypothetical situations.
Case 1: Object of scorn = PotUS

PotUS: AlQaeda is slipping into the US thru the UK.
      PMoGB: Who cares.

Case 2: Object of scorn = the stupid stain

Your GF: Oh sh--enandoah, I've stained my dress with such a lovely wine.
      Duchess of Cambridge: Who cares. Let's pretend it's not there.
      Your GF: Yes, who cares.
        I'll certainly keep this chateau margaux stain as a vintage souvenir.

Case 3: Object of scorn = someone who originally said about the 47%.

Chris Christie: Someone said 47% will never change their mind.
        Who cares? I do. I do care for that 47%.
      His supporters: {cheering}

Case 4: Object of scorn = public safety

Lindsay Lohan: I am getting arrested too many times a day.
      Paris Hilton: Who cares. Let's have a party.

A: When, "who cares" implies "I don't care." It's rude because it doesn't validate the other person's point. Since it is typically used rhetorically, it implies "everyone" agrees with you and "no one" agrees with the other person, and offers no real chance for a discussion.
"Who cares" can also be used more sensitively to mean "nobody cares" or "why do you care?" when trying to help someone not take a situation too seriously-- as in the example below in the comment by JR.

A: Robusto's response is fantastic and very informative, but I noticed that it failed to answer your question directly in relation to the two scenarios you shared. So, let's see...
In the case of the first conversation, "who cares?" is used in a way that is to my mind reflective of a dismissive, arrogant, and disrespectful disposition. And it's unprofessional to say the least. The fact that you came here in the first place to ask about it already implies that this phrase was used in a manner that made you uncomfortable, which would be consistent with my assessment. I would say that your discomfiture is warranted. I myself would be wary of someone who expresses himself this way about the needs and concerns of clients in a professional environment.
He could have said something like, "We don't have the resources to address the needs of 300 clients. They're going to have to endure for now. We'll revisit this issue if and when those resources become available." But this requires a little more patience, a bit more intellectual cohesiveness, and a degree of respect for both the clients and those present. The dialog you've shared lacks all of these. So there's that.
In the case of the second dialog, "who cares?" implies a complete lack of concern for certain social mores. It also implies a lack of concern for what others think, feel, or believe about this particular behavior. He wants to be free to pick his nose without being bothered about it, so he very clearly states his position so as to cut-off any further debate, "Who cares?" That is to say, "You're the only one that seems to care, so I'm not about to change what I see as a perfectly innocuous behavior just for you." So, the use of the phrase in this particular context means he wants you to back off and drop the subject. It's not open for discussion. He'd rather you look the other way if he's got his fingers up his nose rather than watch you make faces, look horrified, and tell him where and when he should have his fingers up his nose. It's possible that he has dealt life-long with tormenting sinus issues that have ultimately driven him leagues beyond caring what people think about where, when, and how he deals with his sinuses.
This does not necessarily imply arrogance or disrespect--he may be quite the team player and he may otherwise show respect to his peers. He may deal with a concern such as that posed in the first dialog that demonstrates a degree of respect. On the other hand, the speaker in the first dialog may be horrified to be caught with his fingers up his nose and immediately rush off to the bathroom without another word.
So both uses of the phrase imply a degree of disregard, but in very different ways. The first is a clear breach of professionalism while the latter is more the result of a clash of cultural and/or personal values.

A: Would probably only use "who cares" with subordinates, and not with people ranked higher than me in the workplace.   Using with leadership is a little "turnoffish".
Its use also reflects arrogance, so be careful.


text:
Q: Bootstrap complex form layout for combined vertical/inline fields I'm very new to Bootstrap but growing fast in my skill and also appreciation for it. I have a need to build a fairly complex page that will contain a lot of form elements, including multiple address fill-in components. I've attached here an image of the basic design that I am aiming for, and can't seem to achieve it with the basic form design elements available to me. I feel like my approach is getting "out of control" in the sense that I've got too many nesting levels and not enough understanding of what I'm actually doing. So rather than post the code I've got so far, can anyone give me a simplified example of how my design might be achieved?

My dotted-line rectangles represent the fact that my page should have a two-column display, with most of the form elements off to the wider RH side. And then, within that column, my form has some additional levels of complexity. There are many additional form elements that I'm not even showing here, and that's my main reason for wanting to design it this way--because I need to save on vertical screen real estate as much as possible.
Thanks for your help.

A: You should use http://getbootstrap.com/css/#grid for this.
A simple sample from me. Hope this will help you understand the concept.

            Left side for labes

            Right side for forms

                    longer forms

                    shorter forms

                    shorter forms

                    shorter forms

                    shorter forms

    Right panel with instructions

A: Certain types of forms are complicated with and without Bootstrap. There is no complete out of the box solution for your form. You would combine Bootstrap with custom CSS and use nesting. The "easiest" way is to do each chunk, indent, comment and so forth. Be very detail oriented.
This is an example of the more annoying section of the form image you have, which is three nested columns inside the second column. I adjust all my forms that are similar to this to use percentage gutters inside the nested .form-group (which acts like a .row) as the 30px gutter for this is too big. Understanding the grid system, not just using it, will help you get more out of Bootstrap.

DEMO: https://jsbin.com/sejemi
CSS:
/* ---- text-align right the .control-label until 699px MAX width -----*/
@media (max-width:767px) {
    .form-custom .control-label { text-align: right }
}

@media (max-width:699px) {
    .form-custom .control-label {
        width: 100%;
        text-align: left;
    }
    .form-custom .payment-inputs { width: 100% }
    .form-custom .submit-form { margin-left: 0 }
}

/* ----------- adjusted nested columns grid and gutters ----------- */
.form-custom .form-group [class*="col-"] .form-group [class*="col-"] {
    padding-left: 1%;
    padding-right: 1%;
}
.form-custom .form-group [class*="col-"] .form-group {
    margin-left: -1%;
    margin-right: -1%;
}
.form-custom .form-group [class*="col-"] .form-group [class*="col-"]:not(:last-child) { margin-bottom: 5px }

@media (min-width:768px) {
    .form-custom .form-group [class*="col-"] .form-group [class*="col-"]:not(:last-child) { margin-bottom: 0 }
}

HTML

   <form class="form-horizontal form-custom">

         Words Go Here

               Line 1
               <input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon2">

                     City
                     <input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon2">

                     State
                     <input type="text" class="form-control" placeholder="State" aria-describedby="sizing-addon2">

                     Zip
                     <input type="text" class="form-control" placeholder="Zip" aria-describedby="sizing-addon2">

            <button type="submit" class="btn btn-default">Button</button>

   </form>

A: you should look into bootstrap horizontal forms: http://getbootstrap.com/css/#forms-horizontal
heres a demo of what youre looking for using bootstrap horizontal forms: http://jsfiddle.net/swm53ran/31/ (this demo also shows the responsive capabilities of bootstrap)
essentially, you want to combine bootstraps grid system with bootstraps horizontal forms.

  <form class="form-horizontal">

      Email

        <input type="email" class="form-control" id="inputEmail3" placeholder="Email"/>

  </form>

    Some other Elements and Instruction Goes Here

hope this helps!

A: If you want to combine vertical and inline groups you should try the following hope it helps

        <form class="form-horizontal" role="form" method="POST">

                Location Address

 Line 1

                    <input type="text" class="form-control" aria-describedby="basic-addon1" name='line1'>

 Line 2

                    <input type="text" class="form-control" aria-describedby="basic-addon1">

 PO Box

                    <input type="text" class="form-control" aria-describedby="basic-addon1">

 City

                        <input type="text" class="form-control" aria-describedby="basic-addon1">

 State

                        <input type="text" class="form-control" aria-describedby="basic-addon1">

 Zip

                        <input type="text" class="form-control" aria-describedby="basic-addon1">

        </form>

Here is the second column

You can see the result here http://jsfiddle.net/a2Lech1u/3/


text:
Q: Green Arrow over class icon (Android Studio) What is the green right arrow over the class icon in the project navigator sidebar in android studio indicate? What does the red left arrow indicate? I'm new to the IDE and just want to get a better understanding.

A: Here is a link to the all the icons and there meaning on the ItelliJ site:
http://www.jetbrains.com/idea/help/symbols.html
The green arrow denotes a Java class that contains declaration of the main() method.
The green and red arrow denote a test case.


text:
Q: How to integrate OAuth with Azure B2C in Spring MVC? I have to integrate OAut, Azure AD B2C for my existing spring mvc application.
Appreciate any help on implementing the base.

A: This sample to Java Spring MVC web app that authenticates users with Azure AD B2C
describes how to use Azure AD B2C Spring Boot Starter client library for Java to sign in users into your Azure AD tenant . It also makes use of Spring Oauth2 Client and Spring Web boot starters.
You need to Register the app in azure ad b2c,
Add the ,dependencies required in your pom.xml file,
Add  the properties in application.yml using the values you created earlier in app registration.
You can follow further steps in detail  for registration according to starter library
main Reference:
GitHub - Azure-Samples -java-spring-tutorial


text:
Q: Disable vibrancy for every NSView Inside an NSPopover, some subviews (e.g., labels, push buttons) have vibrancy enabled automatically. This makes my app looks very bad when the content behind the popover is in dark colors, unless the user turns on "reduce transparency" in System Preferences. If I subclass the content view of the popover, and set allowsVibrancy to false, it makes the entire popover translucent, which looks better. However, I think my app looks the best when vibrancy is disabled entirely.
My question is, how do I disable vibrancy for all views, without subclassing each of NSView subclasses?

A: You could set your popover to use a solid color with this trick:
How to change NSPopover background color include triangle part?

A: You can accomplish this by setting the appearance of the Popover (or any other view you want to make sure is non-vibrant) to have the NSAppearanceNameAqua appearance. e.g.
popover.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
Otherwise, by default, popovers will have the VibrantLight appearance.


text:
Q: Jar file from Jpa code doesn't work I've developed a simple code that displayes employee name by using Jpa's one of CRUD operations(find) on entity classes "Employee"& "Department" it worked properly while running the code , but the real problem came when I created a jar file from the application, an exception appeared from the  jar file , I wrote the exception in a txt file
Here is the Employee class
    package com.tutorialspoint.eclipselink.entity;

    import java.util.*;
    import javax.persistence.*;

    @Entity
    public class Employee {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int eid;

    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Date dop;

    private String ename;
    private double salary;
    private String deg;

    @OneToOne(targetEntity = Department.class)
    private Department dept;

    @OneToMany (targetEntity = Staff.class)
    private ArrayList<Staff> staffs;

    public Employee(int eid, String ename, double salary, String deg) {
       super( );
       this.eid = eid;
       this.ename = ename;
       this.salary = salary;
       this.deg = deg;
    }

    public Employee( ) {
         super();
    }

    public Date getDop() {
         return dop;
    }

    public void setDop(Date dop) {
         this.dop = dop;
    }

    public int getEid( ) {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    public String getEname( ) {
        return ename;
    }

    public void setEname(String ename) {
       this.ename = ename;
    }

    public double getSalary( ) {
       return salary;
    }

    public void setSalary(double salary) {
       this.salary = salary;
    }

    public String getDeg( ) {
         return deg;
    }

    public void setDeg(String deg) {
        this.deg = deg;
    }

    public ArrayList<Staff> getStaffs() {
        return staffs;
    }

    public void setStaffs(ArrayList<Staff> staffs) {
        this.staffs = staffs;
    }
    }

and here is the class that displays employee name and degree
    public void findEmployee(){
    try{
        EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
        EntityManager entitymanager = emfactory.createEntityManager();
        Employee employee = entitymanager.find( Employee.class, 204 );
        JOptionPane.showMessageDialog(null, employee.getEname()+
        "=>"+employee.getDeg());

        }catch(Exception ex){
              JOptionPane.showMessageDialog(null,ex.getMessage());
              displayMsg(ex.getMessage());
         }
        }
    public void displayMsg(String msg){
    // i made this method to display the exception in a txt file
        File f = new File("E:\\bug2.txt");
        FileWriter fw = new FileWriter(f);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(msg);
        pw.flush();pw.close();

    }

and here is the exception
"
Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [Eclipselink_JPA] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Exception [EclipseLink-1] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The attribute [teacherSet] is not declared as type ValueHolderInterface, but its mapping uses indirection.
Mapping: org.eclipse.persistence.mappings.ManyToManyMapping[teacherSet]
Descriptor: RelationalDescriptor(com.tutorialspoint.eclipselink.entity.Clas --> [DatabaseTable(CLAS)])
Exception [EclipseLink-1] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The attribute [clasSet] is not declared as type ValueHolderInterface, but its mapping uses indirection.
Mapping: org.eclipse.persistence.mappings.ManyToManyMapping[clasSet]
Descriptor: RelationalDescriptor(com.tutorialspoint.eclipselink.entity.Teacher --> [DatabaseTable(TEACHER)])
Exception [EclipseLink-1] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The attribute [staffs] is not declared as type ValueHolderInterface, but its mapping uses indirection.
Mapping: org.eclipse.persistence.mappings.ManyToManyMapping[staffs]
Descriptor: RelationalDescriptor(com.tutorialspoint.eclipselink.entity.Employee --> [DatabaseTable(EMPLOYEE)])
Runtime Exceptions:
--------------------------------------------------------- "
so what can be done?? knowing that the program works well when running the code from IDE but this exception happens when i built it and created jar file and ran the jar file

A: Exceptions that involve interfaces like ValueHolders and indirection is most likely a case of problems due to entity weaving.
Entity weaving is a process of modifying the compiled entities' bytecode so that they implement more interfaces and add new methods such that they can handle things like indirection and lazy-loading, among other features.
Is your IDE Oracle JDeveloper? It is one of the IDEs that, by default, have a run configuration that does this automatically, so that your entities work correctly. This can be configured in other IDEs in a similar manner - by adding -javaagent:<path to eclipselink JAR> as a program argument (or Java Option in some IDEs). Check this blog post for some quick info.
It might the be case in your deployment that Eclipselink's dynamic (runtime) weaving has failed (or is incomplete for some reason). Perhaps you should consider static weaving before the entities are packaged into the deployment artifact.
More info on doing so here: https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Weaving/Static_Weaving

A: thanks , i found out the problem , it was in declaring the ArrayList of staff , it has a problem when I persist Collection declared as ArrayList or HashSet , I should declare it as the super interface eg Set or List ,so I modified it to
  @OneToMany (targetEntity = Staff.class)
  private List<Staff> staffs;

so, it worked very well and when I built the jar file it worked without any problems


text:
Q: Cant Retrieve more than one collection in Flutter from cloud firestore Hy Guys what I am trying to do is to retrieve 2 collection documents from Firestore database and display into my flutter my code is:
Future<QuerySnapshot> getData() async {
    var firebaseUser = await FirebaseAuth.instance.currentUser();
    return await Firestore.instance
        .collection("user")
        .where("email", isEqualTo: firebaseUser.email)
        .getDocuments();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return FutureBuilder(
      future: getData(),

that allow me to retrieve data from a specific user but I have another form called "shippingAddress" which create collection as below:
void createRecord() async {
    await databaseReference.collection("shippingAddress").add({
      'alias': '$alias',
      'shippingName': '$shippingName',
      'shippinglastName': '$shippinglastName',
      'street': '$street',
      'streetNumber': '$streetNumber',
      'zipNumber': '$zipNumber',
      'phoneNumber': '$phoneNumber',
      'textMessage': '$textMessage',
      'totalQuantity': '$totalQuantity',
      'totalWeight': '$totalWeight',
    }).then((value) {
      print(value.documentID);
    });
  }

then I have to retrieve also the above collection but I dont know how... because in the same screen I retrieve "user" collection to display only data from a specific user and I need also to retrieve "shippingAddress" collection because in such collection there are other data to be displayed
for example If I retrieve
${snapshot.data.documents[index].data["email"]} or ${snapshot.data.documents[index].data["name"]}

that I have got into signup form it works and into my widget it show the email or name but if I want for example retrieve:
${snapshot.data.documents[index].data["alias"]}

that is create into "shippingAddress" collection I cant get them

A: I have got myself the solution.
First of all getData from existing user:
final databaseReference = Firestore.instance;

  Future<QuerySnapshot> getData() async {
    var firebaseUser = await FirebaseAuth.instance.currentUser();
    return await Firestore.instance
        .collection("user")
        .where("email", isEqualTo: firebaseUser.email)
        .getDocuments();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getData(),
      builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return ListView.builder(
            itemCount: snapshot.data.documents.length,
              itemBuilder: (BuildContext context, int index) {
                return Column(
                    children: <Widget>[
                    Stream(),

and call a Stream Builder with other collection:
lass Stream extends StatefulWidget {
  @override
  _StreamState createState() => _StreamState();
}

class _StreamState extends State<Stream> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('shippingAddress').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Text('Loading data please Wait');
        return Column(
          children: <Widget>[
            Container(
              height: 1000,
              child: ListView.builder(
                itemCount: snapshot.data.documents.length,

thats all!


text:
Q: Why the statement (foo.__init__ is foo.__init__) return false Code:
class Foo(object):
    pass

foo = Foo()
foo.__init__ == foo.__init__ #return true
foo.__init__ is foo.__init__ #return false

I can understand foo.__init__ == foo.__init__ returns True.
Why foo.__init__ is foo.__init__ return False?


text:
Q: Casino/House bankroll for Blackjack Given a maximum bet size of "x" in blackjack, how many maximum bets should the house keep in its bankroll/account to prevent it ever realistically losing all its money against players playing perfectly? (not including card counting/other factors)
For arguments sake, assume the house probability of winning is 50.5% per game.

A: If you treat this as $\pm1$ random walk where the independent probability of $+1$ steps is $p$ and of $-1$ steps is $1-p$ then it is a known result that with $p \lt \frac12$ the probability of the sum of the steps ever reaching some positive integer $n$ is $\left(\dfrac {p}{1-p}\right)^n$
Here $p =0.495$.  You need to quantify  realistically: if you want the probability or risk of ever losing a net $n$ or more to be less than some $r$ then you need $r \lt \left(\dfrac {p}{1-p}\right)^n$  and so want $n > \dfrac{\log(r)}{\log(p) - \log(1-p)}$
For some illustrative values of the risk $r$ (the first shown is $1\%$ and the fifth $0.0001\%$) you get suggested values of $n$. You can round down if you want the risk of strictly exceeding these positions to be $r$ or less.
  r           n
0.01        230.25
0.001       345.38
0.0001      460.50
0.00001     575.63
0.000001    690.75


text:
Q: Display emojis stored in Algolia I am using Algolia to do autocomplete on cities around the world. I want to display the emoji flag for the country that it's in alongside it in suggested results, however when trying to add the flags in the algolia dashboard it turns them into little diamonds etc. Is there a way to make this work?

A: I would rather add the flag at display time, instead of indexing the emoji in Algolia (the small diamonds you're seeing is a limitation of Algolia's emoji highlighting).
templates: {
  suggestion: function(suggestion) {
    return '<i class="flag ' + suggestion.countryCode + '"></i> ' +
      suggestion._highlightResult.name;
  }
}


text:
Q: CONTEXT-Index on Oracle - How does it works? i have a datatbase in Oracle with a table, whichs holds about 700.000 rows.
Now i have set indexes(Context) for columns i want to search for(First,Last and Other_Names).
If i run the Statement below, it takes about 45sec.
But if i change the OR to an AND then it takes just 0.187sec.
So what is happening here?
And how can i solve it (I need the or Operator)
Thx
SELECT score(1),FIRST_NAME,LAST_NAME,OTHER_NAMES
FROM VIEW_NAMEN
WHERE (CONTAINS(LAST_NAME,'Merkel',0) > 0
  AND CONTAINS(FIRST_NAME,'Angela',1) >0)
   OR (CONTAINS(OTHER_NAMES,'%Angela% AND %Merkel%',2)>0) ;

A: First of all, you should use parentheses when using ANDs and ORs to ensure that they are being performed as you expect.  Your WHERE clause is equivalent to:
WHERE ( CONTAINS(LAST_NAME,'Merkel',0) > 0
       AND CONTAINS(FIRST_NAME,'Angela',1) >0 )
   OR (CONTAINS(OTHER_NAMES,'%Angela% AND %Merkel%',2)>0)

Which may or may not be what you want.
My guess is that the final condition CONTAINS(OTHER_NAMES,'%Angela% AND %Merkel%',2)>0 is much slower to process than the other two (it is more complex).
When you change the OR to AND (and so parentheses are not required) then first the query will look for people whose last name contains 'Merkel'.  Maybe only a few hundred.  Then it filters those 500 (say) for first name contains 'Angela'.  Maybe there are only 10 of these.  Finally it applies the other_names condition, just to those 10 rows.  If that condition takes 0.00006 seconds per row to evaluate, then it will take 0.00006*10 = 0.0006 seconds.
But with the OR, you are now looking for people whose last name is Merkel and first name is Angela OR whose other names contains Angela and Merkel.  So the last condition has to check all the people whose first name and last name isn't Angela Merkel, i.e. nearly 700,000.  And this will take about 700,000*0.00006 = 42 seconds.
OK, that's what may be happening.  As for how to make CONTAINS(OTHER_NAMES,'%Angela% AND %Merkel%',2)>0 go faster, I'm afraid I don't know!


text:
Q: Trying to use php include in an errordocument page but it doesn't work in different directories I think I found that when I have an errordocument custom error page, include does not always work because the include requires a directory and the page that has the error may be in a different directory.
directory1/directory2/thispagecausesa404error.php
directory1/thispagecausesa404error.php
If I have include includepage.php; in my errordocument page, then it won't work.
I resolved to adding include_once $_SERVER['DOCUMENT_ROOT'].'/includepage.php'; to the errordocument page, which solves the problem, but I suspect that I am doing something wrong or not seeing the proper way to have a flawless include on an error page.
What am I doing wrong?

A: I'd recommend never relying on DOCUMENT_ROOT being set correctly. Instead, use a relative path from the current script via the __DIR__ magic constant, eg
include __DIR__ . '/relative/path/from/this/script/to/includepage.php';

The path can also contain parent directory traversal via ../ if required, eg
include __DIR__ . '/../../some/dir/includepage.php';


text:
Q: Using appendText property of Text Area returns error I have a textArea in my main application as:
<s:TextArea id="textAreaLog" visible="false" height="100%" width="100%"/>

I have another mxml file in which I access that textArea as:
import mx.core.FlexGlobals;

and then:
mx.core.FlexGlobals.topLevelApplication.textAreaLog.text = "Testing...\n;"

Above code works fine i.e. the string "Testing..." gets into the textAreaLog. But upon using appendText property of textArea as:
mx.core.FlexGlobals.topLevelApplication.textAreaLog.appendText = "Testing...\n;"

following error arises:
   Error #1037: Cannot assign to a method appendText on spark.components.TextArea.

Same error occurs if I use  instead of  where,
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"

Any idea of how to resolve this problem. I am able to append text via following command which does not seem a good option or is it? Won't following line of code by inefficient if size of text in the Text Area increases considerably?
mx.core.FlexGlobals.topLevelApplication.textAreaLog.text += "Testing...\n;"

A: try this:
mx.core.FlexGlobals.topLevelApplication.textAreaLog.appendText("your text");

More information about the appendText() method:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/supportClasses/SkinnableTextBase.html#appendText()
Good luck,
Rob


text:
Q: Is there a way to attach a 3rd value in Python dictionaries? This may be a stupid question, and I believe there is a good chance I am taking the completely wrong approach to solving my problem, so if anyone knows a better way, please feel free to correct me / point me in the right direction.
I'm trying to make a basic quiz program in Python for fun and I can't seem to find a good way to actually both call the questions with their answers AND store what the correct answer should be. Ideally I'd like to shuffle the answers within the question around as well so for example the answer to #1 is not always "A" as well, but that's going a step too far at the moment.
Anyway, I figured a dictionary could work. I'd do something like this:
test = {
    '1':    "What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n", #A
    '2':    "What is 2+2?\nA) 2\nB) 4\nC) 1\nD) None of the above.\n\n", #B
    '3':    "What is 3+3?\nA) 2\nB) 11\nC) 6\nD) None of the above.\n\n", #C
    '4':    "What is 4+4?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n", #D
    '5':    "What is 5+5?\nA) 2\nB) 11\nC) 10\nD) None of the above.\n\n", #C
    '6':    "What is 6+6?\nA) 2\nB) 12\nC) 1\nD) None of the above.\n\n", #B
    }

answer = raw_input(test['1'])

Which I could use to easily print out questions either in order or randomly with a little modification. However, I have no way of actually attaching the correct answer to the dictionary which means I'd have to do something like make ridiculous amounts of if statements. Does anyone know a solution? Is there a way to add a 3rd value to each dictionary entry? A work-around I'm completely overlooking? Any help would be greatly appreciated.

A: Make the dictionary's values into tuples:
'1': ("What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n", 'A')

You can then access the question through test['1'][0] and the answer through test['1'][1].

A: It looks like you're laying out your data structure wrong. Instead of a dictionary of tuples or lists as your other answers are suggesting, you SHOULD be using a list of dictionaries.
questions = [
    {'question':"What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n",
     'answer':"#A"},
    {'question':"What is 2+2?\nA) 2\nB) 4\nC) 1\nD) None of the above.\n\n",
     'answer':"#B"},
    ...}

This will let you iterate through your questions with:
for q in questions:
    print(q['question'])
    ans = input(">> ")
    if ans == q['answer']:
        # correct!
    else:
        # wrong!

If you still need numbers, you could either save number as another key of the dictionary (making this kind of like rows in a database, with number being the primary key):
{'number': 1,
 'question': ...,
 'answer': ...}

Or just iterate through your questions using enumerate with the start keyword argument
for q_num, q in enumerate(questions, start=1):
    print("{}. {}".format(q_num, q['question']))
    ...

A: Put the value into a list as in
test = {
    '1':    ["What is 1+1?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n", '#A' ]
    '2':    ["What is 2+2?\nA) 2\nB) 4\nC) 1\nD) None of the above.\n\n", '#B' ]
    '3':    ["What is 3+3?\nA) 2\nB) 11\nC) 6\nD) None of the above.\n\n", '#C' ]
    '4':    ["What is 4+4?\nA) 2\nB) 11\nC) 1\nD) None of the above.\n\n", '#D' ]
    '5':    ["What is 5+5?\nA) 2\nB) 11\nC) 10\nD) None of the above.\n\n", '#C' ]
    '6':    ["What is 6+6?\nA) 2\nB) 12\nC) 1\nD) None of the above.\n\n", '#B' ]
    }

Then access it as
question = raw_input(test['1'][0])
answer = raw_input(test['1'][1])

A: Ditch the dictionary and let python do more of the work for you. You can represent each question/answer group with a list where the first item is the question, the last item is the answer and all of the items in between are multiple choice answers. Put those in another list and its easy to shuffle them up.
import string
import random

# a list of question/choices/answer lists
test = [
    # question       choices....                          answer
    ["What is 1+1?", "2", "11", "1", "None of the above", 0],
    ["What is 2+2?", "2", "11", "4", "None of the above", 2],
    # ... more questions ...
]

# shuffle the test so you get a different order every time
random.shuffle(test)

# an example for giving the test...
#   'enumerate' gives you a count (starting from 1 in this case) and
#   each test list in turn
for index, item in enumerate(test, 1):
    # the question is the first item in the list
    question = item[0]
    # possible answers are everything between the first and last items
    answers = item[1:-1]
    # the index to the real answer is the final item
    answer = item[-1]
    # print out the question and possible answers. 'string.uppercase' is a list
    # of "ABC...XYZ" so we can change the index of the answer to a letter
    print "%d) %s" % (index, question)
    for a_index, answer in enumerate(answers):
        print "    %s) %s" % (string.uppercase[a_index], answer)
    # prompt for an answer
    data = raw_input("Answer? ")
    # see if it matches expected
    if data == string.uppercase[answer]:
        print "Correct!"
    else:
        print "No... better luck next time"


text:
Q: Problem with reading and writing to a file at the same time I am trying to read and write the file at the same time in C. I can write to the file but couldn't read from the file. Any suggestions?
#include <stdio.h>
int main()
{
    char *str = "C programming language";
    char str1[100];
    FILE *fptr = fopen("Output.txt", "r+");
    if (fptr == NULL)
        printf("Could not open file!");
    fputs(str, fptr);

    fgets(str1,100,fptr);
    fclose(fptr);
    printf("%s", str1);
    return 0;
}

Please assume that the output.txt file already exists on my computer.

A: Quoting http://www.cplusplus.com/reference/cstdio/fopen:

For files open for update (those which include a "+" sign), on which
  both input and output operations are allowed, the stream shall be
  flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a
  reading operation that follows a writing operation. The stream shall
  be repositioned (fseek, fsetpos, rewind) before a writing operation
  that follows a reading operation (whenever that operation did not
  reach the end-of-file).

A: After you've done the write, you should seek to beginning of the file. For that call rewind().
Here's the corrected code:
#include <stdio.h>
int main()
{
    char *str = "C programming language";
    char str1[100];
    FILE *fptr = fopen("Output.txt", "r+");
    if (fptr == NULL)
        printf("Could not open file!");
    fputs(str, fptr);

    rewind(fptr); // seek to beginning

    fgets(str1,100,fptr);
    fclose(fptr);
    printf("%s", str1);
    return 0;
}

A: You will need to re-position the offset to beginning to read that string.
After your write, the pointer is at the offset which is past the string your wrote.
#include <stdio.h>
int main()
{
    char *str = "C programming language";
    char str1[100];
    FILE *fptr = fopen("Output.txt", "r+");
    if (fptr == NULL)
        printf("Could not open file!");
    fputs(str, fptr);

    fseek(fptr, 0, SEEK_SET); // add this
    fgets(str1,100,fptr);
    fclose(fptr);
    printf("%s", str1);
    return 0;
}

./main.out
C programming language


text:
Q: Visualizar Miniaturas Tenho uma página em PHP onde contém WHILE que deveria mostrar imagem em miniatura conforme as imagens que tenho no mesmo diretorio.
    <?php
while($fetch = mysql_fetch_assoc($select)){
 ?>

            <input type="checkbox" value="">
            <?php echo $fetch['nickname']; ?>
           <?php echo $fetch['sala']; ?>
           <?php ""?>
           <input type="image" src="LOG_29710.png" data-toggle="modal" data-target="#myModal<?php echo $fetch['id']; ?>">
           <?php echo $fetch['quote']; ?>
           <?php echo $fetch['aprovado']; ?>

     ?>

O arquivo thumb.php é quem faz todo o trabalho para gerar a miniatura. Porem, as imagens não aparecem, não gera erro mas no campo da imagem/miniatura, fica em branco. Se eu setar a imagem, fora do thumb.php, a imagem original aparece. Tenho um outro projeto que funciona certinho, usei exatamente o mesmo modelo, mas não funciona.
Segue o trecho do thumb.pbp
function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

$filename = $_GET['img'];
$percent = 0.10;

//Lê o formato do conteudo da imagem
$mime = mimeType($filename);

if (strpos($mime, 'image/') !== 0) {
    die('Este arquivo não é uma imagem');
}

//Remove o prefixo image/
$mime = substr($mime, 6);

//Remove `x` de x-jpeg, talvez ocorram em alguns servidores antigos
$mime = str_replace('x-', '', $mime);

switch ($mime) {
    case 'jpeg':
        $image = imagecreatefromjpeg($filename);
    break;
    case 'png':
        $image = imagecreatefrompng($filename);
    break;
    case 'gif':
        $image = imagecreatefromgif($filename);
    break;
    default:
        die('Formato não aceito');
}

// Cabeçalho que ira definir a saida da pagina
header('Content-type: image/jpeg');

// pegando as dimensoes reais da imagem, largura e altura
list($width, $height) = getimagesize($filename);

//setando a largura da miniatura
$new_width = 120;
//setando a altura da miniatura
$new_height = 100;

//gerando a a miniatura da imagem
$image_p = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

//o 3º argumento é a qualidade da imagem de 0 a 100
imagejpeg($image_p, null, 50);
imagedestroy($image_p);


text:
Q: Large result sets with Oracle JDBC, can I turn cursor fetching off? (fetch size issue) I have a case where i need to efficiently load about ~1 million rows into memory for processing. I am using oracle and plain JDBC for this.
If I do not set the fetch size, the oracle driver default of 10 is used meaning it will require 100k round trips which makes performance super inefficient. If I up the fetch size to something very large, such as 500k or 1m, the data is loaded in about 5 seconds.
Unfortunately I can't set the fetch size to something like INT_MAX because the oracle driver pre-allocates the buffer based on the fetch size.
What I really want is a way to force JDBC to simply get all of the rows and not use a cursor or do any incremental fetching. I would like to do that in the most memory efficient way possible.
Is there a way to tell oracle to just get all the data and don't do any fetching?

A: The 12 driver allocates 15 bytes per column per row in the fetch size for bookkeeping plus the actual data size. So if you set the fetch size to 1G the 12 driver will allocate 15GB for bookkeeping plus whatever the actual data is. So depending on how much memory you have you can set the fetch size to whatever you have the memory to support.
Pre 12 the drivers allocated much, much more memory so the fetch size would have to be much smaller.
There's no way to tell the driver to just fetch all the rows in one round trip.
Edit 2017-03-10: We have tested with up to 2G rows and the recently released 12.2 drivers handle this fine with a FORWARD_ONLY result set. They will handle up to 1,802,723,000 rows with a SCROLL_INSENSITIVE result set. That is an expected limit. Sort of obviously this is with a huge machine and a ginormous heap.


text:
Q: Include req.http.referer in Varnish cached pages I have a site that has traffic spikes from only a few sources. This site also needs to be able to show content to a user by guessing if they've just arrived on the site using PHPs $_SERVER["HTTP_REFERER"].
Is it possible to include the value of req.http.referer in the varnish cache so that this behavior is on more of an individual user basis? I believe that some users are being showed the wrong content because of another user caching content with a different referrer value.

A: If you want the cache to be different on all referers possible the http protocols Vary-header is the solution for you. That will practically kill your cache hitrate if your traffic is not very uniform with referers from very few unique URLs.
What I think is a better solution is to remove the logic of guessing who is a new user from the php layer and add it to varnish. This can be done by setting a custom header to the request in the vcl_recv and then using that header to hash in vcl_hash by adding something like this to vcl_recv
if ((req.http.referer ~ "www.newuserhost1.com" || req.http.referer ~ "www.newuserhost2.com") &&
    req.url == "/") {
       req.http.X-New-User = 1;
}

And adding this to vcl_hash
 hash_data(req.http.X-New-User);

When the user reaches your backend you can check the value of X-New-User from there instead of the referer.

A: The HTTP specification has the solution for this. The Vary response header indicates which request headers was taken into account when producing the content.
Add a "Vary: Referer" header to the backend responses, and Varnish will serve the correct variant to each client.


text:
Q: Given irreducible transition matrix $P$, why does the matrix $(P−I|\mathbb{1})(P−I|\mathbb{1})^T$ have full rank? Given irreducible transition matrix $P$, why does the matrix $(P−I|\mathbb{1})(P−I|\mathbb{1})^T$ have full rank?
I know this is partially due to the fact that since $P$ is irreducible, there exists an eigenvector $\mathbb{v}$ with eigenvalue 1, where $\mathbb{v}$ is in fact the stationary distribution, but I am not sure exactly how.

A: Let $P\in Mat_{n \times n}$ be an irreducible transition matrix.
Since the rows of $P-I$ sum to $0$ (the rows of $P$ sum to $1$ and the rows of the identity matrix sum to $1$), the $rk(P-I)\leq n-1$. This implies that $\exists$ an eigenvector $v$ such that $vP=v$.
Continuing with the proof, we find that if $P$ is irreducible, then $\exists$ a unique solution to $\pi P=\pi$ with $\sum_x \pi_x=1$ and $\pi_x>0 \quad \forall x$. This is the stationary distribution of the transition matrix.
Since $\pi P=\pi$, $\quad\!\!\pi(P-I)=0$. But since we also have the restriction that $\sum_x \pi_x=1$, we can add this restriction and we have $\quad\!\!\pi(P-I|1)=\begin{pmatrix}
0&0&\cdot\cdot\cdot&0&1
\end{pmatrix}$ where $(P-I|1)$ is the matrix $P-I$ with the last column replaced by $1$'s.
Since $\pi$ is unique, we have that $\pi=\begin{pmatrix}
0&0&\cdot\cdot\cdot&0&1
\end{pmatrix}(P-I|1)^{-1}$. Thus, because $(P-I|1)$ is invertible, it must have full rank. Also, since $\det(A)=\det(A^t)$, $\quad\!\! (P-I|1)^t$ is also invertible and has full rank. Since both matrices $(P-I|1)$ and $(P-I|1)^t$ are invertible, their product$(P-I|1)(P-I|1)^t$ must also be invertible.

A: Let $A$ be the $n\times (n+1)$ matrix obtained by attaching
a column of ones to $P-I$, and let $x$ be a row vector
of length $n$ with $AA^T x^T={\bf 0}.$
Then $\| xA\|^2=xAA^Tx^T=0$ so that $xA={\bf 0}.$
This shows that $x$ is an invariant measure for
the Markov chain. But since $P$ is irreducible,
all invariant measures are of the form $\lambda \pi$,
where $\lambda\in\mathbb{R}$ and $\pi$ is the
unique invariant probability measure. Write
$x=\lambda \pi$.
Because of the column of ones, $xA={\bf 0}$ also implies
that $0=\sum_i x_i = \lambda \sum_i \pi_i=\lambda.$
In other words, $x^T={\bf 0}.$
This shows that the matrix $AA^T$ is invertible,
 and hence has full rank, equal to $n$.


text:
Q: Is there a better name for a 'three-dimensional coordinate system'? I am wondering if there is a commonly agreed name for any system that makes use of three coordinates. Something that includes 'geographical coordinate system', 'spherical coordinate system', 'celestial coordinat system' and all the likes.
Or is 'three-dimensional coordinate system' the answer?
thanks!

A: Well, $\mathbb{R}^3$ is sometimes called space, so I suppose you could use spatial coordinate system.  But other than that, I can't think of a name for a coordinate system with three dimensions besides "three-dimensional coordinate system."

A: "3-space" is sometimes used. See:
https://en.m.wikipedia.org/wiki/Three-dimensional_space?wprov=sfla1
Regarding Cartesian coördinates in a 2-space, it is well-known that the x- and y-coördinates are called, respectively, the "abscissa" and "ordinate." Less well-known is that, in a 3-space, the z-coördinate is called the "applicate."
Abscissa, Ordinate and ?? for z-axis?


text:
Q: How to prevent download with same request from AFHTTPRequestOperation?multiple download occurs for same file I am using AFHTTPRequestOperation to download a file from remote server now my problem is AFHTTPRequestOperation starts to download same request multiple time so i want to prevent the download process to execute for same request.
so basically what i want is however if downloadFile: function call multiple time with same request i can prevent the download process to start if any process running with same request already.
following is my code
AFHTTPRequestOperation *operation;
-(void)downloadFile:(NSURL *)videoUrl{

    NSURLRequest *request = [NSURLRequest requestWithURL:videoUrl];

   operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:VIDEO_DIRECTORY_NAME];
    NSString *downloadPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"TEMP_%@",[videoUrl lastPathComponent]]];
    NSString *fullPath = [dataPath stringByAppendingPathComponent:[videoUrl lastPathComponent]];

   // NSLog(@"Full Path For Download Video %@",fullPath);
    NSError *error=[[NSError alloc]init];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];

    if (!fileExists)
    {
        NSLog(@"Full Path For Download Video  Started%@",fullPath);
        [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]];

        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
           // NSLog(@"bytesRead: %lu, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", (unsigned long)bytesRead, totalBytesRead, totalBytesExpectedToRead);
        }];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSError *error;
            if (error) {
                NSLog(@"ERR: %@", [error description]);
            } else {
                CustomAlertView *alert=[[CustomAlertView alloc]init];
                NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];

                //check for Available Space
                if([ALDisk freeDiskSpaceInBytes] >= [operation.response expectedContentLength])
                {

                NSLog(@"Content-lent: %lld", [operation.response expectedContentLength]);
                [alert ShowNotificationInParentView:nil WithTitle:NSLocalizedString(@"Video_title", nil) Message:NSLocalizedString(@"Video_downloaded_succesfully", nil) IsSuperUser:[userDefaults boolForKey:IS_SUPER_USER] TypeOfNotification:ALERT_TYPE_ERROR  IsLoggedIn:YES];
                [assetManager.assetManagerDelegate didAssetManagerSucceedObject:nil ErrorCode:@"" Result:YES ResponseId:VIDEO_DOWNLOAD_RESPONSE_ID];
                }

                else {
                    [alert ShowNotificationInParentView:nil WithTitle:@"Memory Full" Message:NSLocalizedString(@"video_cannot_be_downloaded", nil) IsSuperUser:[userDefaults boolForKey:IS_SUPER_USER] TypeOfNotification:ALERT_TYPE_ERROR  IsLoggedIn:YES];
                    [assetManager.assetManagerDelegate didAssetManagerFailedResponseWithError:[NSError errorWithDomain:@"Memory Full" code:[MEMORY_OUT_OF_STORAGE intValue] userInfo:nil]];

                }
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@", [error description]);
        [assetManager.assetManagerDelegate didAssetManagerFailedResponseWithError:error];
        }];

        [operation start];
    }

}

Please guide me with any suggestion or solution.


text:
Q: Solr Boosting on custom fields Solr Experts,
I am trying to change the score for few of my custom fields through index time/field boosting but doesn't seems to be changing the score. Please help.
These are my custom fields in schema.xml
 <field name="doc_id" type="string" indexed="true" stored="true" omitNorms="false"/>
 <field name="doc_name" type="text_autocomplete" indexed="true" stored="true" multiValued="true" omitNorms="false"/>
 <field name="doc_author" type="text_autocomplete" indexed="true" stored="true" multiValued="true" />
 <field name="modifieddate" type="text_autocomplete" indexed="true" stored="true" multiValued="true"/>
 <field name="doc_content" type="text_autocomplete" indexed="true" stored="true" multiValued="true" omitNorms="false"/>
 <field name="doc_title" type="text_autocomplete" indexed="true" stored="true" multiValued="true"/>
 <field name="doc_description" type="text_autocomplete" indexed="true" stored="true" multiValued="true" omitNorms="false"/>

I posted 3 test docs as below using SolrJ
<?xml version="1.0" encoding="UTF-8"?>
<add>
  <doc>
   <field name="doc_id">7781</field>
   <field name="doc_name" boost="1.5">Cat</field>
   <field name="doc_author">Nsd80</field>
   <field name="modifieddate">11 30</field>
   <field name="doc_content" boost="1.5">Cat life history. Cat life cycle. Cat Foods</field>
   <field name="doc_title">Titled</field>
   <field name="doc_description" boost="1.5">Cat related details</field>
  </doc>
  <doc>
     <field name="doc_id">7782</field>
     <field name="doc_name" boost="2.5">Dog</field>
     <field name="doc_author">Nsd80</field>
     <field name="modifieddate">11 30</field>
     <field name="doc_content" boost="2.5">Dog life history. Dog life cycle. Dog Foods</field>
     <field name="doc_title">Titled</field>
     <field name="doc_description" boost="2.5">Dog details</field>
  </doc>
  <doc>
     <field name="doc_id">7783</field>
     <field name="doc_name" boost="2.7">Cow</field>
     <field name="doc_author">Nsd80</field>
     <field name="modifieddate">11 30</field>
     <field name="doc_content" boost="2.7">Cow life history. Cow life cycle. Cow Foods</field>
     <field name="doc_title">Titled</field>
     <field name="doc_description" boost="2.7">Cow lifecycle</field>
  </doc>
</add>

When I query to find the scores as below,
localhost:8983/solr/select/?q=doc_id:*&fl=*,score

it shows 1.0 as score for all three docs
I was trying to boost them as
localhost:8983/solr/select?defType=edismax&q=doc_description:*Cow*^195

but doesnt seems to be working either
<arr name="doc_description">
<str>Dog details</str>
</arr>
<long name="_version_">1479948142366425088</long>
<float name="score">1.0</float>
</doc>
<doc>

Also tried to elevate as
localhost:8983/solr/elevate?q=doc_id:7781&enableElevation=true&fl=doc_id,score,[elevated]

but result was negative
<result name="response" numFound="1" start="0" maxScore="7.23343">
<doc>
<str name="doc_id">7781</str>
<float name="score">7.23343</float>
<bool name="[elevated]">false</bool>
</doc>
</result>
</response>

My requirement is just to boost the docs to have more scores so that I can retrieve them based on scores. If you look at my xml docs, I have tried field boosting at index time, later tried to boost the docs using edismax (mentioned here) and also a elevation
Can anyone help me with detailed example?


text:
Q: how to iterate ONLY the first tuple in a list of tuples? I don't know if there is a way to find the inside of a tuple of ONLY the first tuple in a list?
list = [(a, b, c, d), (d, e, f, g), (h, i, j, k)]

output:
a
b
c
d

This is what my current loop looks like:
for x in list[0]:

EDIT: edited full question.

A: Input:
_list = [('a', 'b', 'c', 'd'), ('d', 'e', 'f', 'g'), ('h', 'i', 'j', 'k')]

for i in _list[0]:
    print(i)

Output:
a
b
c
d

EDIT:
Maybe you could try the next() function in the standard library. Create an iterator from your list of tuples:
iter_list = iter(_list)

Then just pass it to the next() function:
In: next(iter_list)
Out: ('a', 'b', 'c', 'd')

In: next(iter_list)
Out: ('d', 'e', 'f', 'g')

In: next(iter_list)
Out: ('h', 'i', 'j', 'k')


text:
Q: Understanding numeric data types in functions This is a follow-up to the question on double-float that I posted earlier. I apologize for what's probably a fundamental Lisp concept, but I haven't grasped it yet.
For this problem, I am using GNU CLISP 2.49 (2010-07-07).
Suppose I have the following function, which simply determines square root via Newton's method:
(defun sr (n eps)
  (when (>= n 0)
    (do ((x (/ n 2.0) (/ (+ x (/ n x)) 2.0)))
      ((< (abs (- (* x x) n)) eps)
       x))))

I can call this as follows:
> (sr 2 0.00001)
1.4142157

It's giving me single precision float (the default). Makes sense. Due to the lack of precision, if I make eps too small, it doesn't function properly and goes into an infinite loop:
> (sr 2 0.00000001)
[just sits there...]

If I call it with double precision values, I still get single precision results:
> (sr 2.0d0 0.00001d0)
1.4142157
> (sr 2.0d0 0.00000001d0)
[just sits there...]

But if I redefine my function as follows:
(defun sr (n eps)
  (when (>= n 0)
    (do ((x (/ n 2.0d0) (/ (+ x (/ n x)) 2.0d0)))
      ((< (abs (- (* x x) n)) eps)
       x))))

I then get double precision no matter how I feed it:
> (sr 2 0.00001)
1.4142156862745097d0

And now feeding it a smaller eps works due to the increased precision:
> (sr 2 0.00000001)
1.4142135623746899d0

So my question is: is the precision applied by the function totally driven by the precision I specify in the constants it is using in the arithmetic expressions it contains? And if so, what if there were no constants anywhere in the function? What then determines the precision of the calculations and the result?

ADDENDUM
I just retested this on SBCL 1.0.57-1.fc17 and I get much more expected results, per the documentation that @JoshuaTaylor quoted in the comment.

A: Looks to me like this is an incompatibility of CLISP with the ANSI CL Standard.
The ANSI CL standard requires the result to be the largest type of all arguments:
CL-USER 20 > (/ 2.0d0 2.0)
1.0D0

CLISP gives:
[4]> (/ 2.0d0 2.0)
1.0

This should be a double float.
You can change that in CLISP to standard ANSI CL behavior:
[9]> CUSTOM:*FLOATING-POINT-CONTAGION-ANSI*
NIL
[10]> (setf CUSTOM:*FLOATING-POINT-CONTAGION-ANSI* t)
T
[11]> (sr 2.0d0 0.00001d0)
1.4142156862745097d0

Now it gives back the desired result.
See the CLISP manual: 12.2.4.1. Rule of Float Precision Contagion


text:
Q: Passing components state to query variables inside react-apollo's compose The following React component works correctly, I'm able to query a GraphQL endpoint using Apollo-React. In this specific case I'm using an Apollo-React's compose function, to add several queries in the same component.
I would like to inject dynamically, in the HOC variables field, the userId.
Is there a way to do it ? Because simply calling the function getUser()  doesn't seems to works, I get only a promise.
  class AllCardsScreen extends Component {

    state = {
      query: '',
      userCardsById: [],
      userId:'',
      loading: false,
    };

    getUser = async () => {
    await Auth.currentUserInfo()
      .then((data) => {
        this.setState({ userId: data.attributes.sub});
      })
      .catch(error => console.log(`Error: ${error.message}`));
    };

  render() {

    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.userCardsList}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItem}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          keyboardShouldPersistTaps="handled"
        />
      </View>
    );
  }

 export default compose(

  graphql(ListCards, {
    options: (props) => ({
      fetchPolicy: 'cache-and-network',
      variables: { userId : '18e946df-d3de-49a8-98b3-8b6d74dfd652'}
    }),
    props: (props) => ({
         userCardsList: props.data.userCardsList ? props.data.userCardsList.userCards : [],

    }),
  })

  )(AllCardsScreen);

EDIT:
This is the final working version based also on Daniel suggestion (Thx Daniel), with an API asyncronous call injected inside the HOC Apollo-graphQl enhancer. I had to call the data.props.refetch() function to update the variables value.
 class AuthWrapper extends React.Component {

    state = {
      userId: null,
    }

    async componentDidMount () {
      const data = await Auth.currentUserInfo()
      this.setState({ userId: data.attributes.sub})
    }

    render () {
      return this.state.userId
        ? <AllCardsScreen {...this.state} {...this.props}/>
        : null
    }
  }

class AllCardsScreen extends Component {

    state = {
      query: '',
      userCardsById: [],
      userId:'',
      loading: false,
    };

  componentDidMount() {
    this.props.dataRefetch(this.props.userId)
    SplashScreen.hide();
  }

  render() {

    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.userCardsList}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItem}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          keyboardShouldPersistTaps="handled"
        />
      </View>
    );
  }

 export default compose(

  graphql(ListCards, {
    options: (props) => ({
      fetchPolicy: 'cache-and-network',
      variables: { userId : ''}
    }),
    props: (props) => ({
    userCardsList: props.data.userCardsList ? props.data.userCardsList.userCards : [],
    dataRefetch: (userId) => {
        props.data.refetch({userId})
       },
    }),
  })

  )(AllCardsScreen);

A: The graphql HOC only uses props -- since it's effectively just wrapping the component it's passed, it won't have access to that component's state. There's also not a way to fetch data asynchronously inside the HOC's configuration.
The simplest solution is to just lift the state into either an existing parent component, or a new component that would wrap your existing one. For example:
class WrapperComponent extends Component {
  state = {
    userId: null,
  }

  async componentDidMount () {
    const data = await Auth.currentUserInfo()
    this.setState({ userId: data.attributes.sub})
  }

  render () {
    // May want to render nothing or a loading indicator if userId is null
    return <AllCardsScreen userId={this.state.userId} {...otherProps} />
  }
}

Alternatively, you can create your own HOC to encapsulate the same logic:
function authHOC(WrappedComponent) {
  return class AuthWrapper extends React.Component {
    state = {
      userId: null,
    }

    async componentDidMount () {
      const data = await Auth.currentUserInfo()
      this.setState({ userId: data.attributes.sub})
    }

    render () {
      return this.state.userId
        ? <WrappedComponent {...this.props} userId={this.state.userId} />
        : null
    }
  }
}


text:
Q: Failed automated tests: how to distinguish known and newly introduced bugs? Use case: Fitnesse is used for automated testing of the web site.
SUT (software under test) contains a known bug. Say, we expect that web page contains "Changes saved successfully" string but this string is missing because of the bug. So in Fitnesse, this test case is marked as red.
Suppose, in another test case we expect that web page contains "A user created successfully" string. And it worked just fine until the last test execution. So, now this test case is also marked as red.
So, now we have red light for two test cases: a well known bug and a newly found bug. The problem is they are both marked as red. So when I have a look at test results I can't distinguish which of them are known and new.
Of course, I can compare test history and see the difference between two runnings (with and without a newly created bug).
Or I may not execute a test case with a known bug.
Or I can tune it so that this test case has always been green and change it when the bug is fixed.
But all this is very inconvenient. What I want is to differ two kinds of bugs (a well known bug and new bug) so that:

*

*By looking at test results, I could easily say: this is a new bug and those are old. For example: No bugs - green, Already known bugs - yellow, New bugs - red.

*It is easy to change test case when the bug is fixed.
What are the best strategies for acceptance tests, in general, and Fitnesse, in particular?

A: There's a subtle distinction here: you're talking about tracking test state, not just whether it's a known bug. Good CI systems can help you track a test's state via history, and let you know when it changes state. (Passed yesterday, fails today.) Good CI systems can also resolve false failures so they don't muddy up your history. (I'm thinking specifically of Team City which I've done this in.)
Having a bug against a failing test is another issue. Naming conventions can help, as Barry mentioned. I've also used test framework metadata to help identify existing bugs by marking descriptions in test attributes or properties.

A: To the best of my knowledge, there is no easy way to distinguish between a 'new' bug and an expected bug, other than to have a list of known issues handy. If you use a naming convention where you can quickly list tests that are known that they're going to fail, you can then quickly make a scan of which bugs are not on that list - I.E. they're new bugs that need to be looked at.

A: This is actually multiple questions. I'm going to focus on what I consider a good practice for running FitNesse tests.
I suggest that you run your tests in a CI system like Hudson.  CI Systems are good at tracking what happens from run to run.
To do this you will need results in a format Hudson can track.  You can use XSL to transform the results of FitNesse Suite runs into Junit style reports and then leverage Hudson's ability  to track Junit results.  This gives you trends and graphs.  It also lets you see the age of any failure.  Here is my way of doing that: http://whotestedthis.squarespace.com/journal/2012/1/26/transforming-fitnesse-results-to-junit.html

A: When we log a confirmed bug, we add a #warning at the failing statement in source code of the test to indicate the bug number and a (very) short description of the failing behavior.  If we don't expect the bug to be fixed soon (e.g., within a few days), we quarantine the test into a group of tests that are expected to fail.  We review the history those tests periodically, to ensure that they haven't developed new failure modes, and we move them out of quarantine when the bug is fixed.
As Jim Holmes says, a good CI system (we also use JetBrains' TeamCity) will maintain the history in a manner that makes this kind of post mortem analysis easy.


text:
Q: Approach for Python wrapper around C++ Asynchronous Programming Model I need to create a python wrapper around C++ code that is heavily modeled around APM model. I was researching, but cannot find good approach how to model this in Python. Options that I could think of, are:

*

*Use concurrent.futures.Future

*

*it is from 3.4, but I would like this wrapper to be used with any Python version (2.x included), maybe use this backported version

*I don't like the fact that APM defines timeout in Begin* call, and Future define timeout in .result()

*Create my own C++ library that will turn those async calls into sync calls

*

*doesn't allow that way for user to do fancy async stuff in Python

*braindead to implement

*Use Twisted's Deferred or some similar library and emulate those Begin/End with it

*

*I would not want to have dependencies on other libraries, if possible

*Build my own Future/Deferred type

*

*I would like to avoid that, so I can focus on app logic and just reuse stable/reliable stuff around

*Something else I am missing

So, none of these is perfect and at this point, I am inclined to approach 2, but need to ask here am I missing something obvious? Also, does anybody knows any other wrapper that needed to do this and how they pulled it off?


text:
Q: How to write a Django test that checks whether an error occurs on a page? I'm currently debugging a pull request that has made a certain page error out:

The view is subclassed from Django's generic UpdateView, and corresponds to the check-ins tab of a URL named 'family' in the dashboard app:
url(
    r'^families/(?P<pk>[0-9]+)/'
    r'(?P<tab>case-management|scheduling|family-demographics|activation-payment|check-ins)$',
    views.FamilyUpdate.as_view(),
    name='family'),

As a first step, I'd like to write a test which captures what I see, namely, an error occurring, so that after I fix it I can be sure it never happens again.
How can achieve this? I've tried the following test case,
from django.test import TestCase
from django.urls import reverse
from lucy_web.test_factories import FamilyFactory, UserFactory

class TestDashboardNavigation(TestCase):
    '''Test class to simply navigate to pages and click the links, making sure no errors occur'''
    def setUp(self):
        self.client.force_login(UserFactory(is_superuser=True))

    def test_family_navigation(self):
        family = FamilyFactory()
        for tab in ["case-management", "scheduling", "family-demographics", "activation-payment", "check-ins"]:
            url = reverse('dashboard:family', kwargs={'pk': family.id, 'tab': tab})
            response = self.client.get(url)
            print(response.status_code)

where FamilyFactory is a factory_boy test fixture which creates a Family object (the underlying model of the UpdateView), but this test simply passes:
(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py test dashboard.tests.test_navigation
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
302
302
302
302
302
.
----------------------------------------------------------------------
Ran 1 test in 1.294s

OK

How would I catch errors like this occurring on a page?


text:
Q: How to display only one of the show/hide buttons using jquery? I am stuck here.  Here is what I am trying to do..If the image and description list are visible, only the hide button should be displayed. If the image and description list are hidden, only the show button should be visible.  Here is what I tried to do:
$("#hide").toggle('slow');
$("#show").toggle('slow');

Here is my js code:  $(document).ready(function(){ $("#hide").click(function(){ $("img, dl").hide(); }); $("#show").click(function(){ $("img, dl").show(); $(document).ready(function(){ $('#show').hide(); function clickHandler() { $('#hide').toggle('slow'); $('#show').toggle('slow'); } }); }); }); When the page loads only the hide button should show. If the image and description lists are not visible, the show button should be displayed. Both buttons are displayed when the page loads
What is wrong with this?

A: We need to see more of your code to find potential errors - there is nothing wrong with those two lines. And we need to know what is the problem you're facing.
Anyway, here's a possible solution. .toggle() toggles visibility so if only one button should be visible then you need to hide one of them first. This can be done with CSS or with jQuery.
Assuming that this is your markup:
<button id="show">Show</button>
<button id="hide">Hide</button>

If by default everything is visible, the Show button should be hidden:
<button id="show" style="display:none;">Show</button>
<button id="hide">Hide</button>

Or you can use a special class. For example .hidden {display:none;}
Otherwise, you can hide the button on page load:
$(document).ready(function(){
    $('#show').hide();
});

Then you can use .toggle() in the click event handler:
function clickHandler() {
    $('#hide').toggle('slow');
    $('#show').toggle('slow');
}

$(document).ready(function(){
    $('#show').hide();

    $('#hide, #show').on('click', clickHandler);
});

Here is an example: jsfiddle

A: Please include JQuery Library in your project to run this code

$(document).ready(function(){

 if($("#mode").val() == 'N') {
  $("#req_button").html("<input type='submit' value='Save Record' id='btnSave'>").show();
 }

 $("#mode").change(function(){
  var mode = $("#mode").val();
  if(mode == 'N') {
   $("#req_button").html("<input type='submit' value='Save Record' id='btnSave'>").show();
  } else if(mode == 'M') {
   $("#req_button").html("<input type='submit' value='Update Record' id='btnUpdate'>").show();
  } else if(mode == 'R') {
   $("#req_button").html("<input type='submit' value='Remove Record' id='btnRemove'>").show();
  }
 });

});

  <select name="mode" id="mode">
    <option value="N">New</option>
    <option value="M">Modify</option>
    <option value="R">Remove</option>
  </select>


text:
Q: Criteria of a trivial G bundle of a 3-manifold It is said that

If G is a simply connected compact Lie group, then a G bundle on a
  3-manifold is necessarily trivial, see e.g. here.

I think, this means that a bundle or fiber bundle is trivial if it is isomorphic to the cross product of the base space and a fiber.

*

*How do we show this?

*Is this below true that

"If G is a simply connected compact Lie group, then a G bundle on any $d$-manifold is necessarily trivial?" For $d=1,2,3,4,...$? What is the limitation of $d$?

*

*What is the criteria of trivial G bundle on a $d$-manifold? (Other than saying the definition that the bundle is the cross product of the base space and a fiber.)

A: A principal $G$-bundle $P \to B$ is trivial if and only if there exists a section $\sigma: B \to P$. (Then $B \times G \cong P$, given by sending $(b,g) \mapsto \sigma(b)g$.) Whenever you want to know if a bundle has a section, the right place to look is obstruction theory.
Given a fiber bundle $F \to E \to B$, there is a sequence of classes $o_i(E) \in H^{i+1}(E; \pi_i F)$, where $o_i$ is defined provided that $o_{i-1} = 0$.
(Two comments deserve to be made to make this precise: 1) this sequence of classes only exists assuming that $F$ is simple, meaning that $\pi_1 F$ acts trivially on $\pi_n F$ for all $n$; 2) these cohomology groups use local coefficients, depending on the action of $\pi_1 B$ on $\pi_i F$ determined by the fiber bundle. The first is true when $F$ is a Lie group, and the second is true for any principal $G$-bundle.)
If $o_i(E) = 0$ for all $i \leq j$, then there exists a section of $E$ defined over the $(j+1)$-skeleton of $B$. If all classes $o_i(E) = 0$, then there is a section of $E$ defined over all of $B$.
When $G$ is a simply connected Lie group, then $\pi_0 G = \pi_1 G = 0$ is the trivial group by assumption. It is furthermore a theorem (I believe of Bott) that $\pi_2 G = 0$ is trivial as well; see here for more details. Then $\pi_3 G \cong \Bbb Z^t$ is nontrivial unless $G$ is the trivial group (also due to Bott).
Now, on a prinicipal $G$-bundle $P \to B$ over a 3-manifold $B$, you may run the obstruction theory machine: because $\pi_0 G = \pi_1 G = \pi_2 G = 0$, the elements $o_i(P) \in H^{i+1}(B; \pi_i G)$ are zero for $0 \leq i \leq 2$. So by the above there exists a section over the 3-skeleton; you are working over a 3-manifold, and thus you have defined a section everywhere. (The higher classes $o_i(P)$ tautologically vanish because $H^k(B) = 0$ when $k > 3$.) In fact, we never used the manifold structure here (except implicitly in assuiming that $B$ has a CW-complex structure of dimension 3, but this is harmless).
It is worth mentioning here that if $G$ is a nontrivial simply connected compact Lie group, there will always be a nontrivial $G$-bundle over a 4-manifold (because $\pi_3 G$ is nonzero).

Here is a by-hands proof encoding the above obstruction theory. Pick a cell decomposition of your 3-manifold $B$ (no need to assume orientability). Pick a section above each point in the $0$-skeleton; this is just picking a point in the fiber, so is clearly possible.
Now we induct. Assume we have constructed a section over $B^{(i)}$, the $i$-skeleton, for $i \leq 2$. (If $i = 3$, we are finished.)
For every $(i+1)$-simplex $e: \Delta^{i+1} \to B$ in the $(i+1)$-skeleton, the bundle $e^*P \cong \Delta^{i+1} \times G$ is trivial over $\Delta^{i+1}$, because the simplex is contractible; and we have already constructed a section over the $i$-skeleton, which pulls back to a map $\partial \Delta^{i+1} \to G$ which we want to extend to a map defined over all of $\Delta^{i+1}$. Note that $\partial \Delta^{i+1} \cong S^i$, and constructing an extension over all of $\Delta^{i+1}$ is constructing a null-homotopy of the map from $S^i$. Now $i \leq 2$, and $\pi_i G = 0$ in this range: every map from $S^i$ is null-homotopic. So we may choose our null-homotopy arbitrarily, and this is how we extend over this simplex $e(\Delta^{i+1}) \subset B$. Run this same argument over the rest of the simplices and you have a section defined over $B^{(i+1)}$, as desired.


text:
Q: HTML - Audio file works if I open index file but will not when uploaded to web I added a short sound clip to my Webpage, and when I open the page directly from the index file, the 15 second sound clip is there. I then uploaded it through Filezilla (several times) and when I open through the web, the sound bar shows 0 seconds. It just doesn't make sense to me. Is there something wrong with my HTML code? Thanks in advance.
<audio controls="controls">
<source src="keleigreeting.m4a" type="audio/mpeg">
<source src="keleigreeting.ogg" type="audio/ogg">
Welcome to keleigrace designs!
</audio>

A: Is the audio file uploaded to the correct folder? You have two references
audio/keleigreeting.m4a and just keleigreeting.m4a
Try changing
<source src="keleigreeting.m4a" type="audio/mpeg">

to
<source src="audio/keleigreeting.m4a" type="audio/mpeg">


text:
Q: .NET MVC4 Create or select foreign key I cant figure how to work this out, maybe you can help me. I have a MVC4 project with a customer model and an event model.
When I access the create view for the event, I would like to select a customer (via dropdownlist, this is ok and working) or if the customer I want is not created yet, create it inside the event create view (not to close this view, open customer view, create customer, go back to event create view...). How can I do that? Any ideas?
Thanks everybody!

A: Can be done through the form and ess or partial view. I understand the question?
HTML
<div id="dialog-form">
        <form>
            ...
        </form>
    </div>

js
function openDialogForm() {
    $("#dialog-form").dialog("open");
}

function closeDialogForm() {
    $("#dialog-form").dialog('close');
}

function dialogForm() {
    if ($('#dialog-form').length) {
        $('#dialog-form').dialog({
            autoOpen: false,
            height: 200,
            width: 475,
            modal: true,
            resizable: false,
            show: "slow",
            open: function () { $('.ui-widget-overlay').bind('click', function () { $("#dialog-form").dialog('close'); }); }
        });
    }

Your implementation may be another.


text:
Q: Constant conditional correlation (CCC) shows high spikes compared to Dynamic CC (DCC), why? I have calculated 5 beta factors (beta is defined as the ratio between covariance between two time series and the variance between the one series).
When I used CCC with GJR dynamics I get this

When calculating with DCC the picture looks very similar just without this extreme spikes of the blue line.
I am searching for an explanation. My first guess: The constant correlation matrix is not able to capture breaks in variance and covariance adequately?
But this is very high level. Do you have a more detailed idea for this phenomen?

A: The diagonal elements of the conditional covariance matrix are modelled separately by univariate GJRGARCH models in both CCC-GJRGARCH and DCC-GJRGARCH. Thus the fitted variances will be the same in both cases. Therefore, the differences in betas (which are ratios of covariances to variances) will be due to differences in cond. covariances, or more precisely cond. correlations.
When the spikes in betas are more pronounced in CCC than in DCC, it means cond. correlations at these spike periods are higher in CCC than in DCC. Since cond. correlations are constant in CCC, it means the fitted cond. correlations do not dip in those periods, while they do dip in DCC. (You can inspect the fitted cond. correlations to see if this is indeed the case.)
Whether CCC or DCC fits the data better can be seen by comparing the AIC or BIC values of the models.
Regarding breaks in variance and covariance, neither CCC nor DCC produces them by default. There is dynamics, but not breaks in the traditional sense. You would need to include dummy variables or fit the models on subsamples to properly account for breaks.


text:
Q: Fail to compile library - openalpr I'm trying to install openalpr on MacOSX El Capitan 10.11.6
and when I tried to run 'make' command, it goes smoothly until it reaches 55% which it generates following errors. Here are the steps that I followed (https://github.com/openalpr/openalpr/wiki/Compilation-instructions-(OS-X))
error output image
The remaining outputs are:
In file included from /Users/Anonymous/openalpr/src/daemon.cpp:8:
In file included from
/Users/Anonymous/openalpr/src/video/logging_videobuffer.h:5:
In file included from /usr/local/include/log4cplus/logger.h:36:
In file included from
/usr/local/include/log4cplus/spi/appenderattachable.h:33:
In file included from /usr/local/include/log4cplus/appender.h:36:
/usr/local/include/log4cplus/helpers/pointer.h:134:21: error: cannot
initialize object parameter of type 'const
log4cplus::helpers::SharedObject' with an expression of type
'log4cplus::spi::Filter'
                pointee->removeReference();
                ^~~~~~~
/usr/local/include/log4cplus/helpers/pointer.h:152:17: note: in
instantiation of member function
'log4cplus::helpers::SharedObjectPtr<log4cplus::spi::Filter>::~SharedObjectPtr' requested here
            SharedObjectPtr<T> (rhs).swap (*this);
                ^
/usr/local/include/log4cplus/helpers/pointer.h:147:30: note: in instantiation of member function 'log4cplus::helpers::SharedObjectPtr<log4cplus::spi::Filter>::operator=' requested here
            return this->operator = (rhs.pointee);
                         ^
   /usr/local/include/log4cplus/appender.h:211:62: note: in instantiation of member function
   'log4cplus::helpers::SharedObjectPtr<log4cplus::spi::Filter>::operator=' requested here
    void setFilter(log4cplus::spi::FilterPtr f) { filter = f; }
                                                         ^
1 warning and 7 errors generated.
make[2]: *** [CMakeFiles/alprd.dir/daemon.cpp.o] Error 1
make[1]: *** [CMakeFiles/alprd.dir/all] Error 2
make: *** [all] Error 2`

A: I believe you're missing the atomic library. You can find it here. Place it alongside all the other c++ include files in your system.