text:
Q: How to make HTTP request in Swift? I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?

A: I have done HTTP Request Both methods GET & POST with JSON Parsing this way:
on viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()

    makeGetRequest()
    makePostRequest()

}

func makePostRequest(){

    let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example-script/"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request.HTTPMethod = "POST"
    var stringPost="firstName=James&lastName=Bond" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request.timeoutInterval = 60
    request.HTTPBody=data
    request.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

         if (jsonResult != nil) {
            // Success
           println(jsonResult)

           let message = jsonResult["Message"] as! NSString

           println(message)
         }else {
            // Failed
            println("Failed")
        }

    })

}

func makeGetRequest(){
    var url : String = "http://api.androidhive.info/contacts/"
    var request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: url)
    request.HTTPMethod = "GET"
    request.timeoutInterval = 60

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

        if (jsonResult != nil) {
            // Success
            println(jsonResult)

            let dataArray = jsonResult["contacts"] as! NSArray;

            for item in dataArray { // loop through data items

                let obj = item as! NSDictionary

                for (key, value) in obj {

                    println("Key: \(key) - Value: \(value)")

                    let phone = obj["phone"] as! NSDictionary;

                    let mobile = phone["mobile"] as! NSString
                    println(mobile)
                    let home = phone["home"] as! NSString
                    println(home)
                    let office = phone["office"] as! NSString
                    println(office)
                }
            }

        } else {
            // Failed
            println("Failed")
        }

    })
}

Done

A: You can use URL, URLRequest and URLSession or NSURLConnection as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred.
Using URLSession
Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume().
let url = URL(string: "http://www.stackoverflow.com")!

let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}

task.resume()

Using NSURLConnection
First, initialize a URL and a URLRequest:
let url = URL(string: "http://www.stackoverflow.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

Then, you can load the request asynchronously with:
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
    guard let data = data else { return }
    print(String(data: data, encoding: .utf8)!)
}

Or you can initialize an NSURLConnection:
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)

Just make sure to set your delegate to something other than nil and use the delegate methods to work with the response and data received.
For more detail, check the documentation for the NSURLConnectionDataDelegate protocol
Testing on an Xcode playground
If you want to try this code on a Xcode playground, add import PlaygroundSupport to your playground, as well as the following call:
PlaygroundPage.current.needsIndefiniteExecution = true

This will allow you to use asynchronous code in playgrounds.

A: Swift 4 and above : Data Request using URLSession API
   // create the url
   let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url

   // create the session object
   let session = URLSession.shared

   // now create the URLRequest object using the url object
   let request = URLRequest(url: url)

   // create dataTask using the session object to send data to the server
   let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

       guard error == nil else {
           return
       }

       guard let data = data else {
           return
       }

      do {
         //create json object from data
         if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
         }
      } catch let error {
        print(error.localizedDescription)
      }
   })

   task.resume()

Swift 4 and above, Decodable and Result enum
// APIError enum which shows all possible Network errors
enum APIError: Error {
    case networkError(Error)
    case dataNotFound
    case jsonParsingError(Error)
    case invalidStatusCode(Int)
    case badURL(String)
}

// Result enum to show success or failure
enum Result<T> {
    case success(T)
    case failure(AppError)
}

// dataRequest which sends request to given URL and convert to Decodable Object
func dataRequest<T: Decodable>(with url: String, objectType: T.Type, completion: @escaping (Result<T>) -> Void) {

    // create the url with NSURL
    guard let dataURL = URL(string: url) else {
       completion(.failure(APIError.badURL(url))
       return
    }

    // create the session object
    let session = URLSession.shared

    // now create the URLRequest object using the url object
    let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)

    // create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(Result.failure(APIError.networkError(error!)))
            return
        }

        guard let data = data else {
            completion(Result.failure(AppError.dataNotFound))
            return
        }

        do {
            // create decodable object from data
            let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
            completion(Result.success(decodedObject))
        } catch let error {
            completion(Result.failure(APIError.jsonParsingError(error as! DecodingError)))
        }
    })

    task.resume()
}

example:
//if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.
struct ToDo: Decodable {
    let id: Int
    let userId: Int
    let title: String
    let completed: Bool

}

dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in
    switch result {
    case .success(let object):
        print(object)
    case .failure(let error):
        print(error)
    }
}

// this prints the result:
ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false)

A:
I am calling the json on login button click

@IBAction func loginClicked(sender : AnyObject) {

    var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.

    var session = NSURLSession.sharedSession()

    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        var err1: NSError?
        var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary

        println("json2 :\(json2)")

        if(err) {
            println(err!.localizedDescription)
        }
        else {
            var success = json2["success"] as? Int
            println("Success: \(success)")
        }
    })

    task.resume()
}

Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
    return params
}

// You can add your own sets of parameter here.

A: You can use Just, a python-requests style HTTP library.
Some example of sending HTTP request with Just:
// synchronous GET request with URL query a=1
let r = Just.get("https://httpbin.org/get", params:["a":1])

// asynchronous POST request with form value and file uploads
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

In both cases, the result of a request r can be accessed in ways similar to python-request:
r.ok            // is the response successful?
r.statusCode    // status code of response
r.content       // response body as NSData?
r.text          // response body as text?
r.json          // response body parsed by NSJSONSerielization

You can find more examples in this playground
Using this library in synchronous mode in a playground is the closest thing to cURL one can get in Swift.

A: KISS answer:
URLSession.shared.dataTask(with: URL(string: "https://google.com")!) {(data, response, error) in
    print(String(data: data!, encoding: .utf8))
}.resume()

A: Basic Swift 3+ Solution
guard let url = URL(string: "http://www.stackoverflow.com") else { return }

let task = URLSession.shared.dataTask(with: url) { data, response, error in

  guard let data = data, error == nil else { return }

  print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}

task.resume()

A: In Swift 4.1 and Xcode 9.4.1.
JSON POST approach example. To check internet connection add Reachability.h & .m files from https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2
func yourFunctionName {
    //Check internet connection
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    print(networkStatus)
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg//Message
        //Call alert from shared class
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)
    } else {
        //Call spinner from shared class
        SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner

        let parameters = "Your parameters here"
        var request = URLRequest(url: URL(string: url)!)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        print("URL : \(request)")

        request.httpBody = parameters.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            //Stop spinner
            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner
            //Print error in alert
            SharedClass.sharedInstance.alert(view: self, title: "", message: "\(String(describing: error!.localizedDescription))")
            return
            }

            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
                print(response!)
                //Your code here
            } catch let error as NSError {
                print(error)
            }
        }

        task.resume()

    }

}

If you have interest to use this function in SharedClass
//My shared class
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

func postRequestFunction(apiName: String , parameters: String, onCompletion: @escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {

    var URL =  "your URL here/index.php/***?"

    URL = URL.replacingOccurrences(of: "***", with: apiName)

    var request = URLRequest(url: URL(string: URL)!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    print("shared URL : \(request)")
    request.httpBody = parameters.data(using: .utf8)

    var returnRes:[String:Any] = [:]
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        if let error = error {
            onCompletion(false, error, nil)
        } else {
            guard let data = data else {
                onCompletion(false, error, nil)
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
                do {
                   returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
                    onCompletion(true, nil, returnRes)

                } catch let error as NSError {
                   onCompletion(false, error, nil)
                }
            } else {
                onCompletion(false, error, nil)
            }
        }
    }
    task.resume()
}

private override init() {

}

And finally call this function like this....
SharedClass.sharedInstance.postRequestFunction(apiName: "Your API name", parameters: parameters) { (success, error, result) in
    print(result!)
    if success {
        //Your code here
    } else {
        print(error?.localizedDescription ?? "")
    }
}

A: Here are start to finish instructions to make an HTTP request with Swift on Linux.
First create a SwiftPM package
mkdir swift-http && cd swift-http && swift package init --type executable

Then replace the contents of ./Sources/swift-http/main.swift
with the code below:
import Foundation
import FoundationNetworking

let sema = DispatchSemaphore(value: 0)

URLSession.shared.dataTask(with: URL(string: "http://numbersapi.com/42")!) {(data, response, error) in
    print(String(data: data!, encoding: .utf8) ?? String(describing: error))
    sema.signal()
}.resume()

sema.wait()

Then run the code
swift run

Output example:
[6/6] Build complete!
42 is the answer to the Ultimate Question of Life, the Universe, and Everything.

Note: the DispatchSemaphore is used so that our program doesn't exit before getting a response.
You could have also done something like this:
import Foundation
import FoundationNetworking

var done = false

URLSession.shared.dataTask(with: URL(string: "http://numbersapi.com/42")!) {(data, response, error) in
    print(String(data: data!, encoding: .utf8) ?? String(describing: error))
    done = true
}.resume()

while !done { Thread.sleep(forTimeInterval: 1) }

A: Using URLSession + Swift 5
Just adding to cezar's answer, if you want to make web request using Apple's URLSession class, there are multiple way to do the task

*

*Simple GET Request with URL

*Simple GET Request with URL and Parameters

*Simple GET Request with URL with Error Handlings

*Simple POST Request with URL, Parameters with Error Handlings

1. Simple GET Request with URL
func simpleGetUrlRequest()
    {
        let url = URL(string: "https://httpbin.org/get")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print("The response is : ",String(data: data, encoding: .utf8)!)
            //print(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as Any)
        }
        task.resume()
    }

