Problems making nodejs client for yahoo placemaker api

Question: I need to make a nodejs client application that can send a POST request to YAHOO Placemaker API. I spent 1 day on this with no success so far. I see the http packets in Wireshark and it doesn't complain either.
I am using the following code:
var http = require('http');

var options = {
        host: 'wherein.yahooapis.com',
        port: 80,
        path: '/v1/document',
        method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
//  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
// write data to request body
//req.end('documentURL=http://www.usfca.edu&documentType=text/html&outputType=xml&appid=MrIhH33V34GNOpw91rqJuijGeiLQ7l4hhlJXXt3fOTS0.jAUY8kqhu6SxMhy7J90OSWElw--');
req.write('documentURL%3Dhttp%3A//www.usfca.edu%26documentType%3Dtext/html%26outputType%3Dxml%26appid%3DMrIhH33V34GNOpw91rqJuijGeiLQ7l4hhlJXXt3fOTS0.jAUY8kqhu6SxMhy7J90OSWElw--');
req.end();

I do the same in php and it works there. Any suggestions are appreciated. Similar problems occurred when I tried to run my own server on expressjs. Somehow the above code doesn't produce the correct HTTP request. But the above snippet is directly taken from NodeJs documentation
Please Help!!
I get the 400 HTTP response code saying neither documentURL nore documentContent not found!

Lalith
Comment: why are you posting comments to your own question? If you think that your question is not clear enough don't hesitate to update it and include any relevant information which might help people willing to answer it.
Answer: Consider using Mikeal's request library to simplify your life and avoid any strange problems:
npm install request

Also, stop into #node.js and ask questions for a quicker response. Make sure to report back with your findings.
Answer: Node.js http request does not generate the appropriate header Content-Type, so just add it manually. You don't need Express so far...
var options = {
    host: 'wherein.yahooapis.com',
    port: 80,
    method: 'POST',
    path: '/v1/document',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
};


Fetching all contacts in ios Swift?

Question: I am aware of the ios swift has a Contacts Framework where I can fetch contacts, but I cannot find any method to fetch all the contacts together where I can access each of the contacts from that array. All methods for fetching contacts seems to require some sort of conditions. Is there any method where I can get all the contacts together?
Thanks
Comment: see this question: http://stackoverflow.com/questions/3747844/get-a-list-of-all-contacts-on-ios
Comment: @Christopher many of the solutions on that question actually use the Contacts Framework. The second answer gives a detailed explanation.
Comment: @Ollie OP is looking for solution for "Contacts Framework" whereas the link you posted is still ABAddressBook, which I reckon is not helpful.
Answer: Swift 4 and 5. I have create class PhoneContacts. Please add NSContactsUsageDescription key to your info.plist file
 import Foundation
 import ContactsUI

class PhoneContacts {

    class func getContacts(filter: ContactsFilter = .none) -> [CNContact] { //  ContactsFilter is Enum find it below

        let contactStore = CNContactStore()
        let keysToFetch = [
            CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
            CNContactPhoneNumbersKey,
            CNContactEmailAddressesKey,
            CNContactThumbnailImageDataKey] as [Any]

        var allContainers: [CNContainer] = []
        do {
            allContainers = try contactStore.containers(matching: nil)
        } catch {
            print("Error fetching containers")
        }

        var results: [CNContact] = []

        for container in allContainers {
            let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)

            do {
                let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
                results.append(contentsOf: containerResults)
            } catch {
                print("Error fetching containers")
            }
        }
        return results
    }
}

The calling to above method in another class
import ContactsUI
func phoneNumberWithContryCode() -> [String] {

    let contacts = PhoneContacts.getContacts() // here calling the getContacts methods
    var arrPhoneNumbers = [String]()
    for contact in contacts {
        for ContctNumVar: CNLabeledValue in contact.phoneNumbers {
            if let fulMobNumVar  = ContctNumVar.value as? CNPhoneNumber {
                //let countryCode = fulMobNumVar.value(forKey: "countryCode") get country code
                   if let MccNamVar = fulMobNumVar.value(forKey: "digits") as? String {
                        arrPhoneNumbers.append(MccNamVar)
                }
            }
        }
    }
    return arrPhoneNumbers // here array has all contact numbers.
}

Now, Get email and phone of contacts
    enum ContactsFilter {
        case none
        case mail
        case message
    }

    var phoneContacts = [PhoneContact]() // array of PhoneContact(It is model find it below)
    var filter: ContactsFilter = .none

    self.loadContacts(filter: filter) // Calling loadContacts methods

       fileprivate func loadContacts(filter: ContactsFilter) {
            phoneContacts.removeAll()
            var allContacts = [PhoneContact]()
            for contact in PhoneContacts.getContacts(filter: filter) {
                allContacts.append(PhoneContact(contact: contact))
            }

            var filterdArray = [PhoneContact]()
            if self.filter == .mail {
                filterdArray = allContacts.filter({ $0.email.count > 0 }) // getting all email
            } else if self.filter == .message {
                filterdArray = allContacts.filter({ $0.phoneNumber.count > 0 })
            } else {
                filterdArray = allContacts
            }
            phoneContacts.append(contentsOf: filterdArray)

  for contact in phoneContacts {
      print("Name -> \(contact.name)")
      print("Email -> \(contact.email)")
      print("Phone Number -> \(contact.phoneNumber)")
    }
    let arrayCode  = self.phoneNumberWithContryCode()
    for codes in arrayCode {
      print(codes)
    }
     DispatchQueue.main.async {
       self.tableView.reloadData() // update your tableView having phoneContacts array
              }
            }
        }

PhoneContact Model Class
import Foundation
import ContactsUI

class PhoneContact: NSObject {

    var name: String?
    var avatarData: Data?
    var phoneNumber: [String] = [String]()
    var email: [String] = [String]()
    var isSelected: Bool = false
    var isInvited = false

    init(contact: CNContact) {
        name        = contact.givenName + " " + contact.familyName
        avatarData  = contact.thumbnailImageData
        for phone in contact.phoneNumbers {
            phoneNumber.append(phone.value.stringValue)
        }
        for mail in contact.emailAddresses {
            email.append(mail.value as String)
        }
    }

    override init() {
        super.init()
    }
}

Comment: I am having "Conditional cast from 'CNPhoneNumber' to 'CNPhoneNumber' always succeeds" for "if let fulMobNumVar  = ContctNumVar.value as? CNPhoneNumber"
Answer: Many answers to Contact Framework questions suggest iterating over various containers (accounts). However, Apple's documentation describes a "Unified Contact" as

Contacts in different accounts that represent the same person may be automatically linked together. Linked contacts are displayed in OS X and iOS apps as unified contacts. A unified contact is an in-memory, temporary view of the set of linked contacts that are merged into one contact.
By default the Contacts framework returns unified contacts. Each fetched unified contact (CNContact) object has its own unique identifier that is different from any individual contact's identifier in the set of linked contacts. A refetch of a unified contact should be done with its identifier.
Source

So simplest way to fetch a list of (partial, based on keys) contacts in a single array, would be the following:
      var contacts = [CNContact]()
    let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
    let request = CNContactFetchRequest(keysToFetch: keys)

    let contactStore = CNContactStore()
    do {
        try contactStore.enumerateContacts(with: request) {
            (contact, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact)
        }
    }
    catch {
        print("unable to fetch contacts")
    }

Comment: very helpful. if i want to fetch name and number , and if user has multiple number how to solve that situation
Comment: @uzu it should be defined as `contactStore = CNContactStore()` and `self.contactStore.enumerateContactsWithFetchRequest(request)` should be changed to `self.contactStore.enumerateContacts(with: request)`.
Comment: CNContact returns array of CNPhoneNumbers. You can simply take the first number in the array, or iterate over the list and parse the phone number's CNLabeledValues to find the one you want, e.g. "work" or "mobile"
Comment: where is `self.contactStore` comming from?
Answer: Update for Swift 4
let contactStore = CNContactStore()
var contacts = [CNContact]()
let keys = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
                CNContactPhoneNumbersKey,
                CNContactEmailAddressesKey
        ] as [Any]
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
do {
    try contactStore.enumerateContacts(with: request){
            (contact, stop) in
        // Array containing all unified contacts from everywhere
        contacts.append(contact)
        for phoneNumber in contact.phoneNumbers {
            if let number = phoneNumber.value as? CNPhoneNumber, let label = phoneNumber.label {
                let localizedLabel = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label)
                print("\(contact.givenName) \(contact.familyName) tel:\(localizedLabel) -- \(number.stringValue), email: \(contact.emailAddresses)")
            }
        }
    }
    print(contacts)
} catch {
    print("unable to fetch contacts")
}

