text:
Q: Get AVAudioPlayer to play multiple sounds at a time I'm trying to get multiple sounds files to play on an AVAudioPlayer instance, however when one sound plays, the other stops. I can't get more than one sound to play at a time. Here is my code:
import AVFoundation

class GSAudio{

    static var instance: GSAudio!

    var soundFileNameURL: NSURL = NSURL()
    var soundFileName = ""
    var soundPlay = AVAudioPlayer()

    func playSound (soundFile: String){

        GSAudio.instance = self

        soundFileName = soundFile
        soundFileNameURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundFileName, ofType: "aif", inDirectory:"Sounds")!)
        do{
            try soundPlay = AVAudioPlayer(contentsOfURL: soundFileNameURL)
        } catch {
            print("Could not play sound file!")
        }

        soundPlay.prepareToPlay()
        soundPlay.play ()
    }
}

Can anyone please help me by telling me how to get more than one sound file to play at a time? Any help is much appreciated.
Many thanks,
Kai

A: I have created a helper library that simplifies playing sounds in Swift. It creates multiple instances of AVAudioPlayer to allow playing the same sound multiple times concurrently. You can download it from Github or import with Cocoapods.
Here is the link: SwiftySound
The usage is as simple as it can be:
Sound.play(file: "sound.mp3")

A: All answers are posting pages of code; it doesn't need to be that complicated.
// Create a new player for the sound; it doesn't matter which sound file this is
                let soundPlayer = try AVAudioPlayer( contentsOf: url )
                soundPlayer.numberOfLoops = 0
                soundPlayer.volume = 1
                soundPlayer.play()
                soundPlayers.append( soundPlayer )

// In an timer based loop or other callback such as display link, prune out players that are done, thus deallocating them
        checkSfx: for player in soundPlayers {
            if player.isPlaying { continue } else {
                if let index = soundPlayers.index(of: player) {
                    soundPlayers.remove(at: index)
                    break checkSfx
                }
            }
        }

A: The reason the audio stops is because you only have one AVAudioPlayer set up, so when you ask the class to play another sound you are currently replacing the old instance with a new instance of AVAudioPlayer. You are overwriting it basically.
You can either create two instances of the GSAudio class, and then call playSound on each of them, or make the class a generic audio manager that uses a dictionary of audioPlayers.
I much prefer the latter option, as it allows for cleaner code and is also more efficient. You can check to see if you have already made a player for the sound before, rather than making a new player for example.
Anyways, I re-made your class for you so that it will play multiple sounds at once. It can also play the same sound over itself (it doesn't replace the previous instance of the sound) Hope it helps!
The class is a singleton, so to access the class use:
GSAudio.sharedInstance

for example, to play a sound you would call:
GSAudio.sharedInstance.playSound("AudioFileName")

and to play a number of sounds at once:
GSAudio.sharedInstance.playSounds("AudioFileName1", "AudioFileName2")

or you could load up the sounds in an array somewhere and call the playSounds function that accepts an array:
let sounds = ["AudioFileName1", "AudioFileName2"]
GSAudio.sharedInstance.playSounds(sounds)

I also added a playSounds function that allows you to delay each sound being played in a cascade kind of format. So:
 let soundFileNames = ["SoundFileName1", "SoundFileName2", "SoundFileName3"]
 GSAudio.sharedInstance.playSounds(soundFileNames, withDelay: 1.0)

would play sound2 a second after sound1, then sound3 would play a second after sound2 etc.
Here is the class:
class GSAudio: NSObject, AVAudioPlayerDelegate {

    static let sharedInstance = GSAudio()

    private override init() {}

    var players = [NSURL:AVAudioPlayer]()
    var duplicatePlayers = [AVAudioPlayer]()

    func playSound (soundFileName: String){

        let soundFileNameURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundFileName, ofType: "aif", inDirectory:"Sounds")!)

        if let player = players[soundFileNameURL] { //player for sound has been found

            if player.playing == false { //player is not in use, so use that one
                player.prepareToPlay()
                player.play()

            } else { // player is in use, create a new, duplicate, player and use that instead

                let duplicatePlayer = try! AVAudioPlayer(contentsOfURL: soundFileNameURL)
                //use 'try!' because we know the URL worked before.

                duplicatePlayer.delegate = self
                //assign delegate for duplicatePlayer so delegate can remove the duplicate once it's stopped playing

                duplicatePlayers.append(duplicatePlayer)
                //add duplicate to array so it doesn't get removed from memory before finishing

                duplicatePlayer.prepareToPlay()
                duplicatePlayer.play()

            }
        } else { //player has not been found, create a new player with the URL if possible
            do{
                let player = try AVAudioPlayer(contentsOfURL: soundFileNameURL)
                players[soundFileNameURL] = player
                player.prepareToPlay()
                player.play()
            } catch {
                print("Could not play sound file!")
            }
        }
    }

    func playSounds(soundFileNames: [String]){

        for soundFileName in soundFileNames {
            playSound(soundFileName)
        }
    }

    func playSounds(soundFileNames: String...){
        for soundFileName in soundFileNames {
            playSound(soundFileName)
        }
    }

    func playSounds(soundFileNames: [String], withDelay: Double) { //withDelay is in seconds
        for (index, soundFileName) in soundFileNames.enumerate() {
            let delay = withDelay*Double(index)
            let _ = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(playSoundNotification(_:)), userInfo: ["fileName":soundFileName], repeats: false)
        }
    }

     func playSoundNotification(notification: NSNotification) {
        if let soundFileName = notification.userInfo?["fileName"] as? String {
             playSound(soundFileName)
         }
     }

     func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        duplicatePlayers.removeAtIndex(duplicatePlayers.indexOf(player)!)
        //Remove the duplicate player once it is done
    }

}

A: Here's a Swift 4 version of @Oliver Wilkinson code with some safechecks and improved code formatting:
import Foundation
import AVFoundation

class GSAudio: NSObject, AVAudioPlayerDelegate {

    static let sharedInstance = GSAudio()

    private override init() { }

    var players: [URL: AVAudioPlayer] = [:]
    var duplicatePlayers: [AVAudioPlayer] = []

    func playSound(soundFileName: String) {

        guard let bundle = Bundle.main.path(forResource: soundFileName, ofType: "aac") else { return }
        let soundFileNameURL = URL(fileURLWithPath: bundle)

        if let player = players[soundFileNameURL] { //player for sound has been found

            if !player.isPlaying { //player is not in use, so use that one
                player.prepareToPlay()
                player.play()
            } else { // player is in use, create a new, duplicate, player and use that instead

                do {
                    let duplicatePlayer = try AVAudioPlayer(contentsOf: soundFileNameURL)

                    duplicatePlayer.delegate = self
                    //assign delegate for duplicatePlayer so delegate can remove the duplicate once it's stopped playing

                    duplicatePlayers.append(duplicatePlayer)
                    //add duplicate to array so it doesn't get removed from memory before finishing

                    duplicatePlayer.prepareToPlay()
                    duplicatePlayer.play()
                } catch let error {
                    print(error.localizedDescription)
                }

            }
        } else { //player has not been found, create a new player with the URL if possible
            do {
                let player = try AVAudioPlayer(contentsOf: soundFileNameURL)
                players[soundFileNameURL] = player
                player.prepareToPlay()
                player.play()
            } catch let error {
                print(error.localizedDescription)
            }
        }
    }

    func playSounds(soundFileNames: [String]) {
        for soundFileName in soundFileNames {
            playSound(soundFileName: soundFileName)
        }
    }

    func playSounds(soundFileNames: String...) {
        for soundFileName in soundFileNames {
            playSound(soundFileName: soundFileName)
        }
    }

    func playSounds(soundFileNames: [String], withDelay: Double) { //withDelay is in seconds
        for (index, soundFileName) in soundFileNames.enumerated() {
            let delay = withDelay * Double(index)
            let _ = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(playSoundNotification(_:)), userInfo: ["fileName": soundFileName], repeats: false)
        }
    }

    @objc func playSoundNotification(_ notification: NSNotification) {
        if let soundFileName = notification.userInfo?["fileName"] as? String {
            playSound(soundFileName: soundFileName)
        }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if let index = duplicatePlayers.index(of: player) {
            duplicatePlayers.remove(at: index)
        }
    }

}

A: Swift 5+
Compiling some of the previous answers, improving code style and reusability
I usually avoid loose strings throughout my projects and use, instead, custom protocols for objects that will hold those string properties.
I prefer this to the enum approach simply because enumerations tend to couple your project together quite quickly. Everytime you add a new case you must edit the same file with the enumeration, breaking somewhat the Open-Closed principle from SOLID and increasing chances for error.
In this particular case, you could have a protocol that defines sounds:
protocol Sound {
    func getFileName() -> String
    func getFileExtension() -> String
    func getVolume() -> Float
    func isLoop() -> Bool
}

extension Sound {
    func getVolume() -> Float { 1 }
    func isLoop() -> Bool { false }
}

And when you need a new sound you can simply create a new structure or class that implements this protocol (It will even be suggested on autocomplete if your IDE, just like Xcode, supports it, giving you similar benefits to those of the enumeration... and it works way better in medium to large multi framework projects).
(Usually I leave volume and other configurations with default implementations as they are less frequently customized).
For instance, you could have a coin drop sound:
struct CoinDropSound: Sound {
    func getFileName() -> String { "coin_drop" }
    func getFileExtension() -> String { "wav" }
}

Then, you could use a singleton SoundManager that would take care of managing playing audio files
import AVFAudio

final class SoundManager: NSObject, AVAudioPlayerDelegate {
    static let shared = SoundManager()

    private var audioPlayers: [URL: AVAudioPlayer] = [:]
    private var duplicateAudioPlayers: [AVAudioPlayer] = []

    private override init() {}

    func play(sound: Sound) {
        let fileName = sound.getFileName()
        let fileExtension = sound.getFileExtension()

        guard let url = Bundle.main.url(forResource: fileName, withExtension: fileExtension),
              let player = getAudioPlayer(for: url) else { return }

        player.volume = sound.getVolume()
        player.numberOfLoops = numberOfLoops
        player.prepareToPlay()
        player.play()
    }

    private func getAudioPlayer(for url: URL) -> AVAudioPlayer? {
        guard let player = audioPlayers[url] else {
            let player = try? AVAudioPlayer(contentsOf: url)
            audioPlayers[url] = player
            return  player
        }
        guard player.isPlaying else { return player }
        guard let duplicatePlayer = try? AVAudioPlayer(contentsOf: url) else { return nil }
        duplicatePlayer.delegate = self
        duplicateAudioPlayers.append(duplicatePlayer)
        return duplicatePlayer
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        duplicateAudioPlayers.removeAll { $0 == player }
    }
}