Note : Make sure You must add "NSAppTransportSecurity" key in pList for http requests

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

2. Simple GET Request with URL and Parameters
func simpleGetUrlWithParamRequest()
    {
        let url = URL(string: "https://www.google.com/search?q=peace")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

            if error != nil || data == nil {
                print("Client error!")
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }
            print("The Response is : ",response)
        }
        task.resume()
    }

3. Simple GET Request with URL with Error Handlings
func simpleGetUrlRequestWithErrorHandling()
    {
        let session = URLSession.shared
        let url = URL(string: "https://httpbin.org/get")!

        let task = session.dataTask(with: url) { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("Wrong MIME type!")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        }
        task.resume()
    }

4. Simple POST Request with URL, Parameters with Error Handlings.
func simplePostRequestWithParamsAndErrorHandling(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30
        configuration.timeoutIntervalForResource = 30
        let session = URLSession(configuration: configuration)

        let url = URL(string: "https://httpbin.org/post")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let parameters = ["username": "foo", "password": "123456"]

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }

        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Oops!! there is server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("response is not json")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        })

        task.resume()
    }

Your suggestions are appreciated!!

A: Swift 3.0
Through a small abstraction
https://github.com/daltoniam/swiftHTTP
Example
    do {
        let opt = try HTTP.GET("https://google.com")
        opt.start { response in
            if let err = response.error {
                print("error: \(err.localizedDescription)")
                return //also notify app of failure as needed
            }
            print("opt finished: \(response.description)")
            //print("data is: \(response.data)") access the response of the data with response.data
        }
    } catch let error {
        print("got an error creating the request: \(error)")
    }

A: Details

*

*Xcode Version 14.2 (14C18), Swift 5.7

Info.plist
NSAppTransportSecurity
Add to the info plist:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

URLSession Sample

NetworkManagerable interface

// MARK: NetworkManagerable

protocol NetworkManagerable: AnyObject {
    func process<Value>(request: URLRequest,
                        session: URLSession,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void)
}

extension NetworkManagerable {
    func process<Value>(request: URLRequest,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) {
        process(request: request, session: .shared, completion: completion)
    }

    func get<Value>(url: URL,
                    session: URLSession = .shared,
                    completion: @escaping (Result<Value, NetworkManagerError>) -> Void) {
        process(request: URLRequest(url: url), session: session, completion: completion)
    }
}

// MARK: NetworkManager Errors

enum NetworkManagerError: Error {
    case dataTask(error: Error)
    case emptyData
    case jsonSerialization(error: Error)
    case castingError(value: Any, isNot: Any)
    case networkMangerIsNotExists
}

NetworkManager

// MARK: NetworkManager

class NetworkManager {

    private func process<Value>(data: Data?, response: URLResponse?, error: Error?) -> Result<Value, NetworkManagerError> {
        if let error = error { return .failure(.dataTask(error: error)) }
        guard let data = data else { return .failure(.emptyData) }

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            guard let dictionary = json as? Value else {
                return .failure(.castingError(value: json, isNot: Value.self))
            }
            return .success(dictionary)

        } catch let error {
            return .failure(.jsonSerialization(error: error))
        }
    }
}

// MARK: NetworkManagerable

extension NetworkManager: NetworkManagerable {
    func process<Value>(request: URLRequest,
                        session: URLSession = .shared,
                        completion: @escaping (Result<Value, NetworkManagerError>) -> Void) {
        let task = session.dataTask(with: request) { [weak self] data, response, error in
            guard let self = self else {
                completion(.failure(.networkMangerIsNotExists))
                return
            }
            completion(self.process(data: data, response: response, error: error))
        }
        task.resume()
    }
}

Usage example
var networkManager: NetworkManagerable = NetworkManager()
let searchString = "matrix".replacingOccurrences(of: " ", with: "+")
let urlString = "https://itunes.apple.com/search?term=\(searchString)"
if let url = URL(string: urlString) {
    networkManager.get(url: url) { (result: Result<[String: Any], NetworkManagerError>) in
        print(result)
    }
}

Results

A: Check Below Codes :
1. SynchonousRequest
Swift 1.2
    let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
    println("Synchronous\(jsonResult)")

Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil

    do{

        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)

            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }

    }catch let error as NSError
    {
         print(error.localizedDescription)
    }

2.  AsynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("Asynchronous\(jsonResult)")
       })

Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    })

3. As usual URL connection
Swift 1.2
    var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then
 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.dataVal?.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!)
{
    var error: NSErrorPointer=nil

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

    println(jsonResult)

}

Swift 2.0 +
   var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    dataVal.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!)
{

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

4.  Asynchonous POST Request
Swift 1.2
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
     var stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")

        })

Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    let stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    })

5.  Asynchonous GET Request
Swift 1.2
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    request1.timeoutInterval = 60
    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")

        })

Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    })

6. Image(File) Upload
Swift 2.0 +
  let mainURL = "YOUR_URL_HERE"

    let url = NSURL(string: mainURL)
    let request = NSMutableURLRequest(URL: url!)
    let boundary = "78876565564454554547676"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    request.HTTPMethod = "POST" // POST OR PUT What you want
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)

    var body = NSMutableData()

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your parameters

    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your Image/File Data

    var imageNameval = "HELLO.jpg"

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body

    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error

        }
        else {

            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print("Response:\(outputString)")

        }
    }
    dataTask.resume()

A: Another option is the Alamofire lib that offers Chainable Request / Response methods.
https://github.com/Alamofire/Alamofire
Making a Request
import Alamofire

Alamofire.request(.GET, "http://httpbin.org/get")

Response Handling
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { request, response, data, error in
              print(request)
              print(response)
              print(error)
          }

A: A simple Swift 2.0 approach to making a HTTP GET request
The HTTP request is asynchronous so you need a way to get the returned value from the HTTP Request. This approach uses Notifiers and is spread over two classes.
The example is to check the username and password for an identifier token using the website http://www.example.com/handler.php?do=CheckUserJson&json= That is the file is called handler.php and has a switch statement on the do parameter to get a RESTful approach.
In the viewDidLoad we setup the NotifierObserver, set up the json and make the call to the getHTTPRequest function. It will return to the function checkedUsernameAndPassword with the returned parameter from the http request.
override func viewDidLoad() {
    super.viewDidLoad()
    // setup the Notification observer to catch the result of check username and password
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "checkedUsernameAndPassword:", name: CHECK_USERNAME_AND_PASSWORD, object: nil)
    let username = GlobalVariables.USER_NAME
    let password = GlobalVariables.PASSWORD
    // check username and password
    if let jsonString = Utility.checkUsernameAndPasswordJson(username, password:password){
        print("json string returned = \(jsonString)")
        let url = CHECKUSERJSON+jsonString
        // CHECKUSERJSON = http://www.example.com/handler.php?do=CheckUserJson&json=
        // jsonString = {\"username\":\"demo\",\"password\":\"demo\"}"
        // the php script handles a json request and returns a string identifier
        Utility.getHTTPRequest(url,notifierId: CHECK_USERNAME_AND_PASSWORD)
        // the returned identifier is sent to the checkedUsernaeAndPassword function when it becomes availabel.
    }
}

There are two static functions in Utility.swift first to encode the json and then to do the HTTP call.
    static func checkUsernameAndPasswordJson(username: String, password: String) -> String?{
    let para:NSMutableDictionary = NSMutableDictionary()
        para.setValue("demo", forKey: "username")
        para.setValue("demo", forKey: "password")
    let jsonData: NSData
    do{
        jsonData = try NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
        return jsonString
    } catch _ {
        print ("UH OOO")
        return nil
    }
}