Comment: Before adding this code add permission request in `.Plist` with key : `Privacy - Contacts Usage Description` and value : `Application wants to access your contacts list.` ...
Answer:     // You may add more "keys" to fetch referred to official documentation
    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]

    // The container means
    // that the source the contacts from, such as Exchange and iCloud
    var allContainers: [CNContainer] = []
    do {
        allContainers = try store.containersMatchingPredicate(nil)
    } catch {
        print("Error fetching containers")
    }

    var contacts: [CNContact] = []

    // Loop the containers
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)

        do {
            let containerResults = try store.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            // Put them into "contacts"
            contacts.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

Answer: A Swift 4.0 implementation to pull in all of the contacts.
let contactStore = CNContactStore()
var contacts = [CNContact]()
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
let request = CNContactFetchRequest(keysToFetch: keys)

do {
    try contactStore.enumerateContacts(with: request) { (contact, stop) in
        contacts.append(contact)
    }
} catch {
    print(error.localizedDescription)
}

This creates a local property to store the contacts, which are then populated via the enumeration against contactStore.
Answer: Please see my answer it is based on answers above with certain improvements, just do the following
In your pod file
source 'https://github.com/CocoaPods/Specs.git'
pod 'PhoneNumberKit', '~> 2.6'

then run pod install
then in your ViewController File
import Contacts
import PhoneNumberKit
import UIKit

override func viewDidLoad() {
    super.viewDidLoad()

    let contactStore = CNContactStore()
    var contacts = [CNContact]()
    let keys = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
        CNContactPhoneNumbersKey,
        CNContactEmailAddressesKey,
    ] as [Any]
    let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
    do {
        try contactStore.enumerateContacts(with: request) {
            contact, _ in
            // Array containing all unified contacts from everywhere
            contacts.append(contact)
            for phoneNumber in contact.phoneNumbers {
                if let number = phoneNumber.value as? CNPhoneNumber, let label = phoneNumber.label {
                    let localizedLabel = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label)

                    // Get The Name
                    let name = contact.givenName + " " + contact.familyName
                    print(name)

                    // Get The Mobile Number
                    var mobile = number.stringValue
                    mobile = mobile.replacingOccurrences(of: " ", with: "")

                    // Parse The Mobile Number
                    let phoneNumberKit = PhoneNumberKit()

                    do {
                        let phoneNumberCustomDefaultRegion = try phoneNumberKit.parse(mobile, withRegion: "IN", ignoreType: true)
                        let countryCode = String(phoneNumberCustomDefaultRegion.countryCode)
                        let mobile = String(phoneNumberCustomDefaultRegion.nationalNumber)
                        let finalMobile = "+" + countryCode + mobile
                        print(finalMobile)
                    } catch {
                        print("Generic parser error")
                    }

                    // Get The Email
                    var email: String
                    for mail in contact.emailAddresses {
                        email = mail.value as String
                        print(email)
                    }
                }
            }
        }

    } catch {
        print("unable to fetch contacts")
    }
}

Comment: Your code performance is very low because of this line `let phoneNumberKit = PhoneNumberKit()` you run this line for all contacts, put it outside of `for` loop.
Comment: @UsmanShahid do you have any other suggestion which works better.. thnks..
Comment: yes use this library, it is very fast and accurate (can be used both in swift & objective-c)
https://github.com/iziz/libPhoneNumber-iOS
Comment: PhoneNumberKit is very expensive in performance especially when you have more than 200 contacts
Comment: What's the benefit of using PhoneNumberKit? Seems like the default Contacts library is fairly straightforward? ♂
Answer: Please Try below function, it helps you (Swift 4)
import UIKit
import Contacts
import ContactsUI

override func viewDidLoad() {
    super.viewDidLoad()

    // `contacts` Contains all details of Phone Contacts
    let contacts = self.getContactFromCNContact()
    for contact in contacts {

        print(contact.middleName)
        print(contact.familyName)
        print(contact.givenName)
    }
}

func getContactFromCNContact() -> [CNContact] {

    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
        CNContactGivenNameKey,
        CNContactMiddleNameKey,
        CNContactFamilyNameKey,
        CNContactEmailAddressesKey,
        ] as [Any]

    //Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containers(matching: nil)
    } catch {
        print("Error fetching containers")
    }

    var results: [CNContact] = []

    // Iterate all containers and append their contacts to our results array
    for container in allContainers {

        let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)

        do {
            let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
            results.append(contentsOf: containerResults)

        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}

Answer: Complex solution:
var contacts = [CNContact]()

let keys: [Any] = [
    CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
    CNContactImageDataKey,
    CNContactEmailAddressesKey,
    CNContactPhoneNumbersKey,
    CNContactJobTitleKey,
    CNContactBirthdayKey,
    CNContactPostalAddressesKey
]

let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
let contactStore = CNContactStore()

try? contactStore.enumerateContacts(with: request, usingBlock: { contact, _ in
    contacts.append(contact)
})

Don't forget about Info.plist:
NSContactsUsageDescription

Fetching all contacts in ios Swift?


im having a runtime error for tic tac toe as i didn't use any functions in this program please once look at the code

Question: i'm getting an error while running this code
i alredy did this using functions but this time i thought of doing it without functions
but there is some kind of error
i dont even know that we can do this tic tac toe like this
from IPython.display import clear_output
import random
print('WELCOME TO TIC TAC TOE\n')
board= [' '] * 10
player2 = ' '
player_1 = None
player_2 = None
turn = player_1
clear_output()
print('     |   |  ')
print('   '+board[7]+' | '+board[8]+' | '+board[9])
print('     |   |  ')
print('---------------')
print('     |   |  ')
print('   '+board[4]+' | '+board[5]+' | '+board[6])
print('     |   |  ')
print('---------------')
print('     |   |  ')
print('   '+board[1]+' | '+board[2]+' | '+board[3])
print('     |   |  ')
marker = ''
while not (marker == 'X' or marker == 'O'):
    marker = input('player 1 do you want to be X or O\n').upper()

    if marker == "X":
        player1 = "X"
        player2 = "O"
    else:
        player1 = "O"
        player2 = "X"

if random.randint(0,1) == 0:
    print('player 1 will go first')
    turn=player_1
else:
    print('player 2 will go first')
    turn=player_2

win_check = False
if ((board[7]==player1 and board[8]==player1 and board[9]==player1) or #horizontal check
           (board[4]==player1 and board[5]==player1 and board[6]==player1) or #horizontal check
           (board[1]==player1 and board[2]==player1 and board[3]==player1) or #horizontal check
           (board[1]==player1 and board[4]==player1 and board[7]==player1) or #vertical check
           (board[2]==player1 and board[5]==player1 and board[8]==player1) or #vertical check
           (board[3]==player1 and board[6]==player1 and board[9]==player1) or #vertical check
           (board[1]==player1 and board[5]==player1 and board[9]==player1) or #diagonal check
           (board[3]==player1 and board[5]==player1 and board[7]==player1)):
    win_check=True
elif ((board[7]==player2 and board[8]==player2 and board[9]==player2) or #horizontal check
           (board[4]==player2 and board[5]==player2 and board[6]==player2) or #horizontal check
           (board[1]==player2 and board[2]==player2 and board[3]==player2) or #horizontal check
           (board[1]==player2 and board[4]==player2 and board[7]==player2) or #vertical check
           (board[2]==player2 and board[5]==player2 and board[8]==player2) or #vertical check
           (board[3]==player2 and board[6]==player2 and board[9]==player2) or #vertical check
           (board[1]==player2 and board[5]==player2 and board[9]==player2) or #diagonal check
           (board[3]==player2 and board[5]==player2 and board[7]==player2)):
    win_check=False

board_check = True
for i in range(1,10):
        if board[i] == ' ':
            board_check = True
        else:
            board_check = False
position = 0
gameon = True
while gameon == True:
    if turn == player_1:
        while position not in [1,2,3,4,5,6,7,8,9] or not board[i] == ' ':
            position = int(input("Enter the position (1-9)"))
            board[position] = player1
            if win_check == True:
                print("player1 WON!!")
                print('     |   |  ')
                print('   '+board[7]+' | '+board[8]+' | '+board[9])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   '+board[4]+' | '+board[5]+' | '+board[6])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   '+board[1]+' | '+board[2]+' | '+board[3])
                print('     |   |  ')

                gameon = False
                break
            else:
                if board_check == False:
                    print('     |   |  ')
                    print('   '+board[7]+' | '+board[8]+' | '+board[9])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   '+board[4]+' | '+board[5]+' | '+board[6])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   '+board[1]+' | '+board[2]+' | '+board[3])
                    print('     |   |  ')
                    print('game is Draw')
                else:
                    turn = player_2

    else:
         while position not in [1,2,3,4,5,6,7,8,9] or  not board[i] == ' ':
            position = int(input("Enter the position (1-9)"))
            board[position] = player2
            print("player2 WON!!")
            print('     |   |  ')
            print('   '+board[7]+' | '+board[8]+' | '+board[9])
            print('     |   |  ')
            print('---------------')
            print('     |   |  ')
            print('   '+board[4]+' | '+board[5]+' | '+board[6])
            print('     |   |  ')
            print('---------------')
            print('     |   |  ')
            print('   '+board[1]+' | '+board[2]+' | '+board[3])
            print('     |   |  ')
            if win_check == True:
                print("player2 WON!!")
                print('     |   |  ')
                print('   '+board[7]+' | '+board[8]+' | '+board[9])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   '+board[4]+' | '+board[5]+' | '+board[6])
                print('     |   |  ')
                print('---------------')
                print('     |   |  ')
                print('   '+board[1]+' | '+board[2]+' | '+board[3])
                print('     |   |  ')
                gameon = False
            else:
                if board_check == False:
                    print('     |   |  ')
                    print('   '+board[7]+' | '+board[8]+' | '+board[9])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   '+board[4]+' | '+board[5]+' | '+board[6])
                    print('     |   |  ')
                    print('---------------')
                    print('     |   |  ')
                    print('   '+board[1]+' | '+board[2]+' | '+board[3])
                    print('     |   |  ')

                    print('game is Draw')
                else:
                    turn = player_1

    replay = input('Do you wnt to play again? Y or N').lower()
    if replay == 'y':
        continue
    else:
        break