Here I created a helper getAudioPlayer to be able to return early from code execution and make use of the guard let.
Using guard let more often and preferring less nested code can, most of the time, highly improve readability.
To use this SoundManager from anywhere in your project, simply access its shared instance and pass an object that conforms to Sound.
For example, given the previous CoinDropSound:
SoundManager.shared.play(sound: CoinDropSound())

You could maybe omit the sound parameter as it may improve readability
class SoundManager {
    // ...
    func play(_ sound: Sound) {
        // ...
    }
    // ...
}

And then:
SoundManager.shared.play(CoinDropSound())


text:
Q: SBS 2003 R2 install errors I just installed sbs2003 R2 as a learning lab box on my home network.  The install seemed to take quit a while with a bit of shuffling between disks 4 and 5.  The continue setup checklist showed the red x besides the exchange install and finally gave me an error about the "schema needing extending run, forest /adprep" and told me at the end that the install did not succeed.  After a longer than normal reboot it comes up and seems to be OK.
What logs do i need to check to see what went wrong?
Should i reinstall and try burning the iso's to new media?
cheers

A: Sounds like its stopped somewhere at the end of the install (while populating the exchange database). Being a learning lab box, it shouldn't be too much or a worry.
I build a 2k3 SBS R2 playing box last week and didn't run into any errors like that. Check the event logs (Application and System), they might explain something. If all else fails, try reinstalling again. It is only a learning box, and I think I re-installed mine countless times over the years trying new things.
"Should i reinstall and try burning the iso's to new media?" Being the SBS series was never released as a downloadable ISO (like all there other os's) than you could also have a bad ISO. Might I suggest trying to play in a Virtual Machine environment? You can then mount the ISO's instead of needing to burn 5 CD's VMWare Server is free, and so is ESXi.
Hope that sort of answers your question in a round about way!

redpajama_set_name: RedPajamaStackExchange


text:
Q: mplus - regression including predictors simultaneously vs. not I'm running an ESEM in MPLUS and I'm wondering if there's a way to run independent regression models with each factors as predictors
so rather than including all factors simultaneously in the model as below:
1ST VERSION
'ANALYSIS:
ESTIMATOR=MLR;
ROTATION=TARGET;
Model:
XS BY
X1-X6
Y1-Y6~0
Z1-Z6~0(*1);
YS BY
Y1-Y6
X1-X6~0
Z1-Z6~0 (*1);
ZS BY
Z1-Z6
X1-X6~0
Y1-Y6~0 (*1);
DV1 ON XS YS ZS;'
I want something like this:
SECOND VERSION:
'Model:
XS BY
X1-X6
Y1-Y6~0
Z1-Z6~0(*1);
YS BY
Y1-Y6
X1-X6~0
Z1-Z6~0 (*1);
ZS BY
Z1-Z6
X1-X6~0
Y1-Y6~0 (*1);
DV1 ON XS;
DV1 ON YS;
DV1 ON ZS;'
When I run the second one, the output still looks like the predictors (XS, YS, ZS) are included in the same model, but the coefficients do change a little bit...
I'm not sure if this is just the way mplus presents the results (so did I make that difference I wanted?) or if these two models I ran are in fact identical (but why did the results change a bit then?)
Really appreciate any thoughts on this!

A: In Mplus just like other SEM programs, all of the regression coefficients are estimated simultaneously, so there should be no differences in the results across the two steps.


text:
Q: Excel automagically insert formula I came across this excel files (xlsx) so there is no VBA involved, no table, no name. But columns C is updated with formula "automagically" when I insert a number into column B. I checked the name manager, there is no name. I would like to know how can I achieve this kind of functionality. Have anyone come across something like this?
P.S: When I copy Range A2:C13 and paste to a different files. The magic still works!
Screenshot in Excel 2016

A: So, you go to File>Options>Advanced and tick the box that says:

Extend data range formats and formul̲as

A: Ok, I got this one. Simply add 4 or 5 subsequence row with formula in column B and C. And continue continue to enter data in column B like this GIF:

A: I manage to have this behavior by having the formula defined on all the cells of the column* with an "IF(NOT(ISBLANK(c); <your formula>; "")" condition on the input cell:

*

*e.g. you enter this in C1
=IF(NOT(ISBLANK(B1)); B1/(1+B1);"")

*you click and drag the formula like you know how;

*Et voila
*)(or as many as necessary, since it could be a little "heavy" for Excel to have the formula 1048576 times, nearly for nothing)
Hope it helps


text:
Q: Cloudera Manager Health Issue: NameNode Connectivity, Web Server Status Below is a snapshot of the health issues reported on CM. The datanodes in the list keep changing. Some errors from the datanode logs :
3:59:31.859 PM  ERROR   org.apache.hadoop.hdfs.server.datanode.DataNode
    datanode05.hadoop.com:50010:DataXceiver error processing WRITE_BLOCK operation  src: /10.248.200.113:45252 dest: /10.248.200.105:50010
    java.io.IOException: Premature EOF from inputStream
        at org.apache.hadoop.io.IOUtils.readFully(IOUtils.java:194)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.doReadFully(PacketReceiver.java:213)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.doRead(PacketReceiver.java:134)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.receiveNextPacket(PacketReceiver.java:109)
        at org.apache.hadoop.hdfs.server.datanode.BlockReceiver.receivePacket(BlockReceiver.java:414)
        at org.apache.hadoop.hdfs.server.datanode.BlockReceiver.receiveBlock(BlockReceiver.java:635)
        at org.apache.hadoop.hdfs.server.datanode.DataXceiver.writeBlock(DataXceiver.java:564)
        at org.apache.hadoop.hdfs.protocol.datatransfer.Receiver.opWriteBlock(Receiver.java:103)
        at org.apache.hadoop.hdfs.protocol.datatransfer.Receiver.processOp(Receiver.java:67)
        at org.apache.hadoop.hdfs.server.datanode.DataXceiver.run(DataXceiver.java:221)
        at java.lang.Thread.run(Thread.java:662)
5:46:03.606 PM  INFO    org.apache.hadoop.hdfs.server.datanode.DataNode
    Exception for BP-846315089-10.248.200.4-1369774276029:blk_-780307518048042460_200374997
    java.net.SocketTimeoutException: 60000 millis timeout while waiting for channel to be ready for read. ch : java.nio.channels.SocketChannel[connected local=/10.248.200.105:50010 remote=/10.248.200.122:43572]
        at org.apache.hadoop.net.SocketIOWithTimeout.doIO(SocketIOWithTimeout.java:165)
        at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:156)
        at org.apache.hadoop.net.SocketInputStream.read(SocketInputStream.java:129)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
        at java.io.DataInputStream.read(DataInputStream.java:132)
        at org.apache.hadoop.io.IOUtils.readFully(IOUtils.java:192)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.doReadFully(PacketReceiver.java:213)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.doRead(PacketReceiver.java:134)
        at org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.receiveNextPacket(PacketReceiver.java:109)
        at org.apache.hadoop.hdfs.server.datanode.BlockReceiver.receivePacket(BlockReceiver.java:414)
        at org.apache.hadoop.hdfs.server.datanode.BlockReceiver.receiveBlock(BlockReceiver.java:635)
        at org.apache.hadoop.hdfs.server.datanode.DataXceiver.writeBlock(DataXceiver.java:564)
        at org.apache.hadoop.hdfs.protocol.datatransfer.Receiver.opWriteBlock(Receiver.java:103)
        at org.apache.hadoop.hdfs.protocol.datatransfer.Receiver.processOp(Receiver.java:67)
        at org.apache.hadoop.hdfs.server.datanode.DataXceiver.run(DataXceiver.java:221)
        at java.lang.Thread.run(Thread.java:662)

Snapshot:

I am unable to figure out the root cause of the issue. I can manually connect from one datanode to another without issues, I don't believe it is a network issue. Also, the missing blocks and under-replicated block counts change (up & down) as well.
Cloudera Manager : Cloudera Standard 4.8.1
CDH 4.7
Any help in resolving this issue is appreciated.
Update: Jan 01, 2016
For the datanodes listed as bad, when I see the dadanode logs, I see this message a lot...
11:58:30.066 AM INFO    org.apache.hadoop.hdfs.server.datanode.DataNode
Receiving BP-846315089-10.248.200.4-1369774276029:blk_-706861374092956879_36606459 src: /10.248.200.123:56795 dest: /10.248.200.112:50010

Why is this datanode receiving a lot of blocks from other datanodes around the same time? It seems that because of this activity the datanode cannot respond to the namenode request in time and thus timing out. All bad datanodes show the same pattern.

A: Similar question got answered
hdfs data node disconnected from namenode.
                                       Please check your firewall. Use
telnet ipaddress port

to check the connectivity.


text:
Q: You have an error in your SQL syntax (...) near ; I got this message, and I couldn't find any error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where id ='null'' at line 1

I assumed this code was wrong, but it turned out it isn't.
ResultSet rs = stmt.executeQuery("select password" +
                                 "from userinfo where id = '" + id + "';");

This is full code of error file.
 private boolean checkLoginInfo(String id, String password) throws ServletException
 {
        Connection conn = null;
        Statement stmt = null;

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/webdb", "root", "1234");
            if (conn == null)
                throw new Exception("can't connect to database.<BR>");
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select password" +
                                            " from userinfo where id = '" + id + "';");
                if (!rs.next())
                   return false;
                String correctPassword = rs.getString("password");
                if (password.equals(correctPassword))
                    return true;
                else
                    return false;
        }

A: There is a missing space between password and from:
select password" + "from userinfo where id = '" + id + "';"

Try this:
"SELECT password FROM `userinfo` WHERE id = '"+id+"'"

You should furthermore read about:

*

*Escaping SQL queries

*Authentication/Authorization (why do you select the password only?)

*Code formatting

Edit 1:
The error messages tells us, you are setting the id to 'null' (String, because of ''), not NULL. If your id is expecting an Integer, but you are providing a String, it will break.


text:
Q: Get key usage using pymongo Is there a way to get a list of keys and count their values using pymongo? I have solved it using Counter object and looping through the entire collection, however, this code would be inefficient for extensive collections. Is there a way how to solve it on the database level?
import pymongo
from collections import Counter
client = pymongo.MongoClient("XXX")
database = client["jiripesik"]
collection = database["database"]
result = collection.find({})
key_list = []
for item in result:
    for key in item.keys():
        key_list.append(key)
counter = Counter(key_list)
print(counter)

A: I doubt this would be very performant, but here's a way to get a count of all the top-level fields in the collection.
db.collection.aggregate([
  {
    "$project": {
      "keys": {
        "$map": {
          "input": { "$objectToArray": "$$ROOT" },
          "in": "$$this.k"
        }
      }
    }
  },
  { "$unwind": "$keys" },
  {
    "$group": {
      "_id": "$keys",
      "count": { "$count": {} }
    }
  },
  {
    "$group": {
      "_id": null,
      "histo": {
        "$mergeObjects": {
          "$arrayToObject": [
            [ { "k": "$_id", "v": "$count" } ]
          ]
        }
      }
    }
  },
  { "$replaceWith": "$histo" }
])