and the Http request
    static func getHTTPRequest (url:String , notifierId: String) -> Void{
    let urlString = url
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
    let safeURL = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    if let url = NSURL(string: safeURL){
        let request  = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.timeoutInterval = 60
        let taskData = session.dataTaskWithRequest(request, completionHandler: {
            (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            if (data != nil) {
                let result = NSString(data: data! , encoding: NSUTF8StringEncoding)
                sendNotification (notifierId, message: String(result), num: 0)
            }else{
                  sendNotification (notifierId, message: String(UTF8String: nil), num: -1)                    }
        })
    taskData.resume()
    }else{
        print("bad urlString = \(urlString)")
    }
}

The sendNotification function completes the circle. Notice that in teh Observer there is a ":" at the end of the selector string. This allows the notification to carry a payload in userInfo. I give this  a String and an Int.
    static func sendNotification (key: String, message:String?, num: Int?){
    NSNotificationCenter.defaultCenter().postNotificationName(
        key,
        object: nil,
        userInfo:   (["message": message!,
                      "num": "\(num!)"])
    )
}

Note that using HTTP is oldFashioned, prefer HTTPS see How do I load an HTTP URL with App Transport Security enabled in iOS 9?

A: Update :- Xcode 13.0 & Swift 5+
GET HTTP REQUEST
let url = URL(string: "URL HERE")! //PUT Your URL
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let safeData = data,
                  let response = response as? HTTPURLResponse,
                  error == nil else {                                              // check for fundamental networking error
                      print("error", error ?? "Unknown error")
                      delegate?.onError(error!)
                      return
                  }

            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }

            let responseString = String(data: safeData, encoding: .utf8)
            print("Response String = \(responseString)")
        }

        task.resume()

A:  var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"

    NSLog("PostData: %@",post);

    var url1:NSURL = NSURL(string: url)!

    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

            let success:NSInteger = jsonData.valueForKey("error") as NSInteger

            //[jsonData[@"success"] integerValue];

            NSLog("Success: %ld", success);

            if(success == 0)
            {
                NSLog("Login SUCCESS");

                self.dataArr = jsonData.valueForKey("data") as NSMutableArray
                self.table.reloadData()

            } else {

                NSLog("Login failed1");
                ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
            }

        } else {

            NSLog("Login failed2");
            ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")

        }
    } else {

        NSLog("Login failed3");
        ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}

it will help you surely

A: //Here is an example that worked for me
//Swift function that post a request to a server with key values
func insertRecords()
{

    let usrID = txtID.text
    let checkin = lblInOut.text
    let comment = txtComment.text

    // The address of the web service
    let urlString = "http://your_url/checkInOut_post.php"

    // These are the keys that your are sending as part of the post request
    let keyValues = "id=\(usrID)&inout=\(checkin)&comment=\(comment)"

    // 1 - Create the session by getting the configuration and then
    //     creating the session

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)

    // 2 - Create the URL Object

    if let url = NSURL(string: urlString){

        // 3 - Create the Request Object

        var request  = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"

        // set the key values
        request.HTTPBody = keyValues.dataUsingEncoding(NSUTF8StringEncoding);

        // 4 - execute the request

        let taskData = session.dataTaskWithRequest(request, completionHandler: {

            (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in

            println("\(data)")

            // 5 - Do something with the Data back

            if (data != nil) {

                // we got some data back
                println("\(data)")

                let result = NSString(data: data , encoding: NSUTF8StringEncoding)
                println("\(result)")

                if result == "OK" {

                    let a = UIAlertView(title: "OK", message: "Attendece has been recorded", delegate: nil, cancelButtonTitle: "OK")

                    println("\(result)")

                    dispatch_async(dispatch_get_main_queue()) {

                    a.show()

                    }

                } else {
                  // display error and do something else

                }

            } else

            {   // we got an error
                println("Error getting stores :\(error.localizedDescription)")

            }

        })

        taskData.resume()

    }

}

PHP Code to get the key values
$empID = $_POST['id'];
$inOut = $_POST['inout'];
$comment = $_POST['comment'];

A: Here's a very simple Swift 4 example in a playground:
import UIKit
// run asynchronously in a playground
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

// create a url
let url = URL(string: "http://www.stackoverflow.com")

// create a data task
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil {
        print("there's a problem")
    }
    print(String(data: data!, encoding: String.Encoding.utf8) ?? "")
}

//running the task w/ resume
task.resume()

A: For XCUITest to stop the test finishing before the async request completes use this (maybe reduce the 100 timeout):
func test_api() {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts/42")!
    let exp = expectation(description: "Waiting for data")
    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
        exp.fulfill()
    }
    task.resume()
    XCTWaiter.wait(for: [exp], timeout: 100)
}

A: An example for a sample "GET" request is given below.
let urlString = "YOUR_GET_URL"
let yourURL = URL(string: urlstring)
let dataTask = URLSession.shared.dataTask(with: yourURL) { (data, response, error) in
do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
    print("json --- \(json)")
    }catch let err {
    print("err---\(err.localizedDescription)")
    }
   }
dataTask.resume()


text:
Q: Depurar eventos associados via jQuery Quando desejo depurar um evento associado a um elemento via jQuery, atualmente, consigo fazer das seguintes formas:

*

*no Chrome, é possível ativar o depurador especificamente para certos tipos de eventos. No entanto, isso não tem utilidade quando se é necessário depurar alguma coisa em outros navegadores;

*colocar uma instrução debugger na primeira linha de código de um evento ativa o depurador naquele ponto, mas é inconveniente fazê-lo para cada evento. Além disso, para casos nos quais vou depurar código alheio, ainda há o trabalho de se obter todos os eventos - que podem ser associados e desassociados (amarrados/desamarrados?) dinamicamente.

*Força bruta. Por exemplo, para um evento de clique:
function debugClick (elem) {
    debugger;
    $(elem).click();
}

Esse último exemplo faz com que eu me sinta mal comigo mesmo.
Existe alguma forma mais elegante e cross browser de se depurar os eventos de um elemento?

A: Você pode debuggar ou pausar eventos de clique com a aba Event Listeners do ChromeDev Tools:

Clique aqui para ver a imagem em tamanho maior

A: As ferramentas de desenvolvimento do Chrome são uma excelente ajuda para encontrar os event handlers .
Infelizmente, quando se trata de jQuery, o event handler que é exibido é o do jQuery e não aquele que registamos (o jQuery adiciona alguma funcionalidade e é por isso que vemos o handler do jquery em vez do nosso).
Podemos aceder ao nosso handler da seguinte forma:
$._data($("#idDoElemento").get(0), "events")

Como alternativa existe um pequeno script (disclaimer: sou o dono desse projecto) que permite usar um selector jQuery para encontrar os eventos em que estamos interessados, por examplo, escrevendo na consola do chrome depois de importar findHandlersJS
findEventHandlers("click", "*")

Retorna todos os event handlers para clicks em qualquer tipo de elemento na pagina que estamos.
Outro exemplo:
findEventHandlers("click", "div#items :button")

retorna todos os event handlers para clique nos botões dentro do div com id="items"
Mais informação sobre findHandlersJS aqui(esta em inglês).
E aqui podem encontrar um site exemplo com o findHandlersJS instalado e pronto para usar na consola do chrome.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable stdin echo in a dart console application for password input The example below will read in a user's password but also echo it in plain text, is there a way around this?
Future<String> promptPassword() {
  var completer = new Completer<String>();
  var stream = new StringInputStream(stdin);
  stdout.writeString("Warning: Password will be displayed here until I find a better way to do this.\n");
  stdout.writeString("Watch your back...\n");
  stdout.writeString("GitHub password for $gituser: ");
  stream.onLine = () {
    var str = stream.readLine();
    stdin.close();
    completer.complete(str);
  };
  return completer.future;
}

A: This has been implemented now.
See Stdin.echoMode
import 'dart:io';

void main() {
  print('Enter password: ');
  stdin.echoMode = false;
  var password = stdin.readLineSync();
  // Do something with password...
}

A: This is not possible until tty control is added to dart:io. In the meantime, I recommend:
stty -echo
dart ./password.dart
stty echo

I have opened a bug here: https://code.google.com/p/dart/issues/detail?id=8190

A: The dart DCli package provide an option to do this.
https://pub.dev/packages/dcli
import 'package:dcli/dcli.dart';

void main() {
  var password = ask('password', hidden: true);
}


text:
Q: Error entity framework .net 6.0 C# estoy implementando entity framework en un proyecto .net 6.0 de escritorio. Al ejecutar la verificacion de migraciones me arroja el siguiente error:

Cannot use table 'comprobantes' for entity type
'Usuarios_Cuenta_Corriente' since it is being used for entity type
'Comprobantes' and potentially other entity types, but there is no
linking relationship. Add a foreign key to 'Usuarios_Cuenta_Corriente'
on the primary key properties and pointing to the primary key on
another entity type mapped to 'comprobantes'.