if you could help it will be very usefull for me as im a beginner
in python programing
in this code i cannot get out of while loop and it dosent show any result
Comment: Add the error traceback to the question.
Comment: Your code that checks for a win is before anyone plays, it's not in the loop. The loop that sets `board_check` overwrites the value each time through the loop, so it's just the value from `board[9]`. `while position not in [1,2,3,4,5,6,7,8,9] or not board[i] == ' '` should use `and`, not `or`.
Answer: In the code, win_check and board_check should be functions so you can recheck the status at each turn.
Try this code:
def win_check():
    if ((board[7]==player1 and board[8]==player1 and board[9]==player1) or #horizontal check
               (board[4]==player1 and board[5]==player1 and board[6]==player1) or #horizontal check
               (board[1]==player1 and board[2]==player1 and board[3]==player1) or #horizontal check
               (board[1]==player1 and board[4]==player1 and board[7]==player1) or #vertical check
               (board[2]==player1 and board[5]==player1 and board[8]==player1) or #vertical check
               (board[3]==player1 and board[6]==player1 and board[9]==player1) or #vertical check
               (board[1]==player1 and board[5]==player1 and board[9]==player1) or #diagonal check
               (board[3]==player1 and board[5]==player1 and board[7]==player1)):
        return True
    elif ((board[7]==player2 and board[8]==player2 and board[9]==player2) or #horizontal check
               (board[4]==player2 and board[5]==player2 and board[6]==player2) or #horizontal check
               (board[1]==player2 and board[2]==player2 and board[3]==player2) or #horizontal check
               (board[1]==player2 and board[4]==player2 and board[7]==player2) or #vertical check
               (board[2]==player2 and board[5]==player2 and board[8]==player2) or #vertical check
               (board[3]==player2 and board[6]==player2 and board[9]==player2) or #vertical check
               (board[1]==player2 and board[5]==player2 and board[9]==player2) or #diagonal check
               (board[3]==player2 and board[5]==player2 and board[7]==player2)):
        return False

def board_check():
   for i in range(1,10):
        if board[i] == ' ':
            return True
        return False

In the game loop, refer to these as functions:
if win_check() .......
if board_check() .......


Multiple Spark Workers on Single Windows Machine

Question: I am trying to teach myself Spark through Scala using Intellij on Windows. I'm doing this on a single machine, and I would like to start multiple workers on the single machine to simulate a cluster. I read this page where it says that
"The launch scripts do not currently support Windows. To run a Spark cluster on Windows, start the master and workers by hand."
I don't know what it means to start the masters and workers by hand. Could anyone help? Many thanks for any help/suggestions.
Comment: You probably need to use Standalone, that means you have to set manually the master and the workers. Meaning, that you have to indicate the location, the memory that they will use, etc.
Comment: Thanks Alberto, I'm currently using Standalone successfully but I am unable to start multiple workers. What are the scripts that must be executed to launch multiple workers on a single machine?
Comment: @BenjiKok, if you are running on a single machine, your machine serves both as the master and as a single worker.
Comment: Thanks John, I've marked Naresh's suggestion as the answer since it allows for the registration of multiple workers.
Answer: To manually start Spark Master, run below command from %SPARK_HOME%\bin
spark-class org.apache.spark.deploy.master.Master

Above command will also print master URL like spark://ip:port
Master UI can be accessed at localhost:8080
To start Spark Worker, run
spark-class org.apache.spark.deploy.worker.Worker spark://ip:port

Now if you refresh Master UI, you can see the new worker listed under Workers section.
Repeat the command to add multiple workers to the same master.


Liftweb - Maximum value of a SQL table field with mapper

Question: I would like to find a simple way to access the maximum value of a Mapped element in liftweb, here is an example of what I actually do:
Mapper part
class MappedEntity extends LongKeyedMapper[MappedEntity] with IdPK {
  def getSingleton = MappedEntity
  object targetRaw extends MappedInt(this)
}

object MappedEntity extends MappedEntity with LongKeyedMetaMapper[MappedEntity]

Search part
val max = MappedEntity.findAllByInsecureSql(
  "SELECT MAX (targetRaw) AS targetRaw FROM MappedEntity",
  IHaveValidatedThisSQL("chris", "2011,11,14")
  ).head.targetRaw.get

When supposing that I work with the SQL table called MappedEntity, I want max to contain either a string or an int equal to the maximum value contained in targetRaw
If you have any suggestion or any question I will be happy to help.
Answer: I don't believe that lift-mapper has a built-in way of running this query. In fact, it's very short on any sort of aggregate functions.  All I see are some count methods.
The find* methods are only suitable for returning objects of the Mappers type, as you can see by their return types.
Given that there's no great way to do this in Lift as it stands, you have several options to choose from.

Use lift-squeryl-record instead of lift-mapper. Squeryl is a more complete ORM, and supports group and aggregate functions.
Create your own trait which adds max functions to a MetaMapper. This would be a bit of work, but you can use the implementation of count as a guide.

Technically, there could be a more general implementation that handles all of the aggregate functions (max, min, sum, count, ...). That may be what we in the business call 'overkill'.

Just write some SQL. Lift offers a loan-pattern way of obtaining a connection to the database. It also has loan-pattern helpers for preparing statements and executing queries in such a was that everything is automagically closed when you're done with it.
DB.use(DefaultConnectionIdentifier) { conn =>
  // execute query
}

Find the object with the value your looking for, then just retrieve that field. This has the distinct disadvantage of being ugly, slow and brittle.
val max: Option[String] = MappedEntity.findAll(
  BySql("targetRaw IN (SELECT MAX (targetRaw) FROM MappedEntity)",
    IHaveValidatedThisSQL("chris", "2011,11,14")).map(_.targetRaw.is).headOption

Comment: Thanks for the very complete answer, I think I will explore solution 3.
Comment: That's certainly the most straightforward!
Comment: Can you please provide the request used in solution 3, it would make your answer complete and perfect.
Answer: Here is the solution I finally used:
val max = DB.runQuery("SELECT YEAR(MAX(targetRaw)) FROM targetTable")._2.head.head.toInt


Undefined symbols for architecture x86_64 when switching to Debug

Question: I get the following error, when I switch the scheme to Debug. In Release I can build without any problems.
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_RCTReconnectingWebSocket", referenced from:
      objc-class-ref in libReact.a(RCTPackagerConnection.o)
  "_OBJC_CLASS_$_RCTSRWebSocket", referenced from:
      objc-class-ref in libReact.a(RCTInspectorPackagerConnection.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Pod File:
target "xy" do
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
    'CxxBridge' # Include if RN >= 0.47
  ]
  pod 'DoubleConversion', podspec: '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'Folly', podspec: '../node_modules/react-native/third-party-podspecs/Folly.podspec'
  pod 'GLog', podspec: '../node_modules/react-native/third-party-podspecs/GLog.podspec'

  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
  pod 'Firebase/Core'
  pod 'GoogleToolboxForMac/NSData+zlib'
  pod 'CodePush', :path => '../node_modules/react-native-code-push'
  pod 'react-native-fetch-blob', :path => '../node_modules/react-native-fetch-blob'
  pod 'RNShare', :path => '../node_modules/react-native-share'
  pod 'react-native-fbsdk', :path => '../node_modules/react-native-fbsdk/ios'
  pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'

end

Answer: You can try to add it to your pod 'React' section like this:
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
    'CxxBridge',
    'RCTWebSocket'
 ]

Don't  forget to run pod install.
If this doesn't work:

open XCode,
click to your Project-Root
choose your Target
Tab: Build Phases
Link Binary with Libraries
Press the + (on the buttom of this Section) and
add libRCTWebsocket.a

This should fix it.


Need to Implement Custom Dimensions through Google Tag Manager