Try it on mongoplayground.net.


text:
Q: Parse xml with yearly changing XSD Sorry for the cryptic title.
I'm rewriting a .NET Framework C# application to .NET Core and the main purpose of the application is the read XML-files we get from a 3rd party and save it in our database. A basic ETL process.
Every year a new XSD is published by this 3rd party with several, mostly minor, changes. The application needs to handle XML files from each year.
What is the best way to parse this XML? Because the structure can vary we have created the classes manually and are parsing the XML node for node and check if the node exists before we parse it.
Every year we do a diff of the new XSD and add the new properties and make the properties that are no longer needed nullable. And of course, we need to adjust the node parsing.
Because I'm now going to rewrite everything for .NET Core I wonder if this approach is the best one.
Perhaps someone can suggest something else?

A: Data-binding (mapping XML structures to classes in an object-oriented programming language) is a great technique when the schema is small, simple, and stable. When the schema gets big, complex, or changeable, it becomes an absolute pain, as you are discovering. At this point you're much better off using a generic model such as DOM, or an XML-oriented programming language such as XSLT or XQuery.


text:
Q: Is it possible to use MTP with iPhone without installing iTunes? I want to transfer photos to the windows computer

A: iTunes is not responsible for photo import [on either Mac or PC].
Windows can use MS Photo Gallery [or equivalent depending on your Win version] as an importer & organiser, the closest free equivalent to Apple's Photos app.
The upside is you don't have to dig around in the file system at all - which is not recommended - the app can handle it all for you.
Re pjctech's answer - idk whether that is also a required first step before my solution will work.

A: You need to manually install the required driver, the Apple Mobile Device Support (or AMDS).

*

*Download the iTunes installation package from the official Apple Website.

*You need a program that can open a CAB file and extract contents from it. 7-zip or WinRar can do it.

*Inspect the content of the iTunes installer iTunes64Setup.exe (that you downloaded in step 1) with 7-zip (right click, 7-zip, Open
  archive). 7-zip will show the files inside that installer file.

*Extract AppleApplicationSupport.msi and AppleMobileDeviceSupport64.msi from the installer file to harddisk.

*Run AppleApplicationSupport.msi and then AppleMobileDeviceSupport64.msi.

After AppleMobileDeviceSupport64 is installed, windows should be able to detect the iDevice.
Source


text:
Q: How do I come to know that a message has arrived in shared memory in c I have two process A and B. The communication between them is through shared memory.
A ---> write->sharedmemory-----> Read-->B.

How does B will come to know that A has written something into the shared memory.

A: A writes to shared memory, then A sends a signal to B, B trap the signal and read from memory
B doesn't usually know, A needs to tell it.
Can use a pipe with a poll, a system signal with a hook or A can execute B on demand when the memory is ready (and many more options)

A: You don't know when shared memory has changed, because by definition shared memory does not involves any synchronization mechanism.
And the synchronization is (like the shared memory) operating system specific.
On Linux, shm_overview(7) gives an overview of Posix shared memory facilities, and refers rightly to sem_overview(7) which talks about Posix semaphores which are a synchronization mechanism. You could also look into Posix message queues, see mq_overview(7).
You could also use pipe(7)-s (probably also using a multiplexing syscall like poll(2)...), socket(7)-s (probably unix(7) sockets if all the processes are on the same system), Linux-specific eventfd(2), signal(7)-s -but I don't recommend using them in that case-, etc.
You might need atomic operations. C11 provides <stdatomic.h> (and C++11 has <atomic>). GCC gives atomic builtins.
You could also consider using pthreads (then include <pthread.h>). You'll be interested in mutex locks (see pthread_mutex_lock etc etc...) and condition variables (see pthread_cond_wait etc etc...).
Read also Advanced Linux Programming to get an overview of various IPC mechanisms on Linux.

A: This really depends on the os you are using.
You could use a signal, to inform process B that you have written something in their shared memory.
see signal.h
Other ways are using mutex, pipes, sockets...

A: There are a lot of ways of organizing the synchronization, but they're all system specific.
You could allocate one byte of the shared memory for communicating the information.  It is initially 0.  When A has written all the information into the rest of the shared memory, it can write a 1 to the synchronization byte.  It will then wait, preferably not a busy wait, for the synchronization byte to change back to 0.  Meanwhile, B is waiting, preferably not a busy wait, for the synchronization byte to change to 1.  When it does, it will copy the message out of shared memory, and then set the synchronization byte back to 0, and go back into its loop waiting for the synchronization byte to change to 1 again.
Of course, in the two process scenario, A and B can simply loop with a nanosleep() or similar short delay between checks of the synchronization byte; that's better than an unconstrained loop checking the synchronization byte.
The 'not a busy wait' part means that you usually end up needing two semaphores or something similar so that you can wait without having to saturate the CPU while you do so, and yet wake promptly when the data is available. One semaphore is set by the writer when there's a message present; the other is set by the reader when the message has been consumed.  One advantage of semaphores is that you could have multiple readers, or multiple writers.
You could also use a pair of pipes, one for A to write to B and one for B to write to A. A would copy the message into shared memory and write a byte to the pipe to B when there's a message in shared memory and then read a byte from the pipe from B.  Meanwhile, B would read a byte from the pipe from A, copy the message out of shared memory, and write a byte on the pipe to A to indicate that it has finished with the message in shared memory.  (But then you might ask yourself — why not just use pipes instead of shared memory.)


text:
Q: How can I re-parse req.url from inside a middleware function? I have a middleware function that takes a query string value and turns it into
I am using Express 4 and Node.js. I have a route defined for /:module/:page.aspx and am using req.params and req.query values across a number of middleware functions.
app.get('/:module/:page.aspx', catchEncodedQuery, doSomeStuff, doOtherStuff);

I have one middleware function that appears first, which catches certain requests which have a query string value that can be transformed into a new req.url that I set for use further on in the middleware chain. Basically, I want to proceed as though the un-encoded form of this query string value was the request URL the whole time.
function catchEncodedQuery(req, res, next) {
    if (
        // req meets some specific criteria
    ) {
        req.url = myUnencodeFunction(req.query.url_str);
        next();
    } else {
        next();
    }
};

But I would also like req.params and req.query to reflect this new URL. I could just parse the new URL myself and reassign these values to req.params and req.query, but I'm wondering if there's a better way to do this that leverages Express's existing URL-parsing functionality.


text:
Q: How to access row data from a MouseLeftButtonDown event on a textblock, in a gridview I am trying to modify data in rows in a gridview which I have pulled from a database.
The data is being bound to each gridview column like the following.
<GridViewColumn Header="Status" Width="120" util:GridViewSort.PropertyName="Status">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Status}" FontWeight="Bold" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown_1"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

I have a MouseLeftButtonDown event on the textblock, and this fires when I click on the specific text.
private void TextBlock_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Hello");
}

The issue I am having is that I can't find a way to access the row data(such as the id, or the text in the row).
Is there any way to access all the row data from within the click event?
Thanks

A: Try This:
  private void TextBlock_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
    {
        TextBlock textBlock = (sender as TextBlock);
        string text = textBlock.Text;// Text in the TextBlock
        object datacontext = textBlock.DataContext; // datacontext, Entire row info
    }

A: You should not do anything not directly related to the UI in the code behind of your XAML file.. you should bind the click event to a command  of your Model or ViewModel (the entity bound to your cell, in your case the entity which contains the "Status" property) ; that entity should have easier access to "the row data".


text:
Q: how to convert dictionary to list in python I have a dictionary like this.
dict = {'cow': [200, 50], 'chicken': [100, 70], 'pig': [300, 20]}

I want to convert this dictionary to list with this result.
list = [['cow', 200, 50], ['chicken', 100, 70], ['pig', 300, 20]]

I really tried to find how to do it but failed.

A: Here is the one-liner:
a = [[k, *v] for k,v in d.items()]

(Never name anything list or dict.)


text:
Q: Multiplication operators on $L^2$ Let $X$ be a $\sigma$-finite measure space, and let $g$ a measurable complex-valued function $X$, which lies in $L^\infty(X)$. I would like to determine sufficient and necessary properties for the operator $T:L^2(X)\rightarrow L^2(X)$ by $f\mapsto gf$ to be self-adjoint, an isometry (i.e. inner-product preserving), to be surjective, and to be injective. I feel that it is self-adjoint iff $g$ is real-valued, an isometry iff it takes values in the unit circle, surjective or injective iff it is constant. Is this true?

A: This should be a comment, but it is too long.
Suppose $g$ is not essentially bounded from below (i.e., for every $c>0$, the set $\left\{x\in X : \left|g(x)\right|\leq c\right\}$ has positive measure). If $g=0$ is on a set of positive measure $E$, then since $X$ is $\sigma$-finite, we may assume that $\mu(E)<\infty$. Then $\chi_{E}\in L^{2}(X)$, but $Tf\neq\chi_{E}$ for any $f\in L^{2}(X)$, since $gf=0$ for a.e. $x\in E$. So assume that $\left|g\right|>0$ a.e.
Using our hypotheses together with the $\sigma$-additivity of measure, we may find a subsequence $n_{k}$ of positive integers such that the measurable set
$$E_{k}:=\left\{x\in X:2^{-(n_{k}+1)}\leq\left|g(x)\right|<2^{-n_{k}}\right\},\qquad k\in\mathbb{N}$$
has positive measure. Appealing to $\sigma$-additivity and replacing $E_{k}$ with a smaller subset, w.l.o.g. assume that $\mu(E_{k})<\infty$. Define a measurable function $h$ on $X$ by
$$h:=\sum_{k=1}^{\infty}\dfrac{2^{-n_{k}}}{(\mu(E_{k}))^{1/2}}\chi_{E_{k}}$$
$h\in L^{2}(X)$, as
$$\int_{X}\left|h\right|^{2}\mathrm{d}\mu=\sum_{k=1}^{\infty}\int_{E_{k}}\dfrac{2^{-2n_{k}}}{\mu(E_{k})}\mathrm{d}\mu=\sum_{k}2^{-2n_{k}}<\infty$$
I claim that $h\notin T(L^{2}(X))$. Otherwise, $f=g^{-1}h$ a.e., but
$$\int_{X}\left|g^{-1}h\right|^{2}\mathrm{d}\mu\geq\sum_{k}\dfrac{2^{-2n_{k}}}{\mu(E_{k})}\int_{E_{k}}\left|g^{-1}\right|^{2}\mathrm{d}\mu\geq\sum_{k}\dfrac{2^{-2n_{k}}}{\mu(E_{k})}\int_{E_{k}}2^{2(n_{k}+1)}=\sum_{k}4=\infty,$$
which is a contradiction.