Alguno tiene idea por que es esto?
A continuacion dejo mi codigo:
Mi contexto:
    using EntityFramework.Configuracion;

namespace EntityFramework.Data;

public class DataBaseContext : DbContext
{

    public DbSet<Usuarios_Cuenta_Corriente>? Usuarios_Cuenta_Corriente { get; set; }
    public DbSet<Comprobantes>? Comprobantes { get; set; }
    public DbSet<Comprobantes_Tipo>? Comprobantes_Tipo { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        string ConnectionString = @"server=localhost;database=db_storesys_test;user=root;port=3306;password=15648836";
       optionsBuilder.UseMySql
            (ConnectionString,
            ServerVersion.AutoDetect(ConnectionString));
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        try
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfiguration(new ComprobanteTipoConfiguracion());
            modelBuilder.ApplyConfiguration(new ComprobanteConfiguracion());
            modelBuilder.ApplyConfiguration(new UsuarioCuentaCorrienteConfiguracion());
        }
        catch(Exception ex)
        {
            string Mensaje = ex.Message;
            throw ex;
        }
    }

}

Mis configuracion (Usuario cuenta corriente)
    using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EntityFramework.Configuracion;
public class UsuarioCuentaCorrienteConfiguracion : IEntityTypeConfiguration<Usuarios_Cuenta_Corriente>
{
    public void Configure(EntityTypeBuilder<Usuarios_Cuenta_Corriente> modelBuilder)
    {
        modelBuilder.ToTable("comprobantes");
        modelBuilder.HasKey(e => e.clienteCuentaCorrienteId).HasName("clienteCuentaCorrienteId");
        modelBuilder.HasOne(x => x.Comprobante).WithOne(p => p!.usuarioCuentaCorriente);
    }
}

Mi configuracion (Comprobante):
using EntityFramework.Data;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EntityFramework.Configuracion;
public class ComprobanteConfiguracion : IEntityTypeConfiguration<Comprobantes>
{
    public void Configure(EntityTypeBuilder<Comprobantes> modelBuilder)
    {
        modelBuilder.ToTable("comprobantes");
        modelBuilder.HasKey(e => e.comprobanteId);
        modelBuilder.Property(e => e.comprobanteDescripcion).IsRequired();
        modelBuilder.Property(e => e.fechaEfectuado).IsRequired().HasColumnName("fechaEfectuado");
        modelBuilder.HasOne(e => e.comprobanteTipo).WithOne(p => p!.Comprobante);
        modelBuilder.HasOne(e => e.usuarioCuentaCorriente).WithOne(p => p!.Comprobante);
    }
}

Mi configuracino (Comprobante tipo)
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EntityFramework.Configuracion;

public class ComprobanteTipoConfiguracion : IEntityTypeConfiguration<Comprobantes_Tipo>
{
    public void Configure(EntityTypeBuilder<Comprobantes_Tipo> modelBuilder)
    {
        //ESTRUCTURA
        modelBuilder.ToTable("comprobantes_tipo");
        modelBuilder.HasKey(e => e.comprobanteTipoId);
        modelBuilder.Property(e => e.descripcion).IsRequired();
        modelBuilder.HasOne(x => x.Comprobante).WithOne(p => p!.comprobanteTipo);

        //DATOS FIJOS
        modelBuilder.HasData(
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 1,
                descripcion = "PEDIDO"
            },
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 2,
                descripcion = "COMPROBANTE DE DEUDA"
            },
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 3,
                descripcion = "FACTURA A"
            },
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 4,
                descripcion = "FACTURA B"
            },
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 5,
                descripcion = "PRUEBA"
            },
            new Comprobantes_Tipo
            {
                comprobanteTipoId = 6,
                descripcion = "PRUEBA2"
            });
    }
}

Anotacion:
EL ERROR ME LO TIRA EN TEORIA EN LA TABLA USUARIOS CUENTA CORRIENTE CUANDO QUIERO ESTABLECER LA RELACION CON LA TABLA COMPROBANTES, SEGUN ESTOY LEYENDO EN EL MENSAJE DE ERROR

A: La entidad Usuarios_Cuenta_Corriente deberia crear la tabla clienteCuentaCorriente. Ahora intenta crear la tabla comprobantes y esa tabla ya existe.
Por ejemplo:
public class UsuarioCuentaCorrienteConfiguracion : IEntityTypeConfiguration<Usuarios_Cuenta_Corriente>
{
    public void Configure(EntityTypeBuilder<Usuarios_Cuenta_Corriente> modelBuilder)
    {
        modelBuilder.ToTable("clienteCuentaCorriente");
        modelBuilder.HasKey(e => e.clienteCuentaCorrienteId).HasName("clienteCuentaCorrienteId");
        modelBuilder.HasOne(x => x.Comprobante).WithOne(p => p!.usuarioCuentaCorriente);
    }
}


text:
Q: How to parse the key value field with Jackson parser android I am using jackson parser.
What type of field should be created in model class to parse the following field with Object Mapper.
directions":
{
 "1":"Heat oil in a nonstick skillet coated with cooking spray over medium heat. Add red bell pepper and garlic; cook, uncovered, 30 minutes, stirring occasionally. Set aside, and cool slightly.",
 "2":"Place pepper mixture in a blender; add chopped basil and next 3 ingredients. Process until smooth, stopping once to scrape down sides.",
 "3":"Cook pasta according to package directions, omitting salt and fat.",
 "4":"To serve, top pasta with pepper sauce. Garnish with basil sprigs, if desired."
}

I have created the field
private HashMap<String,String> directions;

But while parsing it is showing an exception
 com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [map type; class java.util.HashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] from String value;
 no single-String constructor/factory method (through reference chain: com.project.android.vo.ModelClass["directions"])


text:
Q: Bootstrap4 multi-slide carousel with Django I'm trying to build a dynamic multi-slide carousel with Django and Bootstrap.
Following the instructions laid out here, I've built the following but there is a problem with the html as the data from the model is not rendered on screen. (I am certain that it is a problem with the below as I have another similar carousel on the page which works fine).
template.html:

            {% for modelInstance in modelData %}
            {% if forloop.first %}

            {% endif %}

          {% endfor %}

            Previous

            Next

Thanks!

A: Simplest way to explain it:
                     {% for modelInstance in modelData %}


text:
Q: how to send html value per post in the same php file without refreshing page I have a table with buttons and I want to send a value depending on the button activated to perform a php query in the same file without refreshing the page, how can I do??.. help.
I'm trying to use ajax but it doesn't work for me..
in the buttons saved in the tables I assign the id of each row in the value of the button and that value I want to send it by ajax to a fragment of php code within the same file to make a query and fill out a form that details more each record .

<?php
    session_start();

?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link rel="stylesheet" href="css/style_table.css">

 Intervenciones

<form name="back" method="post" action="Home.html" class="regresarform">
    <input class="btn__submit" type="submit" value="Regresar">
</form>

        id
        carpeta
        numeros intervenidos
        Nombre Juez
        Numero de Resolucion
        Objetivos

    <?php

    $conexion=mysqli_connect("192.168.0.13", "FGE", "MARJ901201", "mps");
    $criterio = $_POST['buscarporinter'];
    $variable_B = $_POST['dateinterv'];

    if($criterio === "1"){
        $FLAG_B = "carpeta";
    }
    elseif ($criterio==="2"){
        $FLAG_B = "numeros";
    }elseif ($criterio === "3") {
        $FLAG_B = "juez";
    }elseif ($criterio ==="4") {
        $FLAG_B = "resolucion";
    }elseif ($criterio ==="5") {
        $FLAG_B = "fechainicio";
    }elseif ($criterio ==="6") {
        $FLAG_B = "fechatermino";
    }elseif ($criterio ==="7") {
        $FLAG_B = "duracion";
    }elseif ($criterio ==="8") {
        $FLAG_B = "informeinicial";
    }elseif ($criterio ==="9") {
        $FLAG_B = "informemes1";
    }elseif ($criterio ==="10") {
        $FLAG_B = "informemes2";
    }elseif ($criterio ==="11") {
        $FLAG_B = "informemes3";
    }elseif ($criterio ==="12") {
        $FLAG_B = "terminacion";
    }elseif ($criterio ==="13") {
        $FLAG_B = "conclusion_ant";
    }elseif ($criterio ==="14") {
        $FLAG_B = "objetivos";
    }

    $sql="SELECT *FROM intervenciones where $FLAG_B like '$variable_B%'";
    $result = mysqli_query($conexion, $sql);

    $A = array();
    $count = 0;
    while($mostrar1=mysqli_fetch_array($result)){
        array_push($A, $mostrar1['idintervenciones']);
    ?>

        <?php echo $mostrar1['idintervenciones'] ?>
        <?php echo $mostrar1['carpeta'] ?>
        <?php echo $mostrar1['numeros'] ?>
        <?php echo $mostrar1['juez'] ?>
        <?php echo $mostrar1['resolucion'] ?>
        <?php echo $mostrar1['objetivos'] ?>
        <button value="<?php echo $mostrar1['idintervenciones']?>" class="edit" onclick="openForm()">EDITAR</button>
            <button class="edit"  onclick="enviarDatos(this)" id="<?php echo  $mostrar1['idintervenciones']; ?>" value="<?php echo  $mostrar1['idintervenciones']; ?>"  >VER</button>

    <?php
    $count++;
    }

    ?>

  <form class="form-container" action="" enctype="multipart/form-data" method="POST">