Question: I have created virtual pageview tag successfully for " New Registrations" via Google Tag manager.
Now, I want to add two custom dimensions using same Tag i.e. Customer ID and UserRole.
Actually, I am not sure where to add the code to get dynamic values for CustomerID and UserRole. Can you guide me to complete this?
Answer: Custom dimensions are configured either in the Google Analytics settings variable (if you use this), or in the tag via the "More Settings" >> "Custom Dimensions" settings or both.
If you use a settings variable and want to add extra dimensions to a specific tag you need to tick the "Enable override settings" checkbox.
In the settings you enter in the first field the numeric index of the dimensions (you can look this up in the property settings of your GA account where you have created the dimensions), the second field takes the variable with a value (or a simple string if it's not a dynamic value).
Comment: Thank you so much for answering my question. I have taken few steps which are:

Created new Custom dimensions in GA. You can see here: http://tinypic.com/view.php?pic=2ywctp2&s=9

Created 'Custom Variables" in GTM against each "Custom dimension". And added "Index value" and "Dimension value" into a GTM tag. You can see here: http://tinypic.com/r/f0sncz/9
Comment: FYI: I have added following data layer for registration virtual page view.
window.dataLayer.push({ 'event' : 'virtualPageview', 'virtualPageURL' : '/virtual/registration-complete', 'VirtualPageTitle' : 'Registration Complete'});

Do I need to push separate data layer for custom dimensions? Do I need to add anything under trigger?

Please advice!!
Comment: Can Anyone please help me on this?


Derivative of a trigonometric function

Question: What is the derivative of $$\cos^2 a (\tan a - \tan b)$$
Please anyone explain in detail.
The differentiation is with respect to $a$. I tried to obtain the answer using chain rule, but didn't get it. Must be facing some problem. The simplified form is $$1-\sin a \cos a (\tan a-\tan b)$$
Comment: can you use $\LaTeX$ please?
Comment: I am a class 11 student so I hope the solution match my standards
Comment: But how in this case I can use f as a function of g (x)?
Answer: You will have to use both the chain rule and the product rules for derivation.
First you have $$\cos^2(a)(\tan(a)-\tan(b))$$
you can first expand to obtain
$$\cos^2(a)\tan(a)-\cos^2(a)\tan(b)$$
Now the chain rule you have to use it with $\cos^2(a)$, you have $f(a)=\cos(a)$, $g(a)=a^2$ and you have the composite function $g\circ f (a)$.
EDIT: Given $g\circ f (a)$, you want to calculate $\frac{d(g\circ f (a))}{da}$.
So the chain rule says $\frac{d(g\circ f (a))}{da}=\frac{d(f (a))}{da}\cdot \frac{dg(f(a))}{da}$
Now $\frac{d(f (a))}{da}=-sin(a)$, $\frac{dg (f(a))}{da}=2cos(a)$ and therefore $\frac{d(g\circ f (a))}{da}=-2sin(a)cos(a)$
However you will have to use also the product rule, since you have $(uv)'=u'v+uv'$ Of course in the first term, $u=\cos^2(a)$, $v=\tan(a)$.
Therefore, first calculate $u'$, using the chain rule, then calculate $v'$ and then use the product rule formula!
Comment: Yes, I understood that but can u explain the chain rule part please?
Comment: edited over there
Comment: Yes now I get it..but does the derivative square of anything applies the general formula of na^ (n-1)? So in that case cos^2 a changes to 2 cos a, by the general formula...is it plausible?

Derivative of a trigonometric function


Our local web server is displaying the IP address instead of the named URL

Question: We installed an apache2 web server to run inside our network. We updated our DNS 'A Record' to point our custom URL. We can paste that address in our browsers and it redirects but afterwards it displays the IP address instead of the actual name. I am including some config files below.
Setting the name of the $wgServer property to the name and not the IP in the LocalSettings.php causes the site to be not found.
media wiki LocalSettings.php
## The protocol and server name to use in fully-qualified URLs
$wgServer = "http://wiki.inovationind.com";

MY_SITE.conf
<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/mediawiki
    ServerName wiki.innovationind.com/

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

apache2.conf
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.

# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# The directory where shm and other runtime files will be stored.
#

DefaultRuntimeDir ${APACHE_RUN_DIR}

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 188.8.131.52 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Comment: I'm voting to close this question because, as the dns tag states: DNS QUESTIONS MUST BE PROGRAMMING RELATED. Use this tag for programming questions related to writing code that interacts with the Domain Name System (DNS); for example, writing code that uses gethostbyname()
Comment: we need more information, could you show your dns records, and also your apache conf files, thanks
Comment: Once your DNS is set correctly (sounds like it is), webservers don't automatically switch back to their IP. There's *something* in your mediawiki or webserver configuration that does this, unrelated to DNS. I would guess that you gave mediawiki this url, so start there.
Comment: @Rob I removed the dns tag
Comment: @DeanVanGreunen I added more info
Comment: The problem is that your question is about DNS and DNS questions are off topic. Removing the tag doesn't change that.
Comment: That your problem was based on a typo also makes your question off topic. Please delete this.
Answer: The issue was that I misspelled the name of my URL in the mediawiki LocalSettings.php. $wgServer = "http://wiki.inovationind.com"; should have been $wgServer = "http://wiki.innovationind.com"; . This link and the comments under my post helped.


Replace substring when knowing only position and structure

Question: I have this situation where i have a string of which i have to replace certain parts. I know where these parts are and what they look like (in other words i can match them through a regex) but not only i don't know the exact content but there might be similar substrings inside a string.
What i want to achieve is to replace only the particular occurrence at that offset while leaving the rest intact.
An Example:
Test String (this) Test (not this) Test Test (this) Test Test (and this) Test (this maybe)

I know i have to replace strings that match this regex: \(.*?\) but only if they start in positions 12, 62 and 78 (in other words, the first (this) but not the second, (and this) and (this maybe). the substrings (not this) and the second (this) must not be replaced)
I know i should be posting my attempts at the problem but i'm staring at the code since half an hour and no idea came out of it (i've been staring at code for longer time before giving up and ask in the past, but today i'm a bit in a hurry) but i have this feeling the solution is simpler than i think. The only thing i have realized is that i should replace strings in reverse order so i don't modify the positions
Comment: Oh, right, my bad.
Comment: That regex will match anything. So even if you find a match starting at position 12, it will match the entire string from position 12 to the end of the string. Are you *sure* that's what you want?
Comment: The regex will match anything inside paranthesis (notice they are escaped)
Comment: So it is always 4 characters inside the brackets?
Comment: No it's any number of characters inside brackets in specific positions (see my edit for clarification)
Comment: can you use strpos to find the position and go from there?
Comment: may be this helps you https://stackoverflow.com/a/23556649/9699530 combined with the limit parameter you could get what you want.
Comment: @IdontDownVote i already have the position, i don't know what the substring exactly is
Answer: Here's what I came up with:
$string = 'Test String (this) Test (not this) Test Test (this) Test Test (and this) Test (this maybe)';

$offsets = [12, 62, 78];
$replace = "REPLACED";

// work backwards so we don't have to keep track of changing offsets
rsort($offsets);

foreach ($offsets as $offset) {
    $string = preg_replace('/^(.{' . $offset . '})\([^\)]*\)/', '$1'.$replace, $string);
}

echo $string;
// Test String REPLACED Test (not this) Test Test (this) Test Test REPLACED Test REPLACED

Note that the second (this) was not replaced, because it doesn't start at offset 12, 62 or 78. That one is actually at offset 45, if you add it to the $offsets array it will be replaced as well.
I noticed in my tests that \(.*\) is too broad for the way I solved it, and I changed it to \([^\)*\) instead (essentially: match anything within brackets as long as it's not a closing bracket itself). I had to do this, because \(.*\) also matched (this) Test (not this).
Comment: Thanks! it worked. It also works using \\(.*?\\) Using .* without ? makes it greedy and will match until the last occurrence of the next character while adding ? makes it non-greedy and will match only until the first. I know there won't be brackets inside brackets so i'm ok with this regex


My image in ImageView glitches for a second

Question: I'm using Xcode 5.1.1
When i click the BACK button from ViewController 1 to ViewController 2, and when VC 1 appears the ImageView glitches for 1 second before going back to normal. I tried programming the segue with performSegueWithIdentifier but that didn't solve the issue. I tried using Modal's cross dissolve transition, cover vertical and partial cross but they don't help the glitch either. Only Flip Horizontal doesn't have the glitch but it wouldn't look good with my app. I'm currently using unwind segue to go from VC 2 to VC 1 but the VC 1 is glitching for 1 second. I tried regular modal but that creates worse problems. What do i do?
Answer: Well you should admit that "The UIImageView" is quite a generic assumption to figure out what your issue actually is. Just for pure diagnosis purpose I'd do the following checks:

Check the size of your UIImage you're assigning to the UIImageView. If the UIImage is too big the higher resolution might cause some rendering problem in the animations.
To have a proper check of what's going on you might want to run instruments adding "Time Profiler" to your tab. Performing either the pop or dismiss of your VC2 you should be able to figure out where the glitch comes from.

I know it's quite a generic answer but with the little info you provided don't think anyone might be able to help you more than that.
Hope this helps.


Microphone issue in audio streaming using FFMPEG

Question: I executed the command
ffmpeg -list_devices true -f dshow -i dummy

to find out that the audio device is 'Realtek HD Audio Input'.

But executing the command
ffmpeg -f dshow -i audio="Microphone (Realtek HD Audio Input" -acodec libmp3lame -ab 128k -ac 2 -ar 44100 -re -f rtp://10:14:35:12:1234

gives the error
"Could not find audio device. audio='Microphone (Realtek HD Audio Input: Input/output error"

I have checked for the working of the microphone and it works fine. Please let me know what is the issue here.
The machine runs on Windows-XP SP2.
Comment: Not 100% sure but is the "Microphone (" prefix really needed?
Comment: Does `ffmpeg -f dshow -list_options true -i audio="Microphone (Realtek HD Audio Input"` list correct information about the microphone
Comment: No! it gives an error "Could not find audio device". But the command - 'ffmpeg -list_devices true -f dshow -i dummy' shows Realtek HD Audio Input as the audio device.
Comment: @RudolfsBundulis: yes you are right! it was not really needed! thanks for pointing it out :)
Comment: Ok, i formulated that as an answer so you can accept it.
Answer: From the input and screenshots given, it seems that you are using the wrong name (apparently could be from an example in another post), if the device is named Realtek HD Audio Input then that is what should be passed to the command line call to ffmpeg.


Do's & Don'ts for Island traveling?

Question: Anyone got a list of things what you can bring for the island later on in the game and items you have to leave behind?
Answer: You can't take anything to the island except what you're wearing. No tools or items of any sort except clothing items that you are currently wearing. Note that wetsuits you are currently wearing count as clothes (so you can take them) but can still be used as tools on the island. Though this isn't a huge advantage as you can rent a wetsuit on the island anyway.
Tools instead will be provided by a Gyroid at the island and on each of the tours. You can take any non-tour related item back to your town by leaving it in the basket in the hut when you first reach the island. All other items will be sold at an extremely low price when you go home or go on a tour.
Comment: Can you currently wear an umbrella? Or you have to leave that behind as well?
Comment: @GraemeHunter good point I've noticed that as well, added.
Comment: You can take a wetsuit to the island if you're wearing it, in that instance it counts as clothing rather than a tool (It's kind of got tool functionality as it lets you do something specific).
Comment: @spongefan12 Umbrellas are equipment, so you automatically put it away when boarding Kapp'n's boat. It's left behind with your other inventory.