text:
Q: What is the maximum number of threads we can run in NSOperationQueue simultaneously It is always being asked in interview how many maximum threads we can run in ios iphone programming simultaneously in NSOperationQueue and through GCD async?
Please explain the answer.

A: You should be using NSOperationQueueDefaultMaxConcurrentOperationCount when you create your operations to let the OS decide the maximum number of operations - it will decide this based on the hardware available and system resources. The number will of course vary depending on device.


text:
Q: Restkit/Core Data relationship mappings, entity to same type of entity (parent/child) I am following the Alexander Edge tutorial on RestKit 0.2.0 but I am confused about how to apply it to my needs. Specifically, I am consuming a web service that returns objects in the following structure:
{
    "ObjectIdMember": 200,
    "ObjectNameMember": "Baseball Bat",
    "SubObjectIdMember": 4124
},
{
    "ObjectIdMember": 200,
    "ObjectNameMember": "Baseball Glove",
    "SubObjectIdMember": 4555
},

The idea is that an Object entity can have many sub-objects. Roughly speaking, the purpose of getting the Object is to use the DisplayName to populate section headers in a table view, and group sub-objects in sections by object.
How do I capture this sort of relationship (or define it) using RestKit + Core Data? The tutorial only suggests what you might do if there is a subobject defined in the response, but this is a different situation.
I know that I could just decorate and use a subclass of Object with a -(NSArray *)getSubObjects, but Core Data would not be aware of what I was doing in the sense that this would not be using any relationships.

A: I believe what you want is RKConnectionDescription, which can establish a relationship in Core Data using foreign keys.
The example in the docs gives the following json:
{ "project":
    { "id": 12345,
      "name": "My Project",
      "userID": 1
    }
}

with the following mapping configuration:
NSEntityDescription *projectEntity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext];
NSRelationshipDescription *userRelationship = [projectEntity relationshipsByName][@"user"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:userRelationship attributes:@{ @"userID": @"userID" }];


text:
Q: final method / class with testing given the very simple example:
public MyClass {

    final List<Integer> numbers = new ArrayList<>();

    public void method1() {
        ...
        addToNumbers(100);
        ...
    }

    boolean addToNumbers( Integer elem) {
        return numbers.add(elem);
    }
}

////////////////////////////////////////////////////

public MyClassTest() {

    @Test
    private void method1Test() {
        final MyClass x = new MyClass();
        ...
        //some mocking
        ...
        x.addToNumbers();
        ...
    }
}

If no inheritance is involved, does it make sense to declare the method addToNumbers() final? What about the test class? Does it make sense to declare it final as well?


text:
Q: Laravel: HTTPrequest to another server How to make http request to another server through Laravel?
I'll be pleased to provide whatever information you need
any help is much appreciated

A: Depends how complex the request needs to be. You can use curl or even, file_get_contents for simple get requests, or install a package like Guzzle for more complex things.
https://github.com/guzzle/guzzle

A: With 'normal' PHP, you can use Curl to work with the http protocol (POST/GET). If you are using Laravel, you can either build your own curl methods or you can use a 3rd party curl library compatible with composer/Laravel:
https://packagist.org/packages/unikent/curl

A: You can use Guzzle
add the dependency package in the composer.json file
{
    "require": {
        "guzzlehttp/guzzle": "~4.0" //you can change the version
    }
}

make composer install or update
To create your very first request with guzzle, a code snippet as simple as below will work:
use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;

$client = new Client();
$response = $client->get("https://api.github.com/");
retrun $response;

A: If for some reason you are running an old Laravel version or don't want to bother with guzzle, you can always use php-curl:
sudo apt-get install php-curl

Then create a function for your needs eg POST:
function httpPost($url, $data){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

or GET
public function httpGet($url){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Simply call your function in controller:
$response = $this->httpPost($url, $data);
$response = $this->httpget($url);

Where $url is your endpoint where you need to send request and $data - parameters required.

A: First of all run this command
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;

    $client = new Client();
    $response = $client->get("http://www.somewebsite.com/getSmth");
    $response = (string) $response->getBody();
    return $response;

getBody() function will return object.
You can use via converting to string and after that if you want you can change it to integer also
    $response = (int) (string) $response->getBody();

A: in Laravel 8 you can send request by Http Facade.
learn more in Laravel documentation
use Illuminate\Support\Facades\Http;

$response = Http::post('http://example.com/users', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

$data = $response->body(); // or $response->json() or $response->collect()


text:
Q: when i redirect forcefully http to https it shows redirected you too many times I apply like this
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

but, It shows www.example.com redirected you too many times.

A: Okay @ravi i have got your problem so please use this solution.
New Code :
  <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L]
  RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L]
  RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L]

  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
 </IfModule>


text:
Q: correct way to call D3.js object in Drupal module I am trying to visualize a network using D3 with Drupal 7.x and I don't know what is the right way to refer to D3 within my js file.
So far I can build the json and use a render array to pass it to my js script (and show it in console), but then I fail calling D3.js:
Uncaught ReferenceError: d3 is not defined

Here's my js code so far:
(function($){
    Drupal.behaviors.mymodule = {
        attach : function(context, settings) {
            if(Drupal.settings.mymodule.graph_json !== ''){
                // visualize the json
                console.log(Drupal.settings.mymodule.graph_json);
                // create the newtork
                d3.json(Drupal.settings.mymodule.graph_json, function (error, json) {
                if (error){
                    return console.warn(error);
                }
                });
            }
        }
    };
}(jQuery));

Should I add a reference in the array? Or since D3.js is in sites/all/libraries/d3 then there is a common way to call it?

A: According to the statement in the bottom of your question:

Should I add a reference in the array? Or since D3.js is in sites/all/libraries/d3 then there is a common way to call it?

You have placed the d3.js file in the wrong directory sites/all/libraries/d3.js. That file should be in the right directory as you can see the screenshot below.
Follow the steps:

*

*Download the D3 library

*Extract in sites/all/libraries/d3/

*Make sure d3.js file is in the right directory sites/all/libraries/d3/d3.js
Screenshot:

After that, if you find another error Uncaught TypeError: Cannot read property 'linear' of undefined the you should read my answer.
This works for me.
I hope this would help you.


text:
Q: Create variable from string in python I have read a lot of posts about this subject but I haven't found an answer to my problem.
Wants to write a function that allows you to create DF with different names and columns.
So I try this:
def createDT(name,c1,c2,c3):
    name = pd.DataFrame(columns = [c1,c2,c3])
    print(type(name))
    return name
createDT(DT,"col1","col2","col3")

and I receive:
NameError: name 'DT' is not defined

when I change the "name" variable to String I receives the message:
<class 'pandas.core.frame.DataFrame'>
and the table below

Which confirms the creation of DF, but if I want to call the DT variable I get a
NameError: name 'DT' is not defined

I know I can do it this way
DT2 = createDT(DT,"col1","col2","col3")

But then I have to name the variables again and I would like to avoid that and
I want it to be written as a function. Any ideas on how to solve it?

A: It's not that easy unfortunately:
def createDT(name,c1,c2,c3):
    globals()[name] = pd.DataFrame(columns = [c1,c2,c3])
    print(type(globals()[name]))
    return globals()[name]
createDT("DT","col1","col2","col3")

But a preferred and efficient solution would be:
def createDT(name,c1,c2,c3):
    return pd.DataFrame(columns = [c1,c2,c3])
createDT("col1","col2","col3")

A: Wouldn't simple
def createDT(c1,c2,c3):
    temp = pd.DataFrame(columns = [c1,c2,c3])
    print(type(temp))
    return temp

DT = createDT("col1","col2","col3")

work?
In Python you (almost always) don't use function parameters as return value. And you don't need to worry about copying since in Python everything is (kind of like) pointers.


text:
Q: Redirect querystring with ? in it using .htaccess I have a URL format of
http://www.domain.com/?text
For any instance of this URL I'd like to redirect to a 3rd party URL but can't figure out how to match the supposed querystring.
RewriteCond %{QUERY_STRING} ^/text(.*)$
RewriteRule http://www.google.com [R=301,L]

Doesn't work

A: Your attempt is fairly close. Add /? in target to strip off this query string:
RewriteEngine On

RewriteCond %{QUERY_STRING} ^/qipco
RewriteRule ^ http://www.google.com/? [R=301,L]


text:
Q: OData Error: The query specified in the URI is not valid. The property cannot be used in the query option I'm trying to get an OData endpoint up and working and I'm having this error that even Google doesn't have much to say about.
I have created an Entity Framework EDMX context (database first), had the designer generate 2 models from it.
Everything is working fine, except $filter queries fail.
I can do this fine:
http://localhost:27164/Projects(6587660)

Which retrieves the Project with a primary ID of 6587660.
But any $filter requests as such:
http://localhost:27164/Projects?$filter=ProjectID eq 6587660

Will fail with the following error:

The query specified in the URI is not valid. The property 'ProjectID' cannot be used in the $filter query option.

I've also tried querying other properties, string properties too. Same error.
I've checked that the model generated by EF doesn't have any attributes on the properties, they don't.
Here's my Register method in WebApiConfig.cs module:
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    // Configure Web API to use only bearer token authentication.
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<DB.Project>("Projects");
    config.MapODataServiceRoute(
        routeName: "ODataRoute",
        routePrefix: null,
        model: builder.GetEdmModel()
    );

}

Here's the Projects controller (GetProjects is the called method when doing a $filter query):
public class ProjectsController : ODataController
{
    private AppContext db = new AppContext();

    //I've tried decorating with that: [EnableQuery(AllowedQueryOptions = System.Web.OData.Query.AllowedQueryOptions.All, AllowedArithmeticOperators = System.Web.OData.Query.AllowedArithmeticOperators.All)] and no go
    [EnableQuery]
    public IQueryable<Project> GetProjects()
    {
        return db.Projects;
    }

    // GET: odata/Projects(5)
    [EnableQuery]
    public SingleResult<Project> GetProject([FromODataUri] int key)
    {
        return SingleResult.Create(db.Projects.Where(project => project.ProjectID == key));
    }

    /*
    // PUT: odata/Projects(5)
    public IHttpActionResult Put([FromODataUri] int key, Delta<Project> patch)
    {
        Validate(patch.GetEntity());

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        Project project = db.Projects.Find(key);
        if (project == null)
        {
            return NotFound();
        }

        patch.Put(project);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProjectExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return Updated(project);
    }

    // POST: odata/Projects
    public IHttpActionResult Post(Project project)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Projects.Add(project);
        db.SaveChanges();

        return Created(project);
    }

    // PATCH: odata/Projects(5)
    [AcceptVerbs("PATCH", "MERGE")]
    public IHttpActionResult Patch([FromODataUri] int key, Delta<Project> patch)
    {
        Validate(patch.GetEntity());

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        Project project = db.Projects.Find(key);
        if (project == null)
        {
            return NotFound();
        }

        patch.Patch(project);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProjectExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return Updated(project);
    }

    // DELETE: odata/Projects(5)
    public IHttpActionResult Delete([FromODataUri] int key)
    {
        Project project = db.Projects.Find(key);
        if (project == null)
        {
            return NotFound();
        }

        db.Projects.Remove(project);
        db.SaveChanges();

        return StatusCode(HttpStatusCode.NoContent);
    }
    */

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool ProjectExists(int key)
    {
        return db.Projects.Count(e => e.ProjectID == key) > 0;
    }
}