Agregar Avance

    <input type="text" placeholder="Agregar Avance" name="avances" required>
    <button type="submit" class="btn">GUARDAR</button>
    <button type="button" class="btn cancel" onclick="closeForm()">CANCELAR</button>
  </form>

    <?php
        print("....".$_POST['ver']);
        if (isset($_POST['ver'])) {
            /* Agregamos los datos recibidos a la variable de sesión */
            array_push($_SESSION['datos'], $_POST['ver']);
            $id = $_POST['ver'];
            print($id);
            header('Content-type: application/json; charset=utf-8');
            $conexion=mysqli_connect("192.168.0.13", "FGE", "MARJ901201", "mps");
            $sql2="SELECT *FROM intervenciones where idintervenciones = $id";
            $result2 = mysqli_query($conexion, $sql2);
            $mostrar=mysqli_fetch_row($result2);
            die(json_encode(true));
        }

    ?>

Usuario: ----

Inteligencia. UECS

Registro de intervenciones

        <button onclick="closeVer()">CERRAR</button>

Información de  Intervención

      <form class="formulario" action="" enctype="multipart/form-data" method="POST">

          Carpeta
          <input type="text" readonly="readonly" value="<?php echo $mostrar[1]?>">

          Numeros Intervenidos
          <input type="text"readonly="readonly" value="<?php echo $mostrar[2]?>">

          Juez
          <input type="text"readonly="readonly" value="<?php echo $mostrar[3]?>">

          Numero de Resolucion
          <input type="text" readonly="readonly" value="<?php echo $mostrar[4]?>">

          Fecha de inicio
          <input type="text"readonly="readonly" value="<?php echo $mostrar[5]?>">

          Fecha de terminacion
          <input type="text"readonly="readonly" value="<?php echo $mostrar[6]?>">

          Duracion de Intervencion
          <input type="text"readonly="readonly" value="<?php echo $mostrar[7]?>">

          Informe Inicial
          <input type="text"readonly="readonly" value="<?php echo $mostrar[8]?>">

          Informe mes 1
          <input type="text" readonly="readonly" value="<?php echo $mostrar[9]?>">

          Informe mes 2
          <input type="text" readonly="readonly" value="<?php echo $mostrar[9]?>">

          Informe mes 3
          <input type="text" readonly="readonly" value="<?php echo $mostrar[10]?>">

          Terminacion
          <input type="text" readonly="readonly" value="<?php echo $mostrar[11]?>">

          Conclusion Anticipada
          <input type="text" readonly="readonly" value="<?php echo $mostrar[12]?>">

          Objetivos
          <input type="text" readonly="readonly" value="<?php echo $mostrar[13]?>">

          Avances
          <textarea name="" id="" cols="30" rows="7" readonly="readonly" value="<?php echo $mostrar[14]?>"></textarea>

      </form>


text:
Q: Converting VB to C# with Linq and Reflection I'm working on a project converting some VB to C#.  This particular Linq query works fine in VB, but it's giving me fits trying to convert.
The C# piece that I'm struggling with is the group by
prop.GetProperty(stringColumn).GetValue(s, null).ToString()
The compiler error is

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

It also notes that the s variable in the select does not exist.
VB
(From s In query Group By StringValue =
    prop.GetProperty(stringColumn).GetValue(s, Nothing)
          Into NumTotal =
          Sum(Double.Parse(prop.GetProperty(numberColumn).GetValue(s, Nothing).ToString()))
          Order By NumTotal Descending Select StringValue, NumTotal)

C#
(from s in query group s by
 new {prop.GetProperty(stringColumn).GetValue(s, null).ToString()} into NumTotal
    select new {
        StringValue = prop.GetProperty(stringColumn).GetValue(s, null),
        NumTotal = NumTotal.Sum(x =>
            Double.Parse(prop.GetProperty(numberColumn).GetValue(s, null).ToString()))})

I saw this, but I really didn't understand how the Expression stuff was supposed to work, and wasn't sure if it should be part of my solution.
What am I missing in the conversion, and why would two seemingly similar queries behave so differently?
Thanks


text:
Q: Exporting a project for an older version of Android Studio I am running Android Studio version 3.5.1. My students have version 3.4.2, and it's not practical to update their IDE because of security restrictions on the school computers.
When I export a project as a .zip file, they aren't able to open the project in their IDEs.
Is there a way for
(a) an older version of Android Studio to import a newer project?
or
(b) a newer version of Android Studio to export a project for an older IDE?

A: The Android Gradle Plugin is not forward compatible. You can downgrade the Android Gradle Plugin to 3.4.2 if you're not using a specific feature in 3.5.1.
dependencies {
    classpath 'com.android.tools.build:gradle:3.4.2'
}


text:
Q: react native ref measureLayout I am following this tutorial
https://www.youtube.com/watch?v=ZiSN9uik6OY&list=RDCMUCTcH04SRuyedaSuuQVeAcdg&start_radio=1&t=1398
The problem is when I console.log( i.ref.current), I see all value. The ap will just not start with error Undefined is not an Object inside the app.
and in reactive native console following comes up
This error is located at:
    in Tabs (at App.js:118)
    in RCTView (at View.js:34)
    in View (at App.js:91)
    in App (at renderApplication.js:47)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:107)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:134)
    in AppContainer (at renderApplication.js:40)
 ERROR  TypeError: undefined is not an object (evaluating 'nativeNode._nativeTag')

below is the app.js file:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Dimensions, Animated, FlatList, Image } from 'react-native';

const {width, height} = Dimensions.get('screen')

const images = {
  man:
    'https://images.pexels.com/photos/3147528/pexels-photo-3147528.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500',
  women:
    'https://images.pexels.com/photos/2552130/pexels-photo-2552130.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500',
  kids:
    'https://images.pexels.com/photos/5080167/pexels-photo-5080167.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500',
  skullcandy:
    'https://images.pexels.com/photos/5602879/pexels-photo-5602879.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500',
  help:
    'https://images.pexels.com/photos/6857165/pexels-photo-6857165.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500',
};
const data = Object.keys(images).map((i) => ({
  key: i,
  title: i,
  image: images[i],
  ref: React.createRef()
}));

const Indicator = () =>{
  return (<View  style={{
    position:'absolute',
    height:4,
    width:100,
    backgroundColor:'white',
    bottom: -10
   }}/>);

}

const Tab = React.forwardRef(({item}, ref) => {
  return (
    <View ref={ref}>
      <Text style={{
        color:'rgba(255, 255, 255, 0.8)',
        fontWeight:'800',
        fontSize:84/data.length,
        textTransform: 'uppercase' }}>{item.title}</Text>
    </View>
  );
});

const Tabs  = ({data, scrollX}) =>{
  const [measures, setMeasures] = React.useState([])
  const containerRef = React.useRef();

  React.useEffect(() => {
    let m = []
    data.forEach((i) => {
      i.ref.current.measureLayout(
        containerRef.current,
        (x, y, width, height) => {
          m.push({x, y, width, height})
          console.log(x, y, width, height)
        }
      );
        if(m.length === data.length){
          setMeasures(m)
        }
    });
  }, [])
  console.log(measures);
   return( <View style={{ position: 'absolute', top:50, width }}>
      <View style={{justifyContent:'space-evenly', flex:1, flexDirection:'row'}}>
        {
          data.map((item) => {
            return <Tab key={item.key} item={item} ref={item.ref} />
          })
        }
      </View>
      <Indicator/>
    </View>
  )

}