Do's & Don'ts for Island traveling?


The polynomial subspace

Question: Let $A$ be a set of 6 polynomials in $\mathbb{R}_5[x]$ over $\mathbb{R}$ field,
assume $sp(A) = \mathbb{R}_5[x]$ which of the following is true?
1. It might be that $A$ holds exactly 4 polynomials from second degree.
2. It might be that $A$ holds exactly 4 polynomials from first degree.
I think the two argument are equivalent, and in order to span $\mathbb{R}_5[x]$
a set must have $6$ vectors, and since 4 of the vectors are in 2nd or 3rd degree it means there will always be an unreachable vector and thus the groups described in 1. and 2. cannot span $\mathbb{R}_5[x]$.
Comment: Can you be more explicit why your argument fails with **3.** It might be that $A$ holds exactly 4 polynomials from third degree?
Comment: Consider $F$ the span of the 4 polynomials in the assumptions and $G$ the span of the other two. Then use $6=\dim (F+G)\leq \dim F+\dim G$ to reach a contradiction.
Comment: The question only mentions first and second degree, I didn't understand your question.
Answer: Your argument is not exact, you claim that there will be unreachable
vectors but you because of the given assumption - but you don't explain
why.
Hint: What is the dimensions of $\mathbb{R}_{1}[x],\mathbb{R}_{2}[x]$
?
Recall that if $V$ is of dimension $n$ then any $n+1$ vectors
are lineally dependent.
Note: the subset of all polynomials of degree exactly $2$ (or exactly
$1$) is not a vector subspace (since, for example $x^{2}+(-x^{2})=0$
is not in this subset, or $(x^{2}+x)+(-x^{2})$).
Comment: I don't understand why $A$ must be linearly dependent, the standard basis hold $(1, x, x^2, x^3, x^4, x^5)$ which are $6$ vectors.
Comment: I say that if we assume that $v_i = \alpha_i + \beta_ix +\gamma_ix^2$ for $1 \leq i \leq 4$ and $\alpha, \beta, \gamma \in \mathbb{R}$ then there are two more vectors left to be in any degree, assume one is from 3rd and one is from 4th degree, none could get to a 5th degree polynomial by any linear combination.
Comment: @Georgey - First, $A$ need not be linearly dependent. But with any of the assumptions
$1$ or $2$ in the question, I provided with a hint to prove it does
indeed linearly dependent hence can not span $\mathbb{R}_{6}[x]$
(since then the span of $A$ is at most of degree $5$).

Secondly, What if the other vectors are something like $x^{5}+x^{4}-2x^{3}+x^{2}-1$
and $x^{5}-x^{4}+x^{3}+x+1$ ? maybe there is some linear combination
to give each $x^{i}$ that is needed
Comment: $A$ needs to span $\mathbb{R}_5$ and not $\mathbb{R}_6$. I haven't understand your hint, I know that $dim(\mathbb{R}_1) = 1$ and $dim(\mathbb{R}_2) = 2$ but how does it help me to prove the required? If $A$ needs to span $\mathbb{R}_5[x]$ and has 6 vectors, then $A$ has the exact same number of vectors such as the basis of $\mathbb{R}_5[x]$.
Comment: I think it might be easier to prove that if __1.__ or __2.__ exist then $A$ is not a vector subspace.
Comment: @Georgey - $A$ can not be a vector subspace since its cardinalty is $6$. Proving this does not require the assumption $1$ or $2$
Comment: @Georgey - I used the same notation as you - the polynomials over $\mathbb{R}^1$ or $\mathbb{R}^2$ which have dimensions $2,3$ accordingly. hence any subset of $4$ elements are  linearly dependent, then $A$ is  linearly dependent
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8935/discussion-between-georgey-and-belgi)
Answer: In short:
$$A:=\,\{x^4\,,\,x^4+1\,,\,x^4+x\,,\,x^4+x^2\,,\,x^3\,,\,x^5\}\;\implies \,\text{Span}(A)=\Bbb R_5[x]$$
and $\,A\,$ contains four quartic polynomials (check the above vectors are line. independent) .
OTOH, if $\,A\,$ contains four linear polynomials then it automatically is a linearly dependent set, since all these four linear pol's are elements of $\;\Bbb R_1[x]\;$ , which is a two-dimensional space, so that $\,\text{Span}(A)\;$ cannot be the whole $\,\Bbb R_5[x]\,$

The polynomial subspace


printing graphics images

Question: I almost always have the problem of files with graphic images (jpg, png, pdf) printing only one-fourth or less of the size of the full 8.5 x 11 page even though the page setup is correct and the print preview shows a full page output. How can I always get the full page when I want it?
Comment: What printer / printer driver are you using?
Answer: This is not an Ubuntu problem. Check your printer's settings. Most probable it is set to print multiple pictures on the same sheet. Look for N-page Up setting or similar.

printing graphics images


Passing variables from php to mysql query and displaying

Question: Can anyone tell me how to pass the php values $value_aid and $value_tradeid to my sql query res3 please ?
<?php
//error_reporting(E_ALL);

///////////////////////Connect to the database and close the connection when finished///////////////////////////////

include ("dbconnect.php");

///////////////////////////////// Gather and Display area_id //////////////////////////////

$res=mysql_query("SELECT area_id FROM pc_test WHERE postcodes = '".$_POST['postcode']."'");
while ($row = mysql_fetch_array($res))
{
// This works !!
//echo("$row[area_id]");
$value_aid="$row[area_id]";
echo("$value_aid");
}

////////////////// Gather and Display postcodes relating to area_id ////////////////////////

$res3=mysql_query("SELECT trade_id FROM trade WHERE trade_type = '".$_POST['trade_type']."'");
while ($row3 = mysql_fetch_array($res3))
{
// And this works !!
echo("\n$row3[trade_id]");
$value_tradeid="$row3[trade_id]";
}

/**************************************** Gather the query information ********************************************/

//************!!!!!!!!!!!!!!!!  This part does not work as the variable values are not being passed !!!!!!!!!!!**********//

$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '$value_aid' && trade_id = '$value_tradeid'");

/**************************************** DISPLAY QUERY RESULTS HERE *********************************************/
while ($row2 = mysql_fetch_array($res2))