This is the first time I'm using OData with Database First so I'm not sure what's causing this.
I'm using the latest runtimes from Nuget on .NET 4.5.2.

A: From the docs 13.1 Model Bound Attributes:

Now the default setting for WebAPI OData is : client can't apply
$count, $orderby, $select, $top, $expand, $filter in the query, query like localhost\odata\Customers?$orderby=Name will failed as
BadRequest, because all properties are not sort-able by default, this
is a breaking change in 6.0.0

So, we now need to enable OData Model Bound Attributes which you can do globally with the middle line in the following block (the other two are your code):
ODataModelBuilder builder = new ODataConventionModelBuilder();
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); //new line
builder.EntitySet<DB.Project>("Projects");

But that is a catch-all and kind of works around the better security/performance this change brings.
So, you can, and maybe should, enable OData Model Bound Attributes using fluent API calls per entity like this:
builder.EntitySet<DB.Project>("Projects"); //your line of code
builder.EntityType<DB.Project>().Filter("ProjectID");

This answer should solve the problem you posted about but, I expect, you will need to take a look at those docs to enable you to work up a comprehensive solution for the rest of your project (unless, of course, you just deploy the one-line catch all!).

As the name "Model Bound Attribute" suggests, you can also achieve what you need via attributes on your models, which is covered in (in fact, is the main focus of) the docs too.

Edit February 2017:
There appears to be a bug in the per-entity fluent API. Calls to $expand entity-sets intermittently return a 400 Bad Request with the error in the original question despite the entity sets being set up with fluent API.  I don't know whether this bug only exists on $expand or with other query params.  I also don't know whether it is my code that is causing the problem or an MS bug and therefore something others are encountering.  I will investigate this further soon and update this answer.  For now I am using the one-line catch all; that works just fine.
Further edit:
I have just reread some of the docs (to try and get this update as understandable as possible)  and they seem to imply that the way I now have things set up (with the Global Config one-line-catch-all plus fluent API), the per-entity fluent API will still be respected because:

"Query settings can be placed in many places, with the following
precedence from lowest to highest: System Default(not query-able by
default), Global Configuration, Model Bound Attribute, Fluent API."

Therefore, maybe this is what you have to do: add the one-line-catch-all and then fine-tune with model-bound-attributes, fluent API or both.  I need to test this and will report back soon...

A: To answer the question asked by @NickG et al:
in .Net Core, you do something similar:
private static IEdmModel GetEdmModel()
{
    var builder = new ODataConventionModelBuilder();
    var products = builder.EntitySet<Product>("Products");
    products.EntityType.Count().Filter().OrderBy().Expand().Select();
    return builder.GetEdmModel();
}


text:
Q: ClusterRole for CSI drivers I'm designing my own CSI driver and I'm wondering about needed role to be used for Kubernetes RBAC API.
The question is: am I forced to define my service specifying ClusterRole?
I made some trials and I couldn't manage to avoid it.
Thanks in advance to anyone will support,
Antonio

A: The answer is yes, you do need to supply the ClusterRole
Here is an example of whats need to be done

*

*Follow those objects to have a full understanding of the required resources
https://github.com/kubernetes-csi/external-provisioner/blob/master/deploy/kubernetes/rbac.yaml


text:
Q: Difference between two ways of measuring kernel execution times I have N separate OpenCL kernels that are run synchronously in a sequential fashion. The second kernel uses results from the first kernel, the third kernel uses those from the second kernel, and etc.
I measured the total "execution" time for the kernels in two different ways:
1) I associate each kernel with an individual event and measure the time for each kernel separately by subtracting the start time from the end time of each event. The total time was computed by adding the times for all the events of all the kernels. In this case, the event wait method was called after executing each kernel.
2) As in 1), I associate each kernel with an event (N kernels and N events). Then, I call the event wait methods at the end after executing all the kernels (namely, all the event wait calls are followed by the series of kernel calls). The total execution time was obtained by subtracting the start time of the first event from the end time of the last event.
The difference between the total times from 1) and 2) was quite significant: ~20% of the total execution time. Where is this 20% lost? Is it associated with (en)queuing the multiple kernels?
How would I go about reducing the "overhead"? Would it reduce the overhead to write a larger kernel by cramming all the kernels into a single large kernel by restructuring the kernels?
Thanks!


text:
Q: Objective C - running for loop on buttons name if i have lets say 5 buttons named:
"button1״
"button2״
"button3״
"button4״
"buttonn"
and i want to run a for loop on their name like this:
button[i].hidden = NO;
i know that button[i] will not work, its just for the example. what is the correct way to write it?

A: You need to set a "tag" for each button.
button1.tag = 1;
button2.tag = 2;
button3.tag = 3;
button4.tag = 4;
button5.tag = 5;

then you can run your for-loop saying something like this:
for (UIButton *theButton in [viewContainingButtons subviews]) {
    if (theButton.tag == 1) {//change to any tag number
        NSLog(@"Variable `theButton` is currently `button1`");
        //do stuff to the first button using "theButton"
    }
}

A: If you have buttons named like that, you are doing it wrong. Whenever you have an index at the end of variable name, use an array. In this case a NSArray named buttons.
Iterating over the elements of an array is simple.
Also note that if you have created your buttons in the Interface Builder, you can use IBOutletCollection to connect your buttons into an array.
@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *buttons;


text:
Q: Finding solution of equation with differentials I am trying to find the point of maximum exponential curvature, where the exponent equation is:
y = 0.2e^(0.4x)
I know the equation for this point is:
k = y'' / [(1+y')²]^(3/2)
How can I code this in mathematica to solve for the point?
Thanks in advance
Regards
Corse

A: With Mathematica version 10 you could do it as follows:
y[x_] := 1/5 E^(2/5 x)

sol = Maximize[ArcCurvature[{x, y[x]}, x], x]
(* {8/375 Sqrt[2/3] E^(1/2 (-3 Log[2] + 4 Log[5])), {x -> -(5/4) (3 Log[2] - 4 Log[5])}} *)

Plot[y[x], {x, -5, 10},
 Epilog -> {Red, PointSize[.02], Point[{sol[[2, 1, 2]], y[sol[[2, 1, 2]]]}]},
 AspectRatio -> Automatic]


text:
Q: Complete matrix
Which of the following are complete eigenvalues (by complete,
  corresponding eigenspace has the same dimension as its multiplicity)
  for the indicated matrix? What is the dimension of the associated
  eigenspace?
a.) $\pmatrix{2&1\\1&2}$
b.) $\pmatrix{-1&-4&-4\\0&-1&0\\0&4&3}$

*

*For a, I got the eigenvalues of $\lambda = 3,1$ and the corresponding eigenvectors are $v = \pmatrix{1\\1}$, $v_1 = \pmatrix{1\\-1}$ but the answer says it is complete and has $dim = 1$ with basis of $\pmatrix{1\\1}$.

*For b, I got the eigenvalues of $\lambda = -1,-1,3$, its corresponding eigenvectors is $\pmatrix{0\\-1\\1}$ for $\lambda = -1$ and $\pmatrix{1\\0\\1}$ for $\lambda = 3$ but then the $dim = 2$ with basis $\pmatrix{1\\0\\0}$, $\pmatrix{0\\-1\\1}$ and it is complete. How did they get that?

Also, why does $\pmatrix{1&3\\3&1}$ (which has eigenvalues of -2,4 and
  eigenvectors $\pmatrix{-1\\1}$, $\pmatrix{1\\1}$) form a basis in
  $\mathbb{R^2}$ and in $\mathbb{C^2}?$

A: (A) Let me check what you're doing for eigenvals/eigenvecs...

*

*$det\pmatrix{{2-\lambda}&1\\1&{2-\lambda}}=(2-\lambda)^2-1=\lambda^2-4\lambda+3=(\lambda-3)(\lambda-1)=0$. So you are correct, $\lambda_1=1$ and $\lambda_2=3$.

*$M-\lambda_1I_2=\pmatrix{{1}&1\\1&{1}}$ which leads to this equation $x_1+x_2=0$ for both which means this eigenvector $v_1=\pmatrix{1\\-1}$.

*$M-\lambda_2 I_2=\pmatrix{{-1}&1\\1&{-1}}$ which leads to the equation $x_1-x_2=0$ for both which means this eigenvector $v_2=\pmatrix{1\\1}$. Everything you did is correct.

Perhaps what you are confused on is associating the eigenvector with an eigenspace. The dimension of $v_1$ and $v_2$ are both $1$ which corresponds to the multiplicity of $\lambda_1$ and $\lambda_2$ which are both $1$ $\Rightarrow$ complete.
Summary: Correspondence

*

*$dim(v_1)=1$ and $mult(\lambda_1)=1$

*$dim(v_2)=1$ and $mult(\lambda_2)=1$

Which implies completeness.

(B) Probably similar confusion. Again correct, $\lambda_1=\lambda_2=-1$ and $\lambda_3=3$.

*

*$M-\lambda_1 I_3=\pmatrix{0&-4&-4\\0&0&0\\0&4&4}$ which leads to the system of equations $x_2+x_3=0$. But you are forgetting that $x_1$ can be anything. So your eigenvectors for $\lambda_1$ are $\pmatrix{0\\-1\\1}$ AND $\pmatrix{1\\0\\0}$. So the dimension of the eigenspace is $2$ (the span of $\pmatrix{0\\-1\\1}, \pmatrix{1\\0\\0}$) which corresponds to the multiplicity of $\lambda_1$ which is $2$ since it appears twice.

Also you are correct for $dim (v_3)=1$ corresponding to $mult (\lambda_3)=1$ $\Rightarrow$ complete.
If you want to do a little more study on evals, evecs and espaces, check this link out.

(C) Your eigenvecs are $\pmatrix{-1\\1}$ and $\pmatrix{1\\1}$. If you can show that the standard basis for $\Bbb R^2$ which is $\pmatrix{1\\0}$ and $\pmatrix{0\\1}$ is within your eigenvecs then you show that it is a basis. Notice

*

*$\frac 1 2 \pmatrix{-1\\1}+\frac 1 2 \pmatrix{1\\1} = \pmatrix{0\\1}$

*$\frac {-1} 2 \pmatrix{-1\\1}+\frac 1 2 \pmatrix{1\\1} = \pmatrix{1\\0}$