export default function App() {
  const scrollX = React.useRef(new Animated.Value(0)).current;

  return (
    <View style={styles.container}>
      <StatusBar hidden />
      <Animated.FlatList
        data={data}
        keyExtractor={item => item.key}
        renderItem={({item}) => {
            return (<View style={{width, height}}>
              <Image
                source={{uri: item.image}}
                style={{flex:1, resizeMode:'cover'}}
                />
                <View style={
                   [
                     StyleSheet.absoluteFillObject,
                     {backgroundColor: 'rgba(0,0,0, 0.3)' }
                   ]}/>
            </View>)
          }
        }
        horizontal
        showsHorizontalScrollIndicator={false}
        pagingEnabled
        onScroll={Animated.event([{nativeEvent: {contentOffset :{x: scrollX } }}],
          {useNativeDriver: false}
          )}
        bounces={false}
        />
        <Tabs scrollX={scrollX} data={data} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
}); ```

Thanks. appreciate your time reading this

A: The problem is that you haven't attached containerRef to any View.
Since the ref isn't attached to a component containerRef.current evaluates to undefined, causing the logic in the useEffect to break.
So your the Tabs component should probably look more like this:
const Tabs = ({data, scrollX}) => {
  const [measures, setMeasures] = React.useState([]);
  const containerRef = React.useRef();

  React.useEffect(() => {
    let m = [];
    data.forEach((i) => {
      i.ref.current.measureLayout(
        containerRef.current,
        (x, y, width, height) => {
          m.push({x, y, width, height});
          console.log(x, y, width, height);
        },
      );
      if (m.length === data.length) {
        setMeasures(m);
      }
    });
  }, []);

  return (
    <View style={{position: 'absolute', top: 50, width}}>
      <View
        ref={containerRef}
        style={{justifyContent: 'space-evenly', flex: 1, flexDirection: 'row'}}>
        {data.map((item) => {
          return <Tab key={item.key} item={item} ref={item.ref} />;
        })}
      </View>
      <Indicator />
    </View>
  );
};


text:
Q: XSLT converting question I have some Microsoft Office Word file, saved as Office XML format output. I am wondering whether there are any XSLT samples which could convert Office XML format output into HTML format? Any other solutions (besides using XSLT) which could convert Office XML format output into HTML format is acceptable.
thanks in advance,
George

A: If your collection of files is not large, then the easiest way to convert to HTML is to use Microsoft Word's save as HTML feature.  If the goal is to produce HTML output, regardless of the cleanliness of the output, that's the way to go.
You can also use a recorded macro to get MS Word to convert large numbers of files.
Edit: Answering comments
I mean use Microsoft Word to open the file (using File, Open), then using File, Save As and choosing "Web Page" as the type.  As for the macro, you can use this Microsoft reference for macros.


text:
Q: Executing Perl command from shell script not resulting into anything I am trying to execute the below command from a shell script:
perl -pi -e 's/Ç/|/g' diff_new_old.dat
This command gets executed without any errors, but the execution doesn't do the intended substitution. It doesn't seem like shell has an issue with execution of perl command, since         perl -pi -e 's/\n/\r\n/g' diff_new_old.dat works fine. It looks like an issue with special character substitution.
When I execute the same command directly on $ prompt, it executes fine and substitutes all Ç characters with | in the file. I want to automate this process and thus need a way to get this done from a shell script.
I have also tried using the sed 's/Ç/|/' command. But this results into below error:
sed: -e expression #1, char 6: unterminated `s' command
Please let me know what I can do to achieve the substitution.
Thanks in advance.

A: You may have to tell perl that the script contains UTF-8 characters:
perl -Mutf8 -pi -e 's/Ç/|/g' diff_new_old.dat

see http://perldoc.perl.org/utf8.html