{

echo("
SEARCH RESULTS	");
echo("
Name :\n$row2[first_name]\n$row2[last_name]
");
echo("
Phone :\n$row2[phone_mobile]
");
echo("
Postcode :\n$row2[postcode]
");
echo("
Trade Type :\n$row2[trade_type]

");
}

/*********************** If no matching records in my table...DISPLAY MESSAGE HERE ******************************/

if (mysql_num_rows($res2) == 0) {

echo ("

No one is advertising for this area just yet, sorry.
We will have tradesmen advertising here very soon.");
}

//include ("db_close.php");

?>

Comment: Please either consider using [PDO](http://php.net/manual/en/book.pdo.php) or escaping your values beforehand. You have an SQL injection vulnerability
Comment: Your problem is that $res3 and $res are tables. Consider run or prepare sql query in a loop.
Answer: first of all, dont pass variables you get from the user (_POST, _GET, ...) directly into Database queries without escaping them (e.g. mysql_real_escape_string($_POST['name']) this leads to massive security problems (SQL Injection)
to assign a variable with the value of a nother variable you simply use:
$value_tradeid = $row['trade_id'];

Variables doesnt need to be capsuled as strings, but array keys should !
On the queries which dont work, why you dont escape the strings, like you have done in the others obove.
$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '".$value_aid."' && trade_id = '".$value_tradeid."'");

you should also read about PDO and Prepared Statements.


Are there formulas for $\sin\left(\frac{\theta}{3}\right)$ and $\cos\left(\frac{\theta}{3}\right)$?

Question: So far, I have seen the half angle formula (i.e.)
$$\sin^2\left(\frac{\theta}{2}\right) = \frac{1-\cos\theta}{2}$$
Is there a way to find $\sin\left(\frac{\theta}{3}\right)$ and $\cos\left(\frac{\theta}{3}\right)$ in terms of $\sin\theta$ and/or $\cos\theta$ (i.e. a closed form solution)?
Comment: If you don't accept Cardano's formula for the roots of a cubic (coming from triple angle formula) then there is no formula. This is because an approach to solving a cubic is also to use that same triple angle formula, reducing solving a cubic to find $\cos(\theta/3)$. In other words, the two problems are equivalent. Either you accept complex third roots, or accept that there is no formula. Yes, I'm aware that for some cubics you would rather use hyperbolic cosine as opposed to the trig cosine, but that's not really relevant.
Comment: Mind you. In the same sense the ability to calculate half-angle trig functions is equivalent to the ability to solve quadratics (or to take square roots).
Comment: You have gotten it wrong. It's $\sin^2 \frac{\theta}{2}=\frac{1-\cos \theta}{2}$
Comment: Oops, sorry, a typo! Just fixed it.
Comment: Are you familiar with the formulae of $\sin 3A$ and $\cos 3A$ and their derivations?
Comment: @AryanSonwatikar I have tried that. Replacing $A$ by $A/3$ in the formulae for $\sin3A$ and $\cos3A$ gives a complicated mess.
Comment: @impopularGuy, it seems like there's no closed form, is it?
Comment: @impopularGuy now that I realize, my approach doesn't give a closed form. You can try and solve the cubic generated though.
Comment: How about $\cos{x/3}=(e^{ix/3}+e^{-ix/3})/2$ ? Replace $e^{ix}=\cos{x}+i\sin{x}$.
Comment: @impopularGuy then it strays into the territory of complex numbers. And taking cube root of a complex number is not that easy.
Comment: Have a look at [this](https://math.stackexchange.com/a/1552459/585410)
Comment: The knowledge in my link is super advanced, and it may not necessarily apply to all $\theta$...
Answer: There is no analytic formula for $\sin\frac{\theta}{3}$ & $\cos\frac{\theta}{3}$ . But the value of $\sin\frac{\theta}{3}$ & $\cos\frac{\theta}{3}$ can be derived in terms of $\sin\theta $ & $\cos\theta$ using triple angle formula (which may also give complex roots) as follows
$$\sin3x=3\sin x-4\sin^3x$$
setting $3x=\theta$ or $x=\frac{\theta}{3}$ in above trig. identity,
$$\sin\theta=3\sin \frac{\theta}{3}-4\sin^3\frac{\theta}{3}$$$$\boxed{4\sin^3\frac{\theta}{3}-3\sin \frac{\theta}{3}+\sin\theta=0}$$
Similarly,
$$\cos3x=4\cos^3x-3\cos x$$
Setting $3x=\theta$ or $x=\frac{\theta}{3}$ in above trig. identity,
$$\boxed{4\cos^3\frac{\theta}{3}-3\cos \frac{\theta}{3}-\cos\theta=0}$$
Comment: Couldn't you use Cardano's formula to give analytical solutions, at least for certain intervals of $\theta$?
Comment: What @KyleMiller says. How so would a cubic equation not have a closed form solution?
Comment: Absolutely right. there was mistake. Thanks @JensRenders


Access selected value from react's Select Component

Question: Hello dear community,
I want to create a very basic website for my school assignment.
I have a dropdown menu with a Select Component as its implementation. I need to access the selected value, which is a currency in my case, in order to update the information displayed on the page once a currency has been selected.
I am kind of frustrated since I wasn't able to find a helpfull solution to my relatively basic problem (I think it's basic :D)
My component class here:
import { Component } from "react";
import Select from 'react-select';

interface DropdownMenuProps {
  values: [{}]
  defaultValue: string
}

interface DropdownMenuState { }

/**
 * Represents a Dropdown Menu
 */
export default class DropdownMenu extends Component<DropdownMenuProps, DropdownMenuState> {

  render() {
    return (

        <Select id="dropdown-menu"
          placeholder={this.props.defaultValue}
          options={this.props.values}
        // getOptionValue={(option) => option.value}
        // getOptionLabel={(option) => option.label}
        />

    )
  }
}

This is how I create a dropdown menu compent:
<DropdownMenu defaultValue="Currency" values={[{ label: "EUR", value: "EUR" }, { label: "GBP", value: "GBP" }, { label: "USD", value: "USD" }]} ></DropdownMenu>

I'm glad for any tips :)
Answer: I recommend you using directly onChange and save it into a state:
1st:
Create state with the name you want:
const [selectValue, setSelectValue] = useState({});

2nd: Create options:
  const options = [
    { label: "Tomate", value: 1 },
    { label: "Queso", value: 2 }
  ];

3rd: add method onChange in select and pass options:
  const onChange = (ev) => {
    setSelectValue(ev);
    //console.log(ev);
    console.log(selectValue);
  };

  <Select
    id="dropdown-menu"
    placeholder={"e"}
    options={options}
    onChange={onChange}
  />

I have created demo here:
https://codesandbox.io/s/ancient-pond-96h53?file=/src/App.js
Comment: thanks for taking the time to answer! :)
Answer: You have to use the onChange prop of react-select:
<select
id="dropdown-menu"
onChange={handleSelectChange}
>

and in this function you could handle the changes:
const handleSelectChange = (selectedVal) => console.log(selectedVal)

Comment: Wow, thank you so much. This is all I wanted :) I think I need more theoretical knowledge on how typescript/javascript works. Like e.g how is it possible for `handleSelectChange` to be called without a parameter?
Comment: You could look more into the props of react-select: https://react-select.com/props. There you'll also see the onChange


Session variable empty after page reload

Question: Only one of my many session variables on the cart page of my e-commerce application is getting destroyed somehow. When i add the product to the cart along with a session id, it creates an order_id(using some hash and salt logic) and puts it in session variable and when i go to the cart page it queries the DB based on both order_id and session id to fetch the products in the cart. For the first time it fetches the records, but immediately after it if i reload the page it gets an empty order_id. I'm pulling my hair on this as to how only one of the session variables is getting flushed.
It is happening on the web-server only but works totally fine on localhost
My add_to_cart.php (Session Logic)
if(empty($_SESSION['sessid'])){
    $_SESSION['sessid'] = session_id();
}

    $user_sessid = $_SESSION['sessid'];

  $ip = get_ip_address();

 if(empty($_SESSION['order_id'])){

    $ip = get_ip_address();
    $with_time = strtotime("now");
    $addsalt = substr(md5($ip.uniqid($with_time,true)),0,15);
    $_SESSION['order_id'] = $addsalt;
}

 $order_id = $_SESSION['order_id'];

My cart.php (Session Logic Only)
 $user_sessid = $_SESSION['sessid'];
 $order_id = $_SESSION['order_id'];

 $userid = $_SESSION['user_id'];

 if(empty($userid)){

 $r_type = 1;

 $q1=<<<SQL
select od.ipaddress, od.modified_ts, od.product_id,od.discount,od.quantity,p.id,p.name,p.price, p.img_dir,p.img_name from orders od, products p where od.order_id='$order_id' and od.user_sessid='$user_sessid' and od.product_id = p.id
 SQL;

} else {
$r_type = 2;

  $q1=<<<SQL
select uc.modified_ts, uc.product_id,uc.discount,uc.quantity,p.id,p.name,p.price, p.img_dir,p.img_name from user_cart uc, products p where uc.userid='$userid' and uc.product_id = p.id
  SQL;

}

 $r1=$db->query($q1);
 $num1 = $r1->num_rows;

When i'm echoing out the query on immediate reload of the cart page it is getting an empty order_id.
I'm wondering my head off as to how this weird thing is happening. Please help...
Update I am including a file on top of both the pages which has session_start on top of it and therefore it explains the user_sessid being created and used.
Comment: Could we possibly see the contents of the file you're including that starts your sessions? Is it the same file executing in the same way for both pages?
Comment: @coder101 We're all asking the same thing because it's good practice to look at *all* of the code involved in an issue. It could be something as simple as a typo - I've had that happen dozens of times. We want to help but can't if we can't see the whole thing.
Comment: `session_start()` is missing on every page. - http://php.net/manual/de/function.session-start.php
Comment: Is this problem in every browser or only in Chrome? If it is related to chrome make sure you include the favicon.
Comment: @Perry i thought of this but it is giving the same thing in firefox as well.
Comment: @Perry favicon?? eh?? how could that create a problem if at all that's the case
Comment: you need to check session variables...
Comment: @coder101 I had once a problem with session to, the thing was it only happend in chrome.Chrome couldn't find the favicon and because of that the response was a 404. see this post for more information http://stackoverflow.com/questions/8247842/session-data-lost-in-chrome-only
Comment: @dartacus In the `add_to_cart.php` a file named `functions.php` is included which has `session_start` and in `cart.php`, a file named `header.php` is included which in turn has `functions.php` included in it. And, i'm wondering why everyone is asking the same thing when i've clearly mentioned that only one variable is beings flushed, others i can use very normally.
Comment: @coder101 can you add this to your code: `echo session_id(); print_r($_SESSION)`
Comment: @Perry but it is happening with firefox as well.
Comment: @coder101 I know it was just a explantion why the favicon was the problem in chrome.
Comment: @Perry I added the code that you gave and printed out the session array, so the immediate access of the cart page after adding a product gives order_id in the session array but then when i refresh the page it is removed from the array but other session variables are well within the array
Comment: @coder101 that is strange, it looks like your are resetting the order_id some how. Do you have some were in your code unset or something like that?
Comment: I'm only unsetting the order_id on the logout page but not when the user is not logged in. And as i said, the only flow is adding to cart and after that viewing the cart page which destroys the orderid on reload.
Answer: You may need to add session_start() to the top of the file.
Edit:
You said you were querying on the session id and order id, but you also have
and od.product_id = p.id

at the end of your query. Where is this logic? I'm guessing that you are using a $_GET request or something similar to determine the product ID. Maybe this has something to do with your issue, possibly just remove it from the query? You should only need to use 1 unique key for your SQL query, especially as unique as the hash you're creating.
Comment: Well, no offence but i do know that and i'm including the functions file on both the pages which has `session_start` on top of it and which explains the session_id not emptying.
Comment: @coder101 I wasn't thinking that you didn't know, I just didn't see it as part of the code.
Comment: `and od.product_id = p.id` is being used to group the products in the results fetched and i'm simply joining the two tables with the product_id hence this part. but how do you explain that only one session variable is getting destroyed and not all of them
Answer: An obvious point, but check you're definitely calling session_start() on both pages?


Is It Possible to get a (rough) Mobile Phone Location from a HTTP Request

Question: If memory serves me correctly, google does this for the maps site. I know google's mobile maps app can determine the rough location (I assume using some kind of cell tower lookup), yet I seem to remember the site getting somewhat close to the current location when viewing on a mobile browser.
Anyone know how/if that's possible? Does the IP address change based on the tower or area (seems like they'd be using some kind of gateway common to the carrier)?
Answer:
This is Not possible.

1.) Location By querying Network Details.
Even if you get the approximate location from an installed app by querying network or cell-id details, it'd not be that reliable. You won't be able to perform anything based on that approximate location.
2.) Location By querying IP.
Secondly, in one country, a single telco will have it geo-stationed GPRS or EDGE gateways and all devices on network are connected to internet with that gateway. So basically you can't rely on location details by IP, because that would be the IP of the Gateway and not the IP of device(in case of EDGE).

Ultimately, if you need to do anything that is based on the location, the
  location itself needs be precise and not approximate.
Comment: Just to respond to the line in bold: there are uses of location where imprecise or approximate locations are sufficient.  If I want to guess a time zone, show the user nearby weather conditions, choose the country-specific version of my website, or any number of other tasks, I don't need anything like GPS-precision.  How approximate the locating method can be will depend on your use case, but there are a wide variety of use cases.
Comment: It seems to me that google is known for 'triangulating' location from cell towers. When I first saw it done on a BlackBerry (a few years back), it was relatively close - enough for some purposes. What I'm trying to determine is if that's somehow possible simply by analyzing the HTTP request. I'd seem rumors of the Kindle having a rough location viewing google maps (web not app).
Answer: With a regular HTTP request the only option you have is GeoIP but this will only give you the country & operator no better.
Depending on the application & device you are using there are various option for geolocation, for example iPhone & Android browsers suport the HTML5 geo javascript functions so you could put some code in the page to send you the location. However these all involve some client side code.
The other option involves doing a deal with the networks, they can supply you the phone number as an additional header in the request and you can then query this number via an API from the operator to get the location of the phone from the network. However they charge a pretty penny for this function and the accuracy can vary from about 100m in an urban environment to 35Km in very rural areas.
Comment: Can you cite the latter option you mention?
Comment: I would also like a source on this. Where is this header data containing the user's phone number? Is it sent from the browser app? Then the cell carrier doesn't control it. Does the carrier inject header info into http data sent over their network?
Answer: We were using Google Gears for some time and that worked on Windows Mobile version 5.0 plus devices. Google recently stopped that service. Yahoo have now started something called Yahoo Fire Eagle. Sounds good, haven't yet checked it out. I dont have a Yahoo account, yet.
Answer: You have Google API Documentation on this:
http://code.google.com/apis/gears/geolocation_network_protocol.html
Hope it helps...
Answer: A little late in the day, but another option not mentioned is the MaxMind geo IP lookup. Enter an IP address and it will provide you with a location. There is free service (with simple API) that provides city level accuracy. There is also a more accurate database available for a fee. I have noticed during testing that there are multiple towers / IP addresses in urban areas and the MaxMind database is aware of these.  You'll get location, plus the telco provider.
http://www.maxmind.com/


I can't launch recently installed games on Windows Vista?

Question: I recently installed Anno 1503, Mafia, and Praetorians on my PC. After installing each one, not one of them will work leading me to believe these are not individual issues relating to each but one.
I have Steam installed but haven't used it for any of the aforementioned games.
Upon installing each one, I went into the properties of each and set them to run as admin but to no avail. When I try to launch, I'm asked to allow the program to run but nothing else happens... no error msg, nothing.
I have also

Restarted my PC
Tested other games. Fallout 3 and Morrowind still run. Rome Total War, which used to run fine, no longer works either
Uninstalled/Reinstalled Notepad++ as a test, and that launches fine still

Any ideas? Feel free to ask for any further info.
My PC specs:

Vista Home Premium (SP2) 64-bit
Intel Core2 Quad CPU Q8200 @ 2.33GHz
8GB Ram
NVIDIA GeForce 9600 GT
DirectX 11
Comment: I'm voting to close this question as off-topic because OP is asking why their games are not working on an operating system that is not listed under the supported system for said titles. If you wish to know why these restrictions occur, perhaps super user would be a better option.
Comment: Not a single one of the games you listed actually advertise Windows Vista compatibility on systemrequirementslab.com. as such, I am voting to close this question
Comment: @Timelord64 only one game is even added to that site? Also they do work on vista, see: https://en.wikipedia.org/wiki/Praetorians_(video_game)#Gameplay, http://forums.2k.com/showthread.php?24145-Mafia-On-Vista, (couldn't find anything for anno 1503)
Comment: @Aequitas, I checked each one myself. I take systemrequirementslab over a wiki, though.
Comment: @Timelord64 can you link me to the sys req lab site for praetorians and anno 1503, I couldn't find it. Also just because it's not listed doesn't mean it won't work
Comment: have you restarted since?
Comment: Yes, several times.
Comment: Also, Rome Total War (which I have had installed for a few years) no longer runs. I haven't played it recently but recall it working fine in the past.
Comment: Do games you installed before these still run? Are you using something like Steam or GoG to run/install these games? Does any new program not run, for instance if you install notepad++ or something simple will that run?
Comment: Will still note that you might be able to upgrade to 7 and run in XP compatibility mode.
Comment: Fallout 3 and Morrowind still run. I have Steam installed but haven't used it for any of the aforementioned games. Uninstalled and reinstalled notepad++ and that launches fine still.
Comment: @user130843 32 or 64 bit?
Comment: @user130843, it doesnt really work that way. Fallout 3 and Morrowind may work, where others would not. Atleast Fallout 3 is significantly newer, there, too.
Comment: @Aequitas 64-bit
Comment: @Timelord64 As I said, I have had Rome Total War running on this system before and now that has stopped so compatibility shouldn't be an issue
Comment: My bad. It was gamesystemrequirements.com ( [Anno](http://gamesystemrequirements.com/game/anno-1503) , [Praetorians](http://gamesystemrequirements.com/game/praetorians) ). I'm not saying it won't work, I'm saying that questions about why a game will not work for a OS it is not listed for is off-topic.
Comment: Also, Total War lists Vista as compatible. Maybe ask about Total War and start from there. But we would also need your system specifications including the direct x your running, and confirmation of actually installing the direct X versions listed under each game. (note: Direct X **is designed to be universal**; You should not need 9 if you have 10. I have had to use Direct X for development, and believe me, there are exceptions to this rule)
Comment: Vista Home Premium (SP2)
Intel Core2 Quad CPU Q8200 @ 2.33GHz
8Gb Ram
NVIDIA GeForce 9600 GT
DirectX 11
Comment: @user130843 Launch the game, then launch Event Viewer. Under *Windows Logs* -> *Application*, see if there is any issues reported there.
Comment: If you have an antivirus program, did you try disabling it before running the games?
Comment: No issues when I attempt to launch @Robotnik.
Comment: Yeah, tried disabling AV progs @Alexander Revo
Comment: @user130843 - ok, try opening Task Manager, and on the Processes tab - is the game process still running?
Comment: @Robotnik Nope. Process starts but immediately ends
Comment: @user130843 really? and there's nothing at all in Event Viewer? Not in any of the other tabs either? no events (including Info/Warning) with the same timestamp?
Comment: @Robotnik No, plenty of events in the event viewer but none with timestamps correlating to me attempting to launch the games it seems.
Answer: The solution to your question is quite simple. Upgrade to Windows 7, and get rid of Windows Vista.
Comment: Why does this fix it?  Why is Vista the problem?
Comment: @Frank vista is always the problem
Comment: I have vista and it works well for me


How can I get more Cubits without buying them?

Question: I was playing Chess Cube on Facebook and suddenly this popped up and I am not able to play any matches.

Why is this happening? Is there way to continue playing? (Other than buying the cubits of course.)
Comment: RIP chesscube!!
Answer: From What are ChessCube Cubits?

What is it?
Cubits are ChessCube's virtual currency, which can be used to enter a ChessCube Tournament, play a wagered Chess match against other ChessCube users, or purchase items in the ChessCube store
How do I get Cubits?

Directly purchasing Cubits using your Credit Card or Paypal account
Using your mobile phone to purchase Cubits through Zong
Taking up and[sic] offer through Offerpal
Playing in ChessCube Tournaments and finishing in a Cubit prize position
Winning Cubits against another user in a Cubit Wager game
Logging in daily
Playing in your first ChessCube Tournament
Inviting your friends to ChessCube via email

Emphasis mine — free options are italicized, the options I think are open to you are additionally bolded.
Answer: Chesscube is not free --
You can play a few games for free every day, but after that you need to buy "Cubits".
Answer: Don't play too many games if you don't have cubits or you don't want to buy them. Just play one a day for your daily bonus. You generate 100 cubits a day so 100*10 days nets you 1000 cubits.
Only play lots of games that you bet on if you know you are good.
Answer: Make two accounts. Open both of them in different browsers. transfer cubits from one account to another by playing a match between them and then losing. you will easily get 200 cubits after 3-4 matches. repeat this process for different accounts.


jquery after 1minute send $POST to server

Question: I know how to do a setTimeout(function(){}),xseconds}
But what I don't know is how do I make the xseconds a minute.
Basiclly what I want to do is make sure the users session gets updated on our server and the only way I know to do that is via PHP as it needs to be saved to the MYSQL, so I was going to $ajax POST send a request to the server to update the session end time in the session table.
So quick simple question is what is 1minute in jquery seconds.
Comment: Just FYI, `setTimeout()` is not a jQuery function, it is a native function of Javascript.
Answer: it's a milisecond not second.
so it you want to have 1 minute means 1x60x1000 = 60000ms
setTimeout(function(){}), 60000}
Answer: setTimeout is used as follows.
var t=setTimeout(function(){},milliseconds);
1000 milliseconds = 1 second. So 60 seconds in milliseconds...
60 * 1000 = 60000
Comment: Please change `"javascript statement"` to `function(){javascript statement;}` before I downvote you lol


Paid an Electrician to install Sub-panel.. & Ground wire question

Question: A couple of years ago, I was needing a sub-panel in my garage.  While I intended to do it  myself, shoulder surgery precluded me from being able so I hired a local, licensed electrician.  He did a great job of running PVC conduit up to and across my 2nd-story attic, down along with breezeway to the garage.  Just a couple of days ago I looked at the sub panel and noticed the cover plate screws were barely screwed in.  So, I took them off to take a peak inside.   This is what I saw.
This is a garage sub-panel, connected to a main where neutrals and ground wires are connected to each other, see pic.
seems like he was in a rush...
Looking at the main, if  you look closelt on the left you can see that he put the new ground for this sub in the neutral bar.  Not wrong, but the only wire now like that....
So I added a ground bar in the sub, and removed the green ground screw/bar from the neutral bar.  Due to the layout, I used a wire nut to connect the grounds from the two cables on the right to 1 ground bar screw terminal on the left.  Is that legit (using wire nut to connect 2 grounds into 1)?
thx
Comment: A couple of years ago? When exactly was the work done? Where are you located? Your location will matter if your state is one of the few that doesn't adopt the NEC and or if they are on a much older version with allowances for existing structures. With these questions answered we can answer your question ( a major portion of the US has required the neutral and ground to be isolated since ~99 but some still do not.
Answer: Yeah, that's fine.  Try not to have ground faults on both circuits at the same time :)
Nice job fixing up that panel.  Weird that the person wired it like that.
The breezeway means it is an attached structure and you are OK with not having a disconnect switch/main breaker.
Comment: thank you for your quick feedback.  Also surprising that a professional would use a half-size 20amp breaker on the left and then 2 full-size breakers on the right bank.  All 3 are feeding outlets in my shop. I know functionally they are the same, but looks sloppy.  And regarding Ed's comment: work was done in 2017, Texas, house was built in 2005, city I'm in uses 2018 NEC. Thanks for reminder on particulars as I am about to post a question about generator power inlet box placement so this is a good reminder to add years/locations in it.  thank you
Comment: @Bobbo1107 Actually, that works; it's a unique characteristic of the GE panels. (a trait it shares with the ancient Crouse-Hinds, and the FPE which had unrelated problems). But GE implemented it much better (those funny cruciforms on the bus stabs are a GE thing, and they mean you don't need left-hand and right-hand breakers). Sadly, it's moot; 2020 Code all but outlaws half width breakers.


GTA 5 online for Xbox One

Question: I have an Xbox One and when I try to use GTA online it says that my account does not have permission to access this feature. Do I need an Xbox LIVE membership/gold membership to use this?
Answer: You must have an Xbox Live Gold membership to play GTA Online.
I can't find any official page to source for this answer, but it's considered common knowledge that multiplayer content in any Xbox game is locked behind a Gold subscription. There are also multiple forums where people ask this same question, and all replies confirm that a Gold subscription is necessary.

GTA 5 online for Xbox One


How to iterate collection in XAML, where the collection is part of the model in c# class

Question: I am building desktop application using WPF and XAML with MVVM pattern.
I have a collection of strings ( error messages) in the model class. Class is binded to the XAML. I need to iterate the collection of strings so that they are displayed in bullet points in the view.
I have tried itemscontrols tag, but no luck with it. It just displays the first element of the list.
I expected that collection will be iterated but only the first element of the collection is displayed. There are no error messages.
Answer: The usual way to render a list of anything in WPF/MVVM is with an ItemsControl:
<ItemsControl ItemsSource="{Binding MyItems}" />

If you don't like the default item representation then you can override the item template:
<ItemsControl ItemsSource="{Binding MyItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., StringFormat={}•{0}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Result:

You can also override the default ItemPanel if you want the items to be laid out different i.e. WrapPanel, horizontal StackPanel etc.


Why does yytext skip the first imput in YACC?

Question: I have been working with a sample problem to construct a three address code for an expression. But to my surprise, YACC seems to skip my first input symbol. I will attach an image with the output to make it clear.
The rules aren't too complicated so I don't seem to understand where the issue is.
Here is my lex file:
%{
#include"y.tab.h"
%}
%%
[a-zA-Z]+ return ID;
[0-9]+ return NUM;
. return yytext[0];
%%
int yywrap(){return 1;}

Here is my yacc file:
%{
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char st[50][50];
extern char * yytext;
int top=-1;char t[5]="0";char temp[5];
void push();
void code();
%}
%token NUM ID
%left '+' '-'
%left '*' '/'
%%
S:' 'E
|' 'A'='E
;
A:ID{push();printf("yytext is %s\n",yytext);}
;
E:E'+'{push();}T{code();}
|E'-'{push();}T{code();}
|T
;
T:T'*'{push();}F{code();}
|T'/'{push();}F{code();}
|F
;
F:ID{push();}
|NUM{push();}
;
%%
void push(){strcpy(st[++top],yytext);}

void code(){
strcpy(temp,"t");
strcat(temp,t);
t[0]++;
printf("%s = %s %s %s \n",temp,st[top-2],st[top-1],st[top]);
top=top-2;
strcpy(st[top],temp);

}

int main(){yyparse();}
int yyerror(){exit(0);}

i expect the print in the A:ID production to print the ID entered, but it is printing the '=' instead.
here is my output:
my output
Comment: You need a *flex* rule to ignore white space.
Answer: In order to be sure that A was seen, yacc had to advance (look ahead) to see =. That overwrites your first token in yytext.
Comment: that makes sense. it is true that one learns a lot more hands-on than sitting in a classroom. Any idea as to how i could get my code running?


Modal window action buttons, top or bottom

Question: Scenario: File upload process for a website on desktop(not mobile) launches a modal window.
Question: Would it be better to place action buttons at the top or at the bottom of the window.
Pros & Cons for Top Placement: more content area space however process flow starts from top left,moves down, then back to the top
Pros & Cons for Bottom Placement: Less content area space, better process flow, odd scroll window placement.
Comment: The bottom placement is standard for Dialogs. [See, for example, the Apple OSX HI Guidelines section on Dialogs.](http://developer.apple.com/library/mac/documentation/userexperience/conceptual/applehiguidelines/Windows/Windows.html#//apple_ref/doc/uid/20000961-BACFBACB)
Comment: Also, if you move the Submit Pictures button to the bottom right instead of the bottom left, your flow would be more natural.
Comment: If you're so concerned with content space that you'd consider putting the Submit button in the header bar, why not put the Add button and Album text box in the header bar, and the Submit at the bottom? Now you have the advantages of both designs.
Comment: What tool was used to create those mockups?
Answer: You should have the buttons at the bottom right because:

The standard for modals is to have the buttons at the bottom, so it is likely where people will look for action buttons
It is a more natural visual flow reading in a Z pattern, and one that has become entrenched.
A button on the right is typical for a submit button as it has the feeling of moving forward (in a left to right language).
Comment: +1 For Z-pattern. The setup described is also standard across platforms. The 'save dialog' on both PC and Mac, for example. Title/Header - user interaction area - cancel/save...it is a human computer interaction standard.
Comment: Do you have a reference for these assertions?
Answer: According to this use study, it is better in terms of errors and completion to have button at the bottom left.
Comment: While being a good study, it was not using modals as a reference, but rather applied to web forms.  Due to that, it used a layout where the page width was significantly wider than the content, resulting in a situation where any right aligned button is outside of the visual content.  Additionally, it was done before any major use of smartphones, which have had an effect on use behaviour.