So since you can form the standard basis using just a linear combination of your eigenvectors, these eigenvectors also serve as a basis for $\Bbb R^2$.
$\Bbb C^2$ is basically the same, as you can have your scalars be in $\Bbb C$.


text:
Q: Encrypt all data from Python script to a Server I am looking for a way to secure the data being sent from my Python script to my server via a known network.
Python Script - > Known Network -> Server
I want the known network so i can restrict all other hosts from accessing the server and only allow the known network to access it.
The Server is running MariaDB, Apache2, SSH and other default Debian packages. My Python script will be run on a number of windows 7 and windows 10 computers.
I only want the connection from the script to be run through this system and all other applications to just use the normal internet.
I am looking into SSH Tunnels, VPNs and SOCKS5 proxy but im not sure which one i need. I have no restriction on speed so if the encryption method takes a second or two to complete i am happy with that.
Can anyone provide any guidance as to how i can achieve this and which protocol i would need ?


text:
Q: Eclipse Indigo : Jobs found still running after platform shutdown I am using eclipse indigo. When I try to run a configuration it says Jobs found still running after platform shutdown. Jobs should be canceled by the plugin that scheduled then during shutdown: org.eclipse.ui.internal.IDEWorkbenchActivityHelper
I tried the following
rm MY_WORKSPACE/.metadata/.plugins/org.eclipse.core.resources/.snap
rm MY_WORKSPACE/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi

But those files are not present itself but I am able to do the following
 rm MY_WORKSPACE/.metadata/.plugins/org.eclipse.ui.workbench/workbench.xml

Even after deleting that when I restart the eclipse and run the previous configuration, I am getting the same error. I also tried the following
eclipse -clearPersistedState

Still no luck. How will I fix this error?

A: eclipse -clean -clearPersistedState option did not work for me( version 3.8.0). I have created new eclipse 'Run configuration' and worked.

A: That is not an error for you to fix as a user. As it says, it's up to the plug-in that scheduled the background job to end it. You should, though, at least see if it's already resolved in Luna SR1 (soon SR2) rather than Indigo, the 2011 release.


text:
Q: Rich:tab action problem In my sample one form of JSF application that contains tab panel and inside that having 3 tabs, each tab having different components like(input Text , output Text,etc), and parent page of this tab panel having common save method.
Problem is: when i  was doing some thing (entering value in input text,etc) in  any  one tab (e.g 3rd tab ) and after clicking save button , it defaults open to the  first tab  after saving, but I need to remain in the same tab.
How can i do that??
Will you you help me out of this?

A: Solution for that case to use a4j:jsFunction for example

Then on each tab we use onleave="clean()" which will call the function from backing bean
like

Hope That help (_)


text: Q: Proof that the transcendence degree of $K(x_1,...x_n)/K$ is $n$. This is more of a clarification than a question. I know that $H/K$ has transcendence degree $|S|$ if $S\subset H$ is algebraically independent over $K$ and such a set is maximal w.r.t inclusion. This is equivalent to stating that $H/K(S)$ is algebraic and $S$ is algebraically independent over $K$. Since, $(x_1,x_2,..,x_n)$ is algebraically independent over $K$ and $K(S)$ is algebraic over itself this implies that the transcendence degree is $n$. Is this valid?


text:
Q: Joining two tables on oracle, where one column on table A is looking for values on two columns on Table B I am trying to join two tables, Table A have one column "Col1" with Account no and ID values, and Table B have two columns Name Account "Dev" and ID column "Ops", I am trying to join table B to table A in a condition that Col1 = dev column on table B, or Col1 v= Ops column on table B
select * from Table a, Table b
where a.Col1 = b.Dev
or a.Col1 = b.Ops

A: The clue is in the error message - which you disclosed in a comment instead of including it in your original question (as you should have done).
It indicates that the Ops (ID) column in the second table is number data type. When the query attempts to match a name like 'Joe' from the Col1 column in the first table against a number like 2381 (an id) - as it will do when 'Joe' does not match the name column in the second table - it will attempt to convert the string 'Joe' to a number, resulting in the error you saw. In a case like that, Oracle attempts to convert the string to a number, not the other way around.
The workaround is simple - compare a.Col1 to to_char(b.Ops).
Hopefully you will be able to fix the first table - its design is fatally flawed. You shouldn't have to put up with such nonsense in the first place.

A: It is about datatype mismatch. As you didn't post your tables' description, I'll show it on Scott's EMP and DEPT tables.
SQL> desc emp
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPNO                                     NOT NULL NUMBER(4)
 ENAME                                              VARCHAR2(10)  --> I'll join it to DEPT.DEPTNO
 JOB                                                VARCHAR2(9)
 MGR                                                NUMBER(4)
 HIREDATE                                           DATE
 SAL                                                NUMBER(7,2)  --> I'll join it to DEPT.LOC
 COMM                                               NUMBER(7,2)
 DEPTNO                                             NUMBER(2)

SQL> desc dept
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPTNO                                    NOT NULL NUMBER(2)
 DNAME                                              VARCHAR2(14)
 LOC                                                VARCHAR2(13)

This is how your current query looks like:
SQL> select *
  2  from emp e, dept d
  3  where e.ename = d.deptno
  4     or e.sal = d.loc;
where e.ename = d.deptno
      *
ERROR at line 3:
ORA-01722: invalid number

See? Exactly the same error as you got, because ENAME's datatype is VARCHAR2, while DEPTNO is a NUMBER. So let's convert number to a string:
SQL> select *
  2  from emp e, dept d
  3  where e.ename = to_char(d.deptno)
  4     or e.sal   = d.loc;
   or e.sal   = d.loc
                *
ERROR at line 4:
ORA-01722: invalid number

Ah, still the same error, but now asterisk points to a different column. Why? Because SAL is a NUMBER, while LOC is a VARCHAR2. So, convert SAL to a string:
SQL> select *
  2  from emp e, dept d
  3  where e.ename        = to_char(d.deptno)
  4     or to_char(e.sal) = d.loc;

no rows selected

SQL>

Right, now it works. Though, no rows are returned as there are no matches, but - there's no error either.

Side note: you'd rather properly JOIN tables; leave WHERE clause for conditions data should meet.
SQL> select *
  2  from emp e join dept d on e.ename        = to_char(d.deptno)
  3                        and to_char(e.sal) = d.loc;

no rows selected

SQL>


text:
Q: Disabling Windows 10 update forever, Embedded use I have 50 computers with windows 10 pro

*

*I disabled Windows Update Service

*I connected them to internet once to activate the windows

These will be on 24/7 for an embedded project and never connected to internet.
 There should be no prompts or interruptions, restarts or warnings. The questions is, will windows continue working with this configuration? Or will it cause restarts/warnings?
It think this was a big mistake to get windows 10 pro. Windows IoT would be better.


text:
Q: How do I make a ROW_NUMBER() function with a condition and also PARTITION BY? I'm looking for help on a SQL query.
Let's say I have a dataset that includes multiple levels of groups. Here's an example: we have students, that took some class, and then had some tests in each class. Let's say I have to use this dataset. I want to do some sort of query (I'm thinking ROW_NUMBER) that increments when there's a new Class ID, but not when there's a new Test ID, PARTITION BY Student ID.
Sample dataset:
StudentID   ClassID   TestID
----------------------------
1            1          1
1            2          1
1            3          1
2            1          1
2            1          2
3            2          1

Desired output:
StudentID   ClassID   TestID   ClassNumber
------------------------------------------
1            1          1      1
1            2          1      2
1            3          1      3
2            1          1      1
2            1          2      1
3            2          1      1

I want to do things like see if the student did better in their 2nd class versus their 1st class, regardless of what the class was.
This is the code I'm trying:
SELECT
    StudentID, ClassID, TestID,
    ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY StudentID ASC) AS "ClassNumber"
FROM
    mytable

Now I know this is WRONG, but I don't know how to get it to do what I want it to do?

A: From your sample data, it seems like you can use partition by studentID, testID order by ClassID:
select
    t.*,
    row_number() over(partition by studentID, testID order by ClassID) ClassNumber
from mytable t

Note: with that few sample data it is hard to tell wich ranking fucntion would best suit your use case (row_number(), rank(), dense_rank()). Since you used row_number(), I sticked to it.
Demo on DB Fiddle

StudentID | ClassID | TestID | ClassNumber
--------: | ------: | -----: | :----------
        1 |       1 |      1 | 1
        1 |       2 |      1 | 2
        1 |       3 |      1 | 3
        2 |       1 |      1 | 1
        2 |       1 |      2 | 1
        3 |       2 |      1 | 1

A: You may want dense_rank():
dense_rank() over (partition by studentID order by ClassID) as ClassNumber

If you had:
4            1          1
4            1          2
4            2          2

This would assign:
4            1          1         1
4            1          2         1
4            2          2         2

which is how I understand your question.

A: I think this is what you are looking for:
Select StudentID,
ClassID,
TestID,
ROW_NUMBER() Over (Partition By StudentID, TestID Order By StudentID) As ClassNumber
From myTable


text:
Q: How to get ::iterator of const std::vector I want to take iterator from const std::vector<T>, but cannot find a way to explain that to the compiler.
This is how could it look like:
(const std::vector<T>)::iterator

The workaround: typedef or using
template<typename T>
using const_vec = const std::vector<T>;
const_vec::iterator ...

Update. std::vector::iterator is example. The question is about C++ syntax.

A: The const qualifier does not change anything about the definition of the type. So the iterator type in const std::vector<T> is the same as in std::vector<T>. Just use
std::vector<T>::iterator

or, if T is a template parameter, making this a dependent name:
typename std::vector<T>::iterator

You probably don't want iterator though, because there is no function of std::vector<T> that could return an iterator on a const qualified instance. You probably want const_iterator instead.
Generally you don't need to access the iterator type aliases anyway. You can obtain the correct type from auto in a variable definition:
const std::vector<T> vec{/* ... */};
auto it = vec.begin();

or with decltype if you need the type itself:
const std::vector<T> vec{/* ... */};
using iterator = decltype(vec.begin());

A: You can use std::vector<int>::const_iterator like:
const std::vector<int> v{ 1, 2, 3, 4, 5 };
std::vector<int>::const_iterator it = v.begin();

or just take advantage of auto like:
const std::vector<int> v{ 1, 2, 3, 4, 5 };
auto it = v.begin();

A: You should read the documentation vector.begin()


text:
Q: Vue router remove params from URL I have a route set up like below. The idea is that if a user clicks a referral link then the key is stored. In the future if the user navigates to the path /store the same component is used and the referral link will be pulled from storage.
Do I need a route for both /store and /store/:referralKey or is there a way to do this with one route?
const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/shop/:referralKey',
            name: 'shop',
            component: () => import('./views/Shop'),
            meta: {
                public: true
            }
        }
    ]
})