text:
Q: Rails pluck error error undefined method `pluck' for # User:0x00000007234e28
I want to get the details of the last two registered users.
def index
    if User.exists?
        user1 = User.first.pluck(:id)
        user2 = User.second.pluck(:id)
    end
end

A: To solve your problem you can do the following
def index
  last_two_users = User.order(created_at: :asc).limit(2).pluck(:id)
end

You can sort on the created_at column if you have one, or on the id column. If you use the id column change asc to desc.
A different way is to use map:
last_two_users = User.last(2).map(&:id)

The last_two_users will have the last 2 users added to your table.


text:
Q: Selecting artifacts on basis of value in selectbox using SOAP interface Using Tuleap 8.13.99.65 on Centos 6.7
Using the get_artifacts.php example script I tried to modify it to find all artifacts in a tracker with a status of 'Completed' however when I run the script it returns all records regardless of their status.  The status field is called status_id and is a fixed select box. I've found the bind_status_id for the Completed status and included it but I still get all artifacts returned.
I'm pretty new to this so it is almost definitely being caused by a mistake on my part but I can't spot it.
I've included a small section of the code, where the query is defined, can anyone spot where I've gone wrong?
$project_id = 0; //not needed
$tracker_id = 20;
$offset     = 0;
$limit      = 100;
$criteria = array(
    array(
        'field_name' => 'status_id',
        'value' => array(
            'bind_value' => array(
                'bind_value_id' =>  '504',
                'bind_value_label' => 'Completed'
            )
        )
    )
);

Any help would be much appreciated.
Thanks in Advance

A: I've just learned that the SOAP interface is deprecated and will be discontinued soon so I guess my question is no longer relevant.
Time to learn the REST API instead!


text:
Q: Statements out of function, but where? Trying to get my last assignment in for the quarter, balance my job, and my other class. I would love an extra set of eyes to tell me where in the world my statements go out outside of my function:
This is an implementation file. The associated header is throwing no errors.
I get the following errors:
1.) In the file included from tests.cpp:7:0:
GBoard.cpp:31:2: error: expected unqualified-id before 'for'
for (int r=0; r<15; r++)

2.) GBoard.cpp:31:14: error: 'r' does not name a type
for (int r=0; r<15; r++)

But I am pretty sure 2 is part of my code being outside of the function somehow.
Here is my code, parts redacted so I don't get hit w/ plagiarism:
bool Gfunction::makeMove(int redacted,int redacted,char secret)
{

    if(redacted >= 0 && redacted < 15 && redacted >= 0 && redacted<15)
    {
        if(redacted() == UNFINISHED && function[redacted][redacted] == '.')
        function[redacted][redacted] = secret;
        return true;
    }
        else
    {
        return false;

    }

    int track = 0;

    for(int r=0;r<15;r++)
    {
        track = 0;
            for(int c=0;c<15;c++)
            {
                    if(function[r][c] == secret)
                    {
                track++;
                    if(track==5)
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                            secret squirrel stuff = O_WON;
                                return true;
                    }
                }
                else
                {
                    track = 0;
                }
        }

    }

    for(int r=0;r<15;r++)
    {
            track = 0;
            for(int c=0;c<15;c++)
            {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track==5)
                        {
                            if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }

                    }
                        else
                    {
                            track = 0;
                    }
            }

    }

        int r = 0, c = 0;
        for(int redacted = 0; redacted<15; redacted++)
        {
            r = redacted;
                c = 0;
                track = 0;
                while(r < 15 && c < 15)
                {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
                }
                        else
                        {
                                track = 0;
                        }
                                r++;
                                c++;
        }
    }

    for(int redacted = 0; redacted<15; redacted++)
    {
            r=0;
            c=redacted;
            track=0;
            while(r<15 && c<15)
                {
                    if(function[r][c] == secret)
                    {
                            track++;
                            if(track == 5)
                            {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
            }
                        else
                        {
                                track = 0;
                        }
                                r++;
                                c++;
                }
        }

    for(int redacted=0; redacted<15; redacted++)
    {
        r=redacted;
        c=15-1;
        track=0;
        while(r<15 && c>=0)
        {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)
                {
                    if(secret == 'x')
                            secret squirrel stuff = X_WON;
                            else
                            secret squirrel stuff = O_WON;
                            return true;
                        }
            }
                            else
                    {
                            track = 0;
                    }
                            r++;
                            c--;
        }
    }

    for(int redacted=15-1;redacted>=0;redacted--)
    {
            r=0;
            c=redacted;
            track=0;
            while(r<15 && c>= 0)
            {
                    if(function[r][c] == secret)
                    {
                        track++;
                        if(track == 5)
                        {
                                if(secret == 'x')
                                secret squirrel stuff = X_WON;
                                else
                                secret squirrel stuff = O_WON;
                                return true;
                        }
            }
                        else
                        {
                            track = 0;
                        }
                            r++;
                            c--;
            }
        }

    for(int r=0;r<15;r++)
    {
            for(int c=0;c<15;c++)
            {
            if(function[r][c] == '.')
                {
                    secret squirrel stuff = UNFINISHED;
                    return true;
            }
        }
    }
        secret squirrel stuff = DRAW;
        return true;
}

A: Double check your innermost if statements. For example:
if(track == 5)
{
    if(secret == 'x')
        secret squirrel stuff = X_WON;
        else
        secret squirrel stuff = O_WON;
        return true;
}

could be
if(track == 5)
{
    if(secret == 'x')
        secret squirrel stuff = X_WON;
    else
        secret squirrel stuff = O_WON;
    return true;
}

or
if(track == 5)
{
    if(secret == 'x')
        secret squirrel stuff = X_WON;
     else{
        secret squirrel stuff = O_WON;
        return true;
     }
}

depending on you algorithm logic.


text:
Q: How to handle Abs constraints in Gurobi? I have a abs constraint in Gurobi. I have look into the manual of official guide. It provides two ways to add abs constraints.
  # x5 = abs(x1)
  model.addGenConstrAbs(x5, x1, "absconstr")

  # overloaded form
  model.addConstr(x5 == abs_(x1), name="absconstr")

I have to use the second form, because I need to draw the dual value of this constraint. Only addConstr can be drew the shadow price(dual value), so addGenConstrAbs should be avoided.
My code is :
    def _build_constraints(self):
        m = self.model
        com = self.data.com
        P_nm3 = self.variables.P_nm3
        agents = self.data.agents

        timewindow = self.data.timewindow
        windowinterval = self.data.windowinterval

        absP_n = self.variables.absP_n
        P_n = self.variables.P_n

        self.constraints.absv = {}

        for t1 in timewindow:
            for t2 in windowinterval:
                for i, p in enumerate(agents):
                    if p in self.data.generators:
                        pass
                    else:
#                        self.constraints.absv[t1,t2,p] = m.addGenConstrAbs( absP_n[p,t1,t2], P_n[p,t1,t2])
                        self.constraints.absv[t1,t2,p] = m.addConstr( absP_n[p,t1,t2] == abs_(P_n[p,t1,t2]), name="absconstr" )

And I get the error like this :
AttributeError: 'gurobipy.Model' object has no attribute 'abs_'

the version of Gurobi is V9.0. It seems the method mentioned doesn't work at all.
How can I solve this?
Thanks a lot!

A: You need to make sure that you also import the abs_ function - in case you did not from gurobipy import *. So you either need to do
from gurobipy import abs_
model.addConstr(x == abs_(y))

or
import gurobipy as gp
model.addConstr(x == gp.abs_(y))


text:
Q: Convering values stored within another language to case classes Rookie question here.
I have 2 apps that utilize Hazelcast, one is in Typescript and the other is in Scala.
The Typescript app stores all the data and the Scala one interacts with it.

I need an easy way to parse items inside of a map to a case class, this is easy if the HazelCast data is saved within Scala because it can be cast but when I attempt to do this with data stored from Typescript I get the following
java.lang.ClassCastException: com.hazelcast.core.HazelcastJsonValue cannot be cast to TheCaseClass

I'm using circe and finch in the rest of the application, not sure if circe can be used here to parse it.
tl;dr Is there an easy way to convert HazelCast data stored in Typescript to a Scala case class.
Thanks

A: You cannot just take one arbitrary class and cast it to another class. You have to parse them. If you use Hazelcast then probably Hanzelcast Scala is what you should use.
Wiki suggest that you would have to do at least:
import com.hazelcast.Scala._

serialization.Defaults.register(conf.getSerializationConfig)

though it might require you to write your own custom serialization.


text:
Q: How do I check if a word ends with a certain string, from a file? I already have this code:
f = open("unknown.txt", 'r')
a = sum(line.count('ly').endswith() for line in f)

words = 0

with open("unknown.txt", 'r') as f:
    words = len(f.read().split())

try:
    percentage = a/words*100
    print('{}% adverbs'.format(percentage))
except:
    print('File is empty!')

But all this does is check if there is 'ly' in a word, how do I make it so only count as 'ly' if .endswith('ly') (i'm guessing those commands are going to be used, but i don't know how. Can someone please make my code do this? Thanks in advance!

A: You have to split your lines into words and test each word:
a = sum(word.endswith('ly') for line in f for word in line.split())

This (ab)uses the fact that the Python boolean is a subclass of int and True == 1 and False == 0.
You can make it more explicit with a filter:
a = sum(1 for line in f for word in line.split() if word.endswith('ly'))

You may want to combine both counts into one loop however:
with open("unknown.txt", 'r') as f:
    total = lycount = 0
    for line in f:
        words = line.split()
        total += len(words)
        lycount += sum(1 for word in words if word.endswith('ly'))

try:
    percentage = (lycount / total) * 100
    print('{}% adverbs'.format(percentage))
except ZeroDivisionError:
    print('File is empty!')

Note that you should never use a blanket except statement; just catch the specific exception instead.


text:
Q: How can we create an object with same name as its class? How can we use same name for class and object , without any issues from the compiler ?
class A{
    public static void main (){
        A A = new A ();
    }
}

Or
class A{
    public static void main(){
        String String="java";
        System.out.println(String);
    }
}

How does the java compiler handle this?

A: In Java it is absolutely correct to specify the name of the class and the name of the variable to be exactly the same. The compiler understands the syntax so it knows what part of the program represents the identifier and what part represents the class name.
But you should never do it as it will become a readability nightmare. Absolutely misleading and violating Java Naming Conventions.


text:
Q: Pass argument store in variable to argparse This is my script mytest.py.
import argparse
parser = argparse.ArgumentParser(description="Params")
parser.add_argument(
        "--value")

def test(args):
  print(args.value)

args = parser.parse_args()
test(args)

I want to pass argument store in variable val
val =1
!python mytest.py --value val

instead of printing 1 it print val. How to send 1 stored in variable val.

A: argparse always get argument as string, or list of strings on default, and what you do on your shell is irrelevant with python program. It is no wonder val is printed.
Use file that contains "1" and read that file to do what you intended to.

A: As jueon park said naming a variable in commandline wont work

It would create an error like the above one.If you are calling the command from any programer will work but in cmd it won't work

A: I'm very late for this but your python code works just fine. The problem you have is that you are not passing the arguments correctly.
For this to work first you need to correctly set the variable:
val=1

(note that the "=" must be next to both the variable name and the value)
and the you can simply use $ to get the value from the variable. So:
python mytest.py --value $val


text:
Q: What are database escape() and quote() used for? I looked at some joomla components and there are functions like
$db->escape()
$db->quote()

What are they used for ?
Thanks

A: Thes escape function is used to escape bad characters in order to protect against SQL injection.
The quote* functions are used to quote strings, because different database dialects have different quoting characters.
So depending on the database system you use, Joomla will choose the appropriate quoting characters.


text:
Q: Delaying the search function in keypress actions I'm trying to delay an action on a textbox. I want to search a large quantity of text for a word. Now I do this with the "textchanged" event. The problem here is, when he reaches a word of more then 3 letters (I've prevented 0-2 wordsearches) the process becomes intensive.
Question:
What are my possibilities here?

*

*ex: Putting a timer on the textchanged-event? If so, how do I do this?

Code:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
 // delay here
 dosearch(searchbox.text);
}

A: (Re)start a dispatcher timer every time a key is pressed, and do the search when the timer elapses. Around 200-300 ms delay is usually pretty good.
private DispatcherTimer _searchTimer;

// Initialize timer in constructor with 200 ms delay and register tick event.

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    _searchTimer.Stop();
    _searchTimer.Start();
}

private void OnSearchTimerTick(object sender, EventArgs e)
{
    _searchTimer.Stop()
    Search(searchBox.Text);
}

private void Search(string searchTxt)
{
    // Do search
}

UPDATE:
To improve the responsiveness (the above example will lock the UI while searching because the dispatcher timer callback runs on the UI thread), you can execute the search in a separate Task. When the search completes you need to ensure that the result is not stale (that the user has not modified the search text while searching):
private void Search(string searchText)
{
    Task.Run(() =>
        {
            // Execute search

            Dispatcher.Invoke(() =>
            {
                if (searchText == searchBox.Text)
                {
                    // Result is good
                }
            });
    });
}


text:
Q: Getting empty dictionary in python I have this code:
 def saveInfo(self):

            info = {}
            info["title"] : self.getHeading()
            info["user"] : self.getUser()
            info["location"] : self.file_path
            info["uploaded"] : False

            print(info)
            self.writeToJSONFile(self.workspace, 'ri', info)

but whenever i print the 'info' or try to save in json, I only get this printed: {}
and json file be like: {}{}{}{}...

A: You're mixing dictionary assignment and literal syntax (see the docs) and accidentally not causing syntax errors because it looks like a type annotation.
The idiomatic way to construct this dictionary would be:
info = {
    "title": self.getHeading(),
    "user": self.getUser(),
    "location": self.file_path,
    "uploaded": False,
}

Alternatively, you can assign each key one at a time with the = operator (not :!):
info = {}
info["title"] = self.getHeading()
info["user"] = self.getUser()
info["location"] = self.file_path
info["uploaded"] = False


text:
Q: Deadlock in producer-consumer C programming I am trying to implement a single-producer-multi-consumer program in C, and I'm using the character '\0' in consumer to see whether it is the end of the file. However, deadlock occurs when when there are multi-consumer and when they all waiting for last character but only one of them entered critical section and consume this character. Here is my code:
void insert(char* buffer, char value){
    printf("lock in insert %c\n", value);
    sem_wait(&empty);
    sem_wait(&mutex);
    printf("insert %c\n",value);
    buffer[in] = value;
    in = (in+1) % BUFFER_SIZE;
    sem_post(&mutex);
    sem_post(&full);
}
char get(char* buffer) {
    char item;
    printf("lock in get\n");

    sem_wait(&full);
    sem_wait(&mutex);
    item = buffer[out];
    printf("comsume %c\n",item);
    out = (out+1)%BUFFER_SIZE;
    sem_post(&mutex);
    sem_post(&empty);
    return item;
}
void *produce(void *param) {
    int i=0;
    char randomChar;
    for(i=0; i<NUM_OF_INTEGERS; ++i) {
        randomChar = 'A' +random()%26;
        insert(buffer, randomChar);
    }
    insert(buffer, '\0');
    printf("produce finished\n");
}

void *consume(void *param) {
    int i=0;
    char data;
    do{
        data = get(buffer);
    }while(data != '\0');
    printf("consume finished\n");
}

A: As others have mentioned, you need to send more than one terminator (i.e.) one for each consumer.
In produce, change:
insert(buffer, '\0');

Into:
for (i=0; i<NUM_OF_CONSUMER; ++i)
    insert(buffer, '\0');

A: Segmentation fault can occur.
buffer size is of 10 Bytes and you are actually storing 20 Bytes.
Change buffer size to 20
#define BUFFER_SIZE 20


text:
Q: AudioEngine to CMSampleBuffer I am using AVAudioEngine to capture audio from macOS microphone and some other sources to mix multiple audio inputs, since the AVAudioCaptureSession does not have a feature to mix multiple inputs. Therefore, I am trying to convert the AVAudioPCMBuffer which I can obtain by installing a tap to the node of audioengine and convert it back to CMSampleBuffer. This is what I got so far.
engine.mainMixerNode.installTap(onBus: 0, bufferSize: 4096, format: format) { (buffer, time) in
    var sbuf : CMSampleBuffer?

    var timing = CMSampleTimingInfo(duration: CMTimeMake(value: 4096, timescale: 44100), presentationTimeStamp: .zero, decodeTimeStamp: .invalid)

    let code = CMSampleBufferCreate(allocator: kCFAllocatorDefault, dataBuffer: nil, dataReady: false, makeDataReadyCallback: nil, refcon: nil, formatDescription: buffer.format.formatDescription, sampleCount: CMItemCount(4096), sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sbuf)
    print(code)
    let status = CMSampleBufferSetDataBufferFromAudioBufferList(sbuf!, blockBufferAllocator: kCFAllocatorDefault, blockBufferMemoryAllocator: kCFAllocatorDefault, flags: 0, bufferList: buffer.audioBufferList)
    print(status)
}

However, when I do print(status) it prints -12731, and the databuffer is not initialized.
I am not sure what I did wrong.


text:
Q: Using seekg() in text mode While trying to read in a simple ANSI-encoded text file in text mode (Windows), I came across some strange behaviour with seekg() and tellg(); Any time I tried to use tellg(), saved its value (as pos_type), and then seek to it later, I would always wind up further ahead in the stream than where I left off.
Eventually I did a sanity check; even if I just do this...
int main()
{
   std::ifstream dataFile("myfile.txt",
         std::ifstream::in);
   if (dataFile.is_open() && !dataFile.fail())
   {
      while (dataFile.good())
      {
         std::string line;
         dataFile.seekg(dataFile.tellg());
         std::getline(dataFile, line);
      }
   }
}

...then eventually, further into the file, lines are half cut-off. Why exactly is this happening?

A: This issue is caused by libstdc++ using the difference between the current remaining buffer with lseek64 to determine the current offset.
The buffer is set using the return value of read, which for a text mode file on windows returns the number of bytes that have been put into the buffer after endline conversion (i.e. the 2 byte \r\n endline is converted to \n, windows also seems to append a spurious newline to the end of the file).
lseek64 however (which with mingw results in a call to _lseeki64) returns the current absolute file position, and once the two values are subtracted you end up with an offset that is off by 1 for each remaining newline in the text file (+1 for the extra newline).
The following code should display the issue, you can even use a file with a single character and no newlines due to the extra newline inserted by windows.
#include <iostream>
#include <fstream>

int main()
{
  std::ifstream f("myfile.txt");

  for (char c; f.get(c);)
    std::cout << f.tellg() << ' ';
}

For a file with a single a character I get the following output
2 3

Clearly off by 1 for the first call to tellg. After the second call the file position is correct as the end has been reached after taking the extra newline into account.
Aside from opening the file in binary mode, you can circumvent the issue by disabling buffering
#include <iostream>
#include <fstream>

int main()
{
  std::ifstream f;
  f.rdbuf()->pubsetbuf(nullptr, 0);
  f.open("myfile.txt");

  for (char c; f.get(c);)
    std::cout << f.tellg() << ' ';
}

but this is far from ideal.
Hopefully mingw / mingw-w64 or gcc can fix this, but first we'll need to determine who would be responsible for fixing it. I suppose the base issue is with MSs implementation of lseek which should return appropriate values according to how the file has been opened.

A: Thanks for this , though it's a very old post. I was stuck on this problem for more then a week. Here's some code examples on my site (the menu versions 1 and 2). Version 1 uses the solution presented here, in case anyone wants to see it .
:)
void customerOrder::deleteOrder(char* argv[]){
std::fstream newinFile,newoutFile;
newinFile.rdbuf()->pubsetbuf(nullptr, 0);
newinFile.open(argv[1],std::ios_base::in);
if(!(newinFile.is_open())){
     throw "Could not open file to read customer order. ";
}
newoutFile.open("outfile.txt",std::ios_base::out);
if(!(newoutFile.is_open())){
     throw "Could not open file to write customer order. ";
}
newoutFile.seekp(0,std::ios::beg);
std::string line;
int skiplinesCount = 2;

if(beginOffset != 0){
    //write file from zero to beginoffset and from endoffset to eof   If to delete is non-zero
    //or write file from zero to beginoffset    if to delete is non-zero and last record
    newinFile.seekg (0,std::ios::beg);
    // if  primarykey < largestkey , it's a middle record
    customerOrder order;
    long tempOffset(0);

    int largestKey = order.largestKey(argv);
    if(primaryKey < largestKey) {
        //stops right before "current..." next record.
            while(tempOffset < beginOffset){
              std::getline(newinFile,line);
      newoutFile << line << std::endl;
              tempOffset = newinFile.tellg();
        }
        newinFile.seekg(endOffset);
        //skip two lines between records.
            for(int i=0; i<skiplinesCount;++i) {
             std::getline(newinFile,line);
            }
        while( std::getline(newinFile,line) ) {
            newoutFile << line << std::endl;
        }
    } else if (primaryKey == largestKey){
        //its the last record.
        //write from zero to beginoffset.
           while((tempOffset < beginOffset) && (std::getline(newinFile,line)) ) {
              newoutFile << line << std::endl;
              tempOffset = newinFile.tellg();
           }
} else {
        throw "Error in delete key"
    }
}  else {
//its the first record.
//write file from endoffset to eof
//works with endOffset - 4  (but why??)
    newinFile.seekg (endOffset);
    //skip two lines between records.
    for(int i=0; i<skiplinesCount;++i) {
        std::getline(newinFile,line);
    }
    while(std::getline(newinFile,line)) {
        newoutFile << line << std::endl;
   }
}
newoutFile.close();
newinFile.close();

}
beginOffset is a specific point in the file (beginning of each record) , and endOffset is the end of the record, calculated in another function with tellg (findFoodOrder) I did not add this as it may become very lengthy, but you can find it on my site  (under: menu version 1 link) :
http://www.buildincode.com