A: Add ? after the Dynamic params and vue-router will make it optional.
path: '/shop/:referralKey?'

Hope this helps!


text:
Q: I'm trying to fetch images from firebase in recyclerview but the listview is empty and show nothing below I'm working on docs manager app in android and i used firebase for storage I want to retrieve files from firebase in ListView but I got nothing once I run my app.
private void setupFirebaseStorageListener() {
    storageElements.clear();
    addElement(emptyElement);
    addElement(emptyElement.duplicate());
    // Showing refresh animation before making requests to firebase server
    swipeRefreshLayout.setRefreshing(true);

    fbHelper.getDatabaseReference().addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            Toast.makeText(context, "Child added", Toast.LENGTH_SHORT).show();

            if (StorageElement.isFile(dataSnapshot)) {
                // the element is a file

                MyFile file = dataSnapshot.getValue(MyFile.class);
                if (file != null &&

                        StorageElement.retrieveFileByName(file.getFilename(), storageElements) == null ) {
                    Log.d(TAG, "Adding new file: " + file.getFilename());
                    Toast.makeText(context, file.getFilename().toString(), Toast.LENGTH_SHORT).show();
                    addElement(file);
                }
            }
            else {
                // the element is a directory
                Log.d(TAG, "Adding new folder..");
                MyDirectory dir = new MyDirectory(dataSnapshot.getKey());
                if (StorageElement.retrieveDirectoryByName(dir.getDirectoryName(), storageElements) == null) {
                    addElement(dir);
                }
            }
            swipeRefreshLayout.setRefreshing(false);
        }


text:
Q: How to reverse spinner left to right without reversing the selected item? Normal Spinner are like this :

when I tried to rotate it using  android:rotationY="180" the selected item is also rotated seems logical

now the problem is the selected item is rotated making the the selected item text has no sense
the required one is the same as the first picture but with rotated spinner
Spinner XML  :
<Spinner
     android:id="@+id/privacySpinner"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_below="@id/eventPrivacy"
     android:layout_alignParentRight="@id/eventPrivacy"
     android:prompt="@string/event_privacy"
     android:entries="@array/privacy_levels"
     android:rotationY="180"
/>

A: Solved by selecting the 'item selected' since it's called back as view (textView)
then rotating it back.The item selected is rotated back
  privacySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> adapter, View view, int pos, long id) {

                  if(Locale.getDefault().getLanguage().equals("ar"))
                    view.setRotationY(180);// rotating the view (Selected Item) back
                public void onNothingSelected(AdapterView<?> arg0) {
                }
            });

        }

A: Keep the rotation on the Spinner, but also add rotation on the textview you are using to display the text.
i.e. assign a View to the selected item, and set it's rotation back the other way.
pseudo:
spinner.setAdapter(...);
spinner.setDropDownViewResource(R.layout.my_view);

myView .. setRotationY = 180

ref
http://developer.android.com/reference/android/widget/ArrayAdapter.html#setDropDownViewResource(int)


text:
Q: How to pass the non dataframe argument to udf in spark Can any please help to know how to pass the non dataframe value as an argument to udf.
val df2 = df1.withColumn("newcol", udffunc(df1("col1"), x)).

The udf function i defined as below.
udffunc = udf(method _)

Method i defined as below.
def method(inputvar1: String, inputvar2: String): Option[Long] = {
  ...
  ...
  return Longvariable
}

A: I am able to fix the issue by just writing the below code for UDF.
def udffunc = udf((y:String) => {
    val format:String = "x"
    method(y, "x")
  })

So with this, I am able to pass one argument(dataframe column) from .withColumn to the UDF function udffunc and then am able to pass external argument which is "x" in the above example to the function named as "method".


text:
Q: CopyTo using xlsx files gives error upon opening I have the following IHttpHandler (ashx) handler:
public class UploadFile : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        using (var fileStream = File.OpenWrite(@"C:\" + context.Request.QueryString["FileName"]))
        {
            context.Request.InputStream.CopyTo(fileStream);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Which is called from:
$.ajax({
    type: "POST",
    url: "UploadFile.ashx?FileName=" + file.name,
    data: file,
    success: function () {
        alert("Success");
    },
    processData: false,
    contentType: file.type
});

The file variable comes from a <input type="file" /> and is retrieved using document.getElementById("fuExcelFile").files[0].
This work with seemingly every file other than xlsx. With xlsx, the file is uploaded but when I open it in Excel I get the following error:

We found a problem with some content in '.xlsx'. Do you want
  us to try to recover as much as we can? If you trust the source of
  this workbook, Click Yes

I'm not sure where to go from here since it works with other files :S
EDIT: Here is the file im testing with and a image of it in the hex editor

A: This was a hard one.
In the discussion in the comment we found out that the destination file is larger then the source. Excel could still open it but issued warnings. This smelled like a partial corruption.
Turns out File.OpenWrite appends to an existing file. During testing you have appended the same file over and over.
The key to debugging this was to binary compare the files. When you're stuck with a bug and don't know what it is: Investigate! Experiment. Obtain new information. Vary the setup.


text:
Q: Aligning the dimensions for conformity in matlab A number of times, I run this simple code. It keeps displaying a usual error related to the dimensions but I have tried to extend the dimensions of rho_1. I am not sure if the error is mainly due to the CDF function. Any suggestions for solving this problem? Thanks
rho_1 = [2*10^-4];
beta=4;
Cua = pi*gamma(1+2/beta)*gamma(1-2/beta);
A = (4*pi-36*sqrt(3)+64)/(12*pi-9*sqrt(3));
p2=10^(15/10);
p1=10^(15/10);
T_1 = 10^(2/10);
T_2 = 10^(2/10);
B_one = 1/2*rho_1*Cua*((T_2)^(2/beta))*(A^2)*(((p2/p1)^(2/beta))+ 1);
Ry_low = 0:10:50; A=(4*pi-36*sqrt(3)+64)/(12*pi-9*sqrt(3));
Ry_high = 50;
D_one= 1/2*rho_1*Cua*((T_2)^(2/beta)) * (A^2) *(((p1/p2)^(2/beta))+ 1) ;
C_rov = ((pi* rho_1)/(2* sqrt(B_one*D_one)*(Ry_high - Ry_low).^2))*((normcdf(sqrt(2*B_one)*Ry_high) - (normcdf(sqrt(2*B_one)*Ry_low))) *((normcdf(sqrt(2*D_one)*Ry_high) - (normcdf(sqrt(2*D_one)*Ry_low)))));
plot(Ry_low,C_rov)

A: Use dot multiplication/division. Also corrected D_1 to D_one.  Please replace your line 13 with this:
C_rov = ((pi* rho_1)./(2* sqrt(B_one*D_one).*(Ry_high - Ry_low).^2)).*((normcdf(sqrt(2*B_one)*Ry_high) - (normcdf(sqrt(2*B_one)*Ry_low))).*((normcdf(sqrt(2*D_one)*Ry_high) - (normcdf(sqrt(2*D_one)*Ry_low)))));


text:
Q: Zend Framework has problems with CamelCase Controller Names? I have a Zend Framework application I've been working on my local machine, I've deploying it to a server but having .htaccess issues because some but not all routes fail with a "Page Not Found". Very weird that I can't access some controllers.
My .htaccess is:
RewriteBase /~user/path/to/app/public/

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

This error does not occur on the local machine, only on the server. The only thing I can see that is common to the controllers that have a "Page Not Found" error on the server is that the Controller names are camel case.
Controllers that work: CustomerController, InvoiceController, StockController. Controllers that fail: SuppliersStockController, StockTypesController.
If I try to do something like 'www.route/to/app/stock-types/' or '/stock.types/' I get an "Application Error".

A: You are seeing the effect of a case sensitive file system.
When you go to /stocktypes/index, ZF will look for StocktypesController.php and succeed on case insensitive systems like Mac OS X and Windows. On Linux however, it will fail.
If you go to /stock-types/index, then ZF will look for StockTypesController.php and will find it on Linux.
If ZF finds a CamelCased controller name, then it will look for a view folder with a hyphen.


text:
Q: clover: how does it work? I am evaluating clover currently and wonder how to use it best. First I'd like to understand how it works conceptually.
1) What does instrumentation mean? Are the test-calls attached to implementation's statements?
2) How is this done? Are the tests actually executed with some fancy execution context (similar to JRebel e.g.) for this? Or is it more like static analysis ?
3) After a "clover-run", some DB is saved to disk, and based on this, reports are generated right? Is the DB-Format accessible? I mean Can I launch my own analysis on it, e.g. using my own reporting tools ? What information does the DB contain exactly? Can I see the mapping between test and implementation there ?
4) Are there other tools that find the mapping between test and implementation? Not just the numbers, but which test, actually covers a line of code ...
Thanks, Bastl.

A:
How is this done? Are the tests actually executed with some fancy execution context (similar to JRebel e.g.) for this? Or is it more like static analysis?

During code instrumentation by Clover it detects which methods are test methods (by default it recognizes JUnit3/4 and TestNG). Such methods gets additional instrumentation instructions. Shortly speaking, entering a test method will usually instantiate a dedicated coverage recorder which measures coverage exclusively for this test. More information about per test recording strategies available in Clover:

*

*https://confluence.atlassian.com/display/CLOVER/Clover+Performance+Results

*https://confluence.atlassian.com/display/CLOVER/About+Distributed+Per-Test+Coverage

After a "clover-run", some DB is saved to disk, and based on this, reports are generated right?

A Clover database (clover.db) contains information about code structure (packages, files, classes, methods, statements, branches), it has also information about test methods. There are also separate coverage recording files (produced at runtime) containing information about number of "hits" of given code element. Clover supports both global coverage (i.e. for the whole run) as well as per-test coverage (i.e. coverage from a single test).
More information is here:

*

*https://confluence.atlassian.com/display/CLOVER/Managing+the+Coverage+Database

Is the DB-Format accessible?

The API is still in development (https://jira.atlassian.com/browse/CLOV-1375), but there is a possibility to get basic information. See:

*

*https://confluence.atlassian.com/display/CLOVER/Database+Structure
for more details about DB model and code samples.
But the question is: do you really need to manually read this DB? You wrote that:

Can I see the mapping between test and implementation there ?

Such mapping is already provided by Clover - in the HTML report for example if you click on a source line it will pop up a list of test methods hitting this line.
PS: I'm a Clover developer at Atlassian, feel free to contact me if you have any questions.

A:
What does instrumentation mean?

Additional code is woven in with your code.

Are the test-calls attached to implementation's statements?

I am not sure what you mean but it could be instructions or call to methods.  Trivial methods will be inlined by the JIT at runtime.

How is this done?

There are many ways to do it, but often the Instrumentation class is to used to capture when a class is being loaded and a library like Objectweb's ASM is used to manipulate the code.

Are the tests actually executed with some fancy execution context

The context counts which lines have been executed.

Or is it more like static analysis ?

No, it is based on what is called.

After a "clover-run", some DB is saved to disk, and based on this, reports are generated right? Is the DB-Format accessible?

You had best ask the producers of clover as to the content of their files.

Are there other tools that find the mapping between test and implementation? Not just the numbers, but which test, actually covers a line of code ...

There are many code coverage tools available including EMMA, JaCoCo, Cobertura, IDEA has one builtin.


text:
Q: What's the meaning of factors 'collapsing' in quotients like $\mathbb{Z}_4\times\mathbb{Z}_6/\langle(0,1)\rangle$? My book says that in
$$\mathbb{Z}_4\times\mathbb{Z}_6/\langle(0,1)\rangle$$
since we're setting everything in $\langle(0,1)\rangle$ to $0$, it's like. That is, the whole second factor $\mathbb{Z}_6$ of $\mathbb{Z}_4\times\mathbb{Z}_6$ is collapsed, leaving just the factor $\mathbb{Z}_4$.
Then, for
$$\mathbb{Z}_4\times\mathbb{Z}_6/\langle(0,2)\rangle$$
It says that the same thing happens, but now $\mathbb{Z}_6$ is collapsed by a subgroup of order $3$, therefore givinf a group in the second factor of order $2$, so it's isomorphic to $\mathbb{Z}_4\times\mathbb{Z}_2$
I tried to visualize the cosets for both groups, here they are:
$$\mathbb{Z}_4\times\mathbb{Z}_6/\langle(0,1)\rangle$$
$$H = \{(0,0),(0,1),(0,2),(0,3),(0,4),(0,5)\}$$
$$H_1 = \{(1,0),(1,1),(1,2),(1,3),(1,4),(1,5)\}$$
$$H_2 = \{(2,0),(2,1),(2,2),(2,3),(2,4),(2,5)\}$$
$$H_3 = \{(3,0),(3,1),(3,2),(3,3),(3,4),(3,5)\}$$
And
$$\mathbb{Z}_4\times\mathbb{Z}_6/\langle(0,2)\rangle$$
$$H = \{(0,0),(0,2),(0,4)\}$$
$$H_1 = \{(1,0),(1,2),(1,4)\}$$
$$H_2 = \{(2,0),(2,2),(2,4)\}$$
$$H_3 = \{(3,0),(3,2),(3,4)\}$$
But I cannot visualize this 'collapse' thing

A: Personally I prefer writing $\langle (0,2)\rangle$ as $0\times 2\Bbb Z_6$, looks neater and gives a more intuitive sense when comparing to the traditional ones of integers. Anyway onto your question, collapsing is more of a metaphore with the illustration that it originally stands as a big building that falls into pockets where the material must be.
Personally I just view it as a word meaning that "we group these elements together and declare them to be equal that is compatible with our algebraic structure". A natural question then is when we do this, how does the structure change? What are the differenses? What are the new things? Etc. This leads to us wanting to find isomorphisms to what is viewed as more simple structures that are isomorphic.
Here it is easy to consider things as we have
$$\frac{\Bbb Z_4\times\Bbb Z_6}{0\times 2\Bbb Z_6}\cong \frac{\Bbb Z_4}{0}\times\frac{\Bbb Z_6}{2\Bbb Z_6}$$
and the latter one is easy to see is isomorphic to $\Bbb Z_3$ after some work.


text:
Q: Can I programatically check if antivirus settings are "managed by an administrator"? We are doing a company wide audit, and need to prove that each machine's Windows Defender settings displays "Some settings are managed by an administrator" and does not allow any changes by an end user.
I'm not sure of any powershell or C# command that can check this.  Being domain joined is not enough evidence, and they need a specific example of end users not being able to change their settings.  Rather than take screenshots of every single machine, is there another way to do this with a command that shows users are unable to change settings?
Either Powershell or C# if possible. Thanks in advance to anyone that can figure this out! I've included an image above of the page I'd like to confirm is set to be managed by an admin.
Here's an image of what I want to search for:


text:
Q: jQuery .css not changing font-size correctly in Chrome This is the closest I've seen:
Changing font-size with jQuery css() function is crashing Chrome
But it didn't help.
Other threads mentioned that it's a bug in Webkit, but those were old threads and I couldn't find the bug report on Webkit's site.
The problem is that the header has a fixed width picture background and the navigation menu needs to stay within that width.  I've since given up on HTML or CSS methods of accomplishing this.  If you know of any, then please do share.  So I've resorted to JavaScript (jQuery).  And it works reasonably well, except in Chrome.  The text actually increases in size for some odd reason.
Here's the simplified code in JSFiddle:
http://jsfiddle.net/alininja/j4jD9/12/
This gist of the code is this line:
$('body').css('font-size',(content_size-1)+'px');

For FireFox and Opera, the text size decreases to fit the header width, but not in Chrome.
If I run JSFiddle in Chrome everything works, but the funny behavior shows up on the actual website.  This is happening on Chrome 17.0.963.56.
Thanks in advance!

A: If you want presentation consistency cross browser there is more involved than just setting font-size. You are assuming other font property defaults such as font-family are the same cross browser which they are not.
Use of a css reset will help


text:
Q: Issues with Powershell Import-CSV Main Script
$Computers = Get-Content .\computers.txt

If ( test-path .\log.txt ) {
    $Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Succesful"}
} ELSE {
    Add-Content "Computer Name,Is On,Attempts,Result,Time,Date"
}
$Log_Successful | format-table -autosize

Issues:
Log_Successful."Computer Name" works fine, but if i change 4 to read as the following
$Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Failed"}

Log_Successful."Computer Name" no longer works... Any ideas why?
Dataset
Computer Name,Is On,Attempts,Result,Time,Date
52qkkgw-94210jv,False,1,Failed,9:48 AM,10/28/2012
HELLBOMBS-PC,False,1,Successful,9:48 AM,10/28/2012
52qkkgw-94210dv,False,1,Failed,9:48 AM,10/28/2012

A: In case of "Successful" a single object is returned. It contains the property "Computer Name". In case of "Failed" an array of two objects is returned. It (the array itself) does not contain the property "Computer Name". In PowerShell v3 in some cases it is possible to use notation $array.SomePropertyOfContainedObject but in PowerShell v2 it is an error always. That is what you probably see.
You should iterate through the array of result objects, e.g. foreach($log in $Log_Successful) {...} and access properties of the $log objects.
And the last tip. In order to ensure that the result of Import-Csv call is always an array (not null or a single object) use the @() operator.
The code after fixes would be:
$logs = @(Import-Csv ... | where ...)
# $logs is an array, e.g. you can use $logs.Count

# process logs
foreach($log in $logs) {
    # use $log."Computer Name"
}

A: I'm not sure if this is the problem but you have a typo, in Where-Object you compare against "Succesful" and the value in the file is "Successful" (missing 's').
Anyway, what's not working?


text:
Q: Issue with std::map having an std::map value I want to create an std::map that maps QStrings onto another std::map. However, when I try to do this, it insteads seems to map them onto an std::_Tree.
The code that does this is here
// *** Meta Data ****
quint8 numMetaDataItems = getBufferUint<quint8>(&frameData[numMetaDataOffset]);
size_t metaDataItemOffset = numMetaDataOffset + sizeof(numMetaDataItems);
std::map<int, QString> tempMap;

for (int i = 0; i < numMetaDataItems; i++)
{
    int metadataId = getBufferUint<quint8>(&frameData[metaDataItemOffset]);
    QString metadata = QString::fromUtf8((const char*) &frameData[metaDataItemOffset + 1]) ;
    //tempMap.insert(std::pair<int, QString>(metadataId, metadata));
    metaDataModel->metaDataMap[fileName][metadataId] = metadata;
    metaDataItemOffset += headerLength - metaDataItemOffset;
}

When I use the debugger, the key for the map is correct but where the value should be another map, it instead says class std::_Tree<>. Can anyone explain why this is?
EDIT:
So I've realised that the problem may have nothing to do with the map. I try to access the map here:
QList<QString> strings;
for(std::map<int, QString>::iterator it = metaDataMap[frameID].begin(); it != metaDataMap[frameID].end(); it++)
{
    QString tempString = idMap[it->first] + ": " + it->second;
    strings.append(tempString);
}

But since there is only one item in the map it appears that .begin() and .end() are the same, and the code in the for loop is never run. Does that sound like it might be what's happening?

A: As this 'doc' states,

Maps are usually implemented as red-black trees.

This means, that in your compiler std::map<> is essentially a typedefed _Tree<> class, so there is nothing wrong about it.

A:
When I use the debugger, the key for the map is correct but where the
  value should be another map, it instead says class std::_Tree<>. Can
  anyone explain why this is?

This hints at how your compiler implements std::map.
It looks like it's Visual C++. If you look at the header file on your machine (it should be something like C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\map), then you will probably see that std::map publicly derives from _Tree. There's nothing magic about it; it's just plain simple public derivation.
Now, the name _Tree already suggests that it is an implementation detail. A name like this (underscore + capital letter) would not be allowed in your own code, but the compiler itself can use it freely in its own header files. That's because as far as the C++ language is concerned, standard-library header files do not exist. You could perfectly write a conforming C++ compiler without any header files, where user code like #include <map> would be interpreted without reading any files. It's just for simplicity and practical reasons that all C++ compilers I'm aware of (and probably all that have ever existed) ship with header files.
The point is that the compiler's own header files may contain everything, including non-C++ code, proprietary constructs and other weird stuff which clients do not need to be aware of, but which the compiler needs in order to implement the C++ standard library.
_Tree is such a thing. Looking into a standard header file or using the debugger exposes you to it.

All of this is perfectly fine, as long as you don't try to fiddle with it in your own code. For example, take the following evil piece of code:
#include <map>

int main()
{
    // Just for demonstration purposes!
    // Do not EVER try this in production code!

    using namespace std;
    _Tree<_Tmap_traits<int,
        int,
        less<int>,
        allocator<int>,
        false>
    > m{ less<int>(), allocator<int>() };
}

It will very likely compile and work fine with MSVC but make your program non-portable and possibly even non-compatible with future or past versions of the same compiler, because you have used compiler-internal components in your own code.
In short: Your own code must be unaware of the fact that _Tree exists.

A: As you mentioned in your comments, the question is how to access from an std::map see my examples below:
#include<map>
#include<string>
#include<iostream>

int main()
{
    std::map<int,int> key = { {1,2}};
    std::map< std::map<int,int>,std::string> myMap;
    myMap[key]="hello";
    std::string val=  myMap[key];
    std::cout<<val;

}

EDIT
    std::map<int,int> key = { {1,2}};
    std::map< std::string, std::map<int,int>> myMap;
    myMap["hello"]=key;
    auto val=  myMap["hello"];
    for( const auto & p: val)
    std::cout<<p.first<<" "<<p.second;