问:
jq: Change multiple values
I'm trying to change multiple json values with this line

```<code> jq '.two="newval", .three="newval"' my.json
</code>```

with this is the input

```<code>{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "val",
  "four": "val"
}
</code>```

but the output is 2 jsons:

```<code>{
  "one": {
    "val": 1
  },
  "two": "newval",
  "three": "val",
  "four": "val"
}
{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "newval",
  "four": "val"
}
</code>```

How can I change multiple values and output in one item?

答:
Simply change the comma to a pipe character and you’re done:

```<code>.two="newval" | .three="newval"
</code>```

"," is for concatenating streams: A,B will emit A followed by B.

Title: jq: Change multiple values

Body:
I'm trying to change multiple json values with this line

 jq '.two="newval", .three="newval"' my.json

with this is the input

{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "val",
  "four": "val"
}

but the output is 2 jsons:

{
  "one": {
    "val": 1
  },
  "two": "newval",
  "three": "val",
  "four": "val"
}
{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "newval",
  "four": "val"
}

How can I change multiple values and output in one item?

Body:
Simply change the comma to a pipe character and you’re done:

.two="newval" | .three="newval"

"," is for concatenating streams: A,B will emit A followed by B.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to handle exception when using asyncio.wait FIRST_COMPLETED?
Is there any chance to handle exception when using asyncio.wait(coro_obj, return_when=FIRST_COMPLETED)?

I am trying to get my ip from several external resourses. But I am not able to handle the exception when one of the provided urls is broken. loop execution should stop when any of the requests returns the ip.

```<code>import asyncio
import aiohttp
from concurrent.futures import FIRST_COMPLETED

SERVICES = [
    ('ip-api1', 'http://ip-api.com/json', 'query'),
    ('broken_api', 'http://broken', 'query'),
]

async def get_ip(session, service, url, ip_attr):
    print('fetching ip from: {}'.format(service))
    async with session.get(url) as resp:
        json_resp = await resp.json()
        ip = json_resp[ip_attr]
        return service, ip

async def get_ip_from_services():
    async with aiohttp.ClientSession() as session:
        coro_obj = [get_ip(session, service[0], service[1], service[2])
                    for service in SERVICES]
        try:
            done, pending = await asyncio.wait(coro_obj, return_when=FIRST_COMPLETED)
            result = done.pop().result()
            print(result)
            for future in pending:
                future.cancel()
        except:
            print('catched')

loop = asyncio.get_event_loop()
loop.run_until_complete(get_ip_from_services())
loop.close()
</code>```

I am able to catch exception when return_when=ALL_COMPLETED but not FIRST_COMPLETED

I got the following errors:

```<code>fetching ip from: ip-api1
fetching ip from: broken_api
catched
exception calling callback for <Future at 0x103839240 state=finished returned list>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 297, in _invoke_callbacks
    callback(self)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py", line 419, in _call_set_state
    dest_loop.call_soon_threadsafe(_set_state, destination, source)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 620, in call_soon_threadsafe
    self._check_closed()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Task was destroyed but it is pending!
task: <Task pending coro=<ThreadedResolver.resolve() running at /Volumes/external/venv/lib/python3.6/site-packages/aiohttp/resolver.py:31> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py:408, <TaskWakeupMethWrapper object at 0x103807948>()]> cb=[shield.<locals>._done_callback() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py:679]>
Task was destroyed but it is pending!
task: <Task pending coro=<get_ip() done, defined at ./run_7.py:15> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x1038073d8>()]>>
</code>```

or warnings

```<code>fetching ip from: ip-api1
fetching ip from: broken_api
catched
Task was destroyed but it is pending!
task: <Task pending coro=<ThreadedResolver.resolve() running at /Volumes/external/venv/lib/python3.6/site-packages/aiohttp/resolver.py:31> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py:408, <TaskWakeupMethWrapper object at 0x1038e2948>()]> cb=[shield.<locals>._done_callback() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py:679]>
Task was destroyed but it is pending!
task: <Task pending coro=<get_ip() done, defined at ./run_7.py:15> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x1038e23d8>()]>>
</code>```

答:
I think it's a bug in aiohttp, I posted it there.

Exception you recieve doesn't seem to be critical, so you can leave it as is until it fixed in aiohttp. Or don't cancel requests if you don't want to see it now.

Few unrelated notes to your code:

1) Don't use concurrent.futures with asyncio: these are different modules. Use asyncio.FIRST_COMPLETED.

2) You should not only cancel task but also wait it cancelled (it'll raise CancelledError). It can be done with this code:

```<code>for task in pending:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task
</code>```

Read more about tasks/cancelling here.

ContentLicense: CC BY-SA 3.0

Body:
Is there any chance to handle exception when using asyncio.wait(coro_obj, return_when=FIRST_COMPLETED)?

I am trying to get my ip from several external resourses. But I am not able to handle the exception when one of the provided urls is broken. loop execution should stop when any of the requests returns the ip.

import asyncio
import aiohttp
from concurrent.futures import FIRST_COMPLETED

SERVICES = [
    ('ip-api1', 'http://ip-api.com/json', 'query'),
    ('broken_api', 'http://broken', 'query'),
]

async def get_ip(session, service, url, ip_attr):
    print('fetching ip from: {}'.format(service))
    async with session.get(url) as resp:
        json_resp = await resp.json()
        ip = json_resp[ip_attr]
        return service, ip

async def get_ip_from_services():
    async with aiohttp.ClientSession() as session:
        coro_obj = [get_ip(session, service[0], service[1], service[2])
                    for service in SERVICES]
        try:
            done, pending = await asyncio.wait(coro_obj, return_when=FIRST_COMPLETED)
            result = done.pop().result()
            print(result)
            for future in pending:
                future.cancel()
        except:
            print('catched')

loop = asyncio.get_event_loop()
loop.run_until_complete(get_ip_from_services())
loop.close()

I am able to catch exception when return_when=ALL_COMPLETED but not FIRST_COMPLETED

I got the following errors:

fetching ip from: ip-api1
fetching ip from: broken_api
catched
exception calling callback for <Future at 0x103839240 state=finished returned list>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 297, in _invoke_callbacks
    callback(self)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py", line 419, in _call_set_state
    dest_loop.call_soon_threadsafe(_set_state, destination, source)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 620, in call_soon_threadsafe
    self._check_closed()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Task was destroyed but it is pending!
task: <Task pending coro=<ThreadedResolver.resolve() running at /Volumes/external/venv/lib/python3.6/site-packages/aiohttp/resolver.py:31> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py:408, <TaskWakeupMethWrapper object at 0x103807948>()]> cb=[shield.<locals>._done_callback() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py:679]>
Task was destroyed but it is pending!
task: <Task pending coro=<get_ip() done, defined at ./run_7.py:15> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x1038073d8>()]>>

or warnings

fetching ip from: ip-api1
fetching ip from: broken_api
catched
Task was destroyed but it is pending!
task: <Task pending coro=<ThreadedResolver.resolve() running at /Volumes/external/venv/lib/python3.6/site-packages/aiohttp/resolver.py:31> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/futures.py:408, <TaskWakeupMethWrapper object at 0x1038e2948>()]> cb=[shield.<locals>._done_callback() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py:679]>
Task was destroyed but it is pending!
task: <Task pending coro=<get_ip() done, defined at ./run_7.py:15> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x1038e23d8>()]>>

Body:
I think it's a bug in aiohttp, I posted it there.

Exception you recieve doesn't seem to be critical, so you can leave it as is until it fixed in aiohttp. Or don't cancel requests if you don't want to see it now.

Few unrelated notes to your code:

1) Don't use concurrent.futures with asyncio: these are different modules. Use asyncio.FIRST_COMPLETED.

2) You should not only cancel task but also wait it cancelled (it'll raise CancelledError). It can be done with this code:

for task in pending:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task

Read more about tasks/cancelling here.


问:
How to configure MuleSoft with Maven?
I am trying to create my first MuleSoft application using Maven. I have used CMD to confirm that both Java and Maven are installed. I've also configured my environment variables.

I then open the MuleSoft Anypoint Studio, and create my first named "mulesoft-sample" I select to use Maven, and leave all default settings as they are.

Once I click finish, the Console begins to download a number of files
These continue to be downloaded until after it would seem the near end of the files, it throws an error:

There was an error running the studio:studio goal on project mulesoft-sample

In Console, I see the errors listed below.

I was originally trying to use the latest version of Maven (3.5.0). However, I found a video tutorial that said 3.3.9 was a verified version for MuleSoft. So I thought perhaps the newest version wasn't supported and instead used 3.3.9. However, it is still failing. I've also tried changing the environment variable to other options, such as going straight to \bin, rather than the complete directory (taking shots in the dark here). Unfortunately, nothing has worked and I'm running out of option.

Can anyone tell me why I'm getting these errors, and my build will not succeed? How to correct the error?

答: I have faced same issue and got resolved by changing the JRE to JDK in preferences==>java==>Installed JRE's there change to JDK and restarted the any point studio. This resolved the issue to me.</p>

Title: How to configure MuleSoft with Maven?


问:
Can't use HTTPS with ServerXMLHTTP object
I am supporting a Classic ASP application that connects to a payment gateway via HTTPS. Up until  recently there have been no issues. A few days ago the latest updates were installed on the server (Windows Server 2003) and caused the site to break. A code snippet is below.

```<code>Dim oHttp
Dim strResult
Set oHttp = CreateObject("MSXML2.ServerXMLHTTP")
oHttp.setOption(2) = 13056
oHttp.open "POST", SOAP_ENDPOINT, false
oHttp.setRequestHeader "Content-Type", "application/soap+xml; charset=utf-8"
oHttp.setRequestHeader "SOAPAction", SOAP_NS + "/" & SOAP_FUNCTION
oHttp.send SOAP_REQUEST
</code>```

Below is a dump of the error object :-

Number: -2147012852
Description: A certificate is required to complete client authentication
Message: A certificate is required to complete client authentication

At first I thought it was because the Payment Gateway's SSL certificate was not being authenticated or they needed a client certificate. I tested the URL in a browser on the server and it displayed correctly without errors and confirmed that the Payment Gateway server did not require a client certificate.

I am at a loss. All the research I have done has lead me nowhere. I even tried the following found on Stackoverflow :-

Getting XMLHTTP to work with HTTPS

xmlHttp, XML request,asp

The last one stated that a client certificate is required by XMLHTTP even though the server does not need it and pointed to a KB article on how to install one, but that is outdated and does not work.

答:
Just found the solution to this which has passed testing on:

Windows 10 (IIS 10)

Windows 2012 R2 (IIS 8.5)

It's a client problem. MSXML2.ServerXMLHTTP does indeed require you to use a client certificate when calling an endpoint secured with SSL (even if the endpoint doesn't require it), as the OP noted.

On the webserver, you need to:

Create a client certificate

Assign permissions to the certificate

Set the certificate on the ServerXMLHTTP object

In detail:

1. Create a client certificate

Use the following PowerShell command to create a new self-signed certificate:

```<code>New-SelfSignedCertificate -DnsName "ServerXMLHTTP", "ServerXMLHTTP" -CertStoreLocation "cert:\LocalMachine\My"
</code>```

Note that the certificate created by this command will only be valid for 1 year.

2. Assign permissions to the certificate

Using MMC, view the certificate store for the computer account:
How to: View Certificates with the MMC Snap-in

The certificate created above can be found in Certificates (Local Computer)\Personal\Certificates (the "Issued By" and "Issued To" columns display "ServerXMLHTTP").

Right click the ServerXMLHTTP certificate, select "All Tasks" -> "Manage Private Keys" and the permissions dialog will display.

Add the user that the ASP website app pool is running as. By default it will be running as "ApplicationPoolIdentity", but your setup may be using a specific user account. If the app pool is using ApplicationPoolIdentity, the username to add is "IIS AppPool\APP POOL NAME", e.g. IIS AppPool\DefaultAppPool

The user will be added with "Full Control" which can be deselected. Only "Read" permission seems to be required. Click "OK" to confirm the permissions.

3. Set the certificate on the ServerXMLHTTP object

In your ASP code, set the ServerXMLHTTP object to use the certificate created above. For example calling PayPal for an access token:

```<code>Dim strAuthToken: strAuthToken = "<Base64 encoded version of ClientId:Secret>"
Dim oHttp: Set oHttp = Server.CreateObject("MSXML2.ServerXMLHTTP")

With oHttp
    Call .Open("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", False)
    Call .SetOption(3, "LOCAL_MACHINE\My\ServerXMLHTTP")
    Call .SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    Call .SetRequestHeader("Authorization", "Basic " & strAuthToken)
    Call .Send("grant_type=client_credentials")
End With
</code>```

Hopefully this is still of assistance.

Body:
I am supporting a Classic ASP application that connects to a payment gateway via HTTPS. Up until  recently there have been no issues. A few days ago the latest updates were installed on the server (Windows Server 2003) and caused the site to break. A code snippet is below.

Dim oHttp
Dim strResult
Set oHttp = CreateObject("MSXML2.ServerXMLHTTP")
oHttp.setOption(2) = 13056
oHttp.open "POST", SOAP_ENDPOINT, false
oHttp.setRequestHeader "Content-Type", "application/soap+xml; charset=utf-8"
oHttp.setRequestHeader "SOAPAction", SOAP_NS + "/" & SOAP_FUNCTION
oHttp.send SOAP_REQUEST

Below is a dump of the error object :-

Number: -2147012852
Description: A certificate is required to complete client authentication
Message: A certificate is required to complete client authentication

At first I thought it was because the Payment Gateway's SSL certificate was not being authenticated or they needed a client certificate. I tested the URL in a browser on the server and it displayed correctly without errors and confirmed that the Payment Gateway server did not require a client certificate.

I am at a loss. All the research I have done has lead me nowhere. I even tried the following found on Stackoverflow :-

Getting XMLHTTP to work with HTTPS

xmlHttp, XML request,asp

The last one stated that a client certificate is required by XMLHTTP even though the server does not need it and pointed to a KB article on how to install one, but that is outdated and does not work.

Body:
Just found the solution to this which has passed testing on:

Windows 10 (IIS 10)

Windows 2012 R2 (IIS 8.5)

It's a client problem. MSXML2.ServerXMLHTTP does indeed require you to use a client certificate when calling an endpoint secured with SSL (even if the endpoint doesn't require it), as the OP noted.

On the webserver, you need to:

Create a client certificate

Assign permissions to the certificate

Set the certificate on the ServerXMLHTTP object

In detail:

1. Create a client certificate

Use the following PowerShell command to create a new self-signed certificate:

New-SelfSignedCertificate -DnsName "ServerXMLHTTP", "ServerXMLHTTP" -CertStoreLocation "cert:\LocalMachine\My"

Note that the certificate created by this command will only be valid for 1 year.

2. Assign permissions to the certificate

Using MMC, view the certificate store for the computer account:
How to: View Certificates with the MMC Snap-in

The certificate created above can be found in Certificates (Local Computer)\Personal\Certificates (the "Issued By" and "Issued To" columns display "ServerXMLHTTP").

Right click the ServerXMLHTTP certificate, select "All Tasks" -> "Manage Private Keys" and the permissions dialog will display.

Add the user that the ASP website app pool is running as. By default it will be running as "ApplicationPoolIdentity", but your setup may be using a specific user account. If the app pool is using ApplicationPoolIdentity, the username to add is "IIS AppPool\APP POOL NAME", e.g. IIS AppPool\DefaultAppPool

The user will be added with "Full Control" which can be deselected. Only "Read" permission seems to be required. Click "OK" to confirm the permissions.

3. Set the certificate on the ServerXMLHTTP object

In your ASP code, set the ServerXMLHTTP object to use the certificate created above. For example calling PayPal for an access token:

Dim strAuthToken: strAuthToken = "<Base64 encoded version of ClientId:Secret>"
Dim oHttp: Set oHttp = Server.CreateObject("MSXML2.ServerXMLHTTP")

With oHttp
    Call .Open("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", False)
    Call .SetOption(3, "LOCAL_MACHINE\My\ServerXMLHTTP")
    Call .SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    Call .SetRequestHeader("Authorization", "Basic " & strAuthToken)
    Call .Send("grant_type=client_credentials")
End With

Hopefully this is still of assistance.


问:
Android Toast equivalent in iOS
Does anyone know what the Java Toast equivalent of this iOS Objective C event would be in a Fragment?
Below is a sample of what I have written in iOS. What I am looking for the same Alert in Java using a Toast in place of the iOS UIAlert.  I am sorry if I did not make that clear on my original post.</p>

```<code>- (void) dateLogic {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM dd"];
    NSString *theDate = [dateFormat stringFromDate:[NSDate date]];

    //JANUARY
    if ([theDate isEqualToString:@"January 01"]) {

        feastDay = [[UIAlertView alloc]
                     initWithTitle:@"New Years Day!"
                     message:@"January 01"
                     delegate:self
                     cancelButtonTitle:nil
                     otherButtonTitles:@"Close", nil];
        feastDay.delegate = self;
        [feastDay show];
    }
}
</code>```

答:
Daniele D has an elegant solution, but UIAlertView is deprecated. Use UIAlertController instead:</p>

```<code>    NSString *message = @"Toast message.";

    UIAlertController *toast =[UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:toast animated:YES completion:nil];

    int duration = 2; // in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [toast dismissViewControllerAnimated:YES completion:nil];
    });
</code>```

Title: Android Toast equivalent in iOS

Body:
Does anyone know what the Java Toast equivalent of this iOS Objective C event would be in a Fragment?
Below is a sample of what I have written in iOS. What I am looking for the same Alert in Java using a Toast in place of the iOS UIAlert.  I am sorry if I did not make that clear on my original post.

- (void) dateLogic {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM dd"];
    NSString *theDate = [dateFormat stringFromDate:[NSDate date]];

    //JANUARY
    if ([theDate isEqualToString:@"January 01"]) {

        feastDay = [[UIAlertView alloc]
                     initWithTitle:@"New Years Day!"
                     message:@"January 01"
                     delegate:self
                     cancelButtonTitle:nil
                     otherButtonTitles:@"Close", nil];
        feastDay.delegate = self;
        [feastDay show];
    }
}

Body:
Daniele D has an elegant solution, but UIAlertView is deprecated. Use UIAlertController instead:

    NSString *message = @"Toast message.";

    UIAlertController *toast =[UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:toast animated:YES completion:nil];

    int duration = 2; // in seconds

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [toast dismissViewControllerAnimated:YES completion:nil];
    });


问:
Swift - Mailgun - not receiving emails
I have below code which uses Mailgun to send out emails, I get response code 200 which supposedly means the email was sent successfully, however I am not receiving any emails, my Mailgun account doesn't show anything either.

Below is my code:

```<code>func email() {
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandboxBLAHBLAH.mailgun.org")! as URL)

    request.httpMethod = "POST"
    let credentials = "api:key-BLAHBLAH"
    request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")

    let data = "from:Test<(postmaster@BLAHBLAH.mailgun.org)>&to:[BLAH@gmail.com,(BLAH@gmail.com)]&subject:Hello&text:Testing_email"

    request.httpBody = data.data(using: String.Encoding.ascii)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}
</code>```

答:
I got it working by making some tweaks to the data variable, below is working code for me:

func email(){
        let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandbox{REPLACE WITH YOURS}.mailgun.org/messages")! as URL)
         request.httpMethod = "POST"

```<code>     // Basic Authentication
     let username = "api"
     let password = "key-{REPLACE WITH YOURS}"
     let loginString = NSString(format: "%@:%@", username, password)
     let loginData: NSData = loginString.data(using: String.Encoding.utf8.rawValue)! as NSData
     let base64LoginString = loginData.base64EncodedString(options: [])
     request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

     let bodyStr = "from=Mailgun Sandbox <postmaster@sandbox{REPLACE WITH YOURS}.mailgun.org>&to=Receiver name <SOMEEMAIL@SOMEMEAIL.com>&subject=Test&text=thank you!"

     // appending the data
     request.httpBody = bodyStr.data(using: String.Encoding.utf8);

     let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
     // ... do other stuff here
     })

     task.resume()
}
</code>```

Title: Swift - Mailgun - not receiving emails

Body:
I have below code which uses Mailgun to send out emails, I get response code 200 which supposedly means the email was sent successfully, however I am not receiving any emails, my Mailgun account doesn't show anything either.

Below is my code:

func email() {
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandboxBLAHBLAH.mailgun.org")! as URL)

    request.httpMethod = "POST"
    let credentials = "api:key-BLAHBLAH"
    request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")

    let data = "from:Test<(postmaster@BLAHBLAH.mailgun.org)>&to:[BLAH@gmail.com,(BLAH@gmail.com)]&subject:Hello&text:Testing_email"

    request.httpBody = data.data(using: String.Encoding.ascii)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}

Body:
I got it working by making some tweaks to the data variable, below is working code for me:

func email(){
        let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandbox{REPLACE WITH YOURS}.mailgun.org/messages")! as URL)
         request.httpMethod = "POST"

     // Basic Authentication
     let username = "api"
     let password = "key-{REPLACE WITH YOURS}"
     let loginString = NSString(format: "%@:%@", username, password)
     let loginData: NSData = loginString.data(using: String.Encoding.utf8.rawValue)! as NSData
     let base64LoginString = loginData.base64EncodedString(options: [])
     request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

     let bodyStr = "from=Mailgun Sandbox <postmaster@sandbox{REPLACE WITH YOURS}.mailgun.org>&to=Receiver name <SOMEEMAIL@SOMEMEAIL.com>&subject=Test&text=thank you!"

     // appending the data
     request.httpBody = bodyStr.data(using: String.Encoding.utf8);

     let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
     // ... do other stuff here
     })

     task.resume()
}


问:
Java server to handle multi-clients simultaneously
I am new to java server and client. I want to make a multi-client server. After making server code ready to accept more than one client it is like this :

Server code :

```<code>public class Server {

int clientNumber = 1;
ServerSocket mServer = new ServerSocket(9090);
try {
    while (true) {
        new TheServer(mServer.accept(), clientNumber++).start();
    }
} finally {
    mServer.close();
}
}

private static class TheServer extends Thread {
private Socket client;
private int clientNumber;

public TheServer(Socket client, int clientNumber) {
    this.client = client;
    this.clientNumber = clientNumber;
}

public void run() {

        try {
                DataOutputStream dos = new DataOutputStream(client.getOutputStream());
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(System.in));

                dos.writeUTF(numberString);

                while (true) {
                String message = br.readLine();
                dos.writeUTF(message);
            }

        } catch (IOException e) { }
}
</code>```

}

The clients are added to the server as I expect.

If I have one client, the --- dos.writeUTF(message); --- give the desired result inside client console, so in server console I write down (A) and press enter, then the (A) is printed inside #1 Client, then I write down (B) in server console and press enter, then the (B) is printed inside #1 Client, it seems good.

But if the second client join the server, the result inside both clients console is hold for one time press and is fired on second enter press. To simplify : Inside server console I press (A) and press enter, nothing is happening on clients consoles, then I press (B) inside server console again, and now the first message (A) and second message (B) are printed one (A) inside #1 Client and one (B) inside #2 Client and this is not the behavior that I expect.

What I expect: When 2 Clients exist and server send message (A), I need all Clients (here there are 2 clients) get the message together. Imagine you are playing a game online, If I have a character (like a ball) and I move it inside a game field, all the other players have to see my character moving. I wish I was clear.

I think I have to make an array to keep the clients and send message to that array maybe...

So how can I solve it. If the client code is needed please tell me.

答:
Look into something called the Publish-Subscribe pattern, also known as the Observer pattern, here is an example:

https://www.journaldev.com/1739/observer-design-pattern-in-java

Body:
I am new to java server and client. I want to make a multi-client server. After making server code ready to accept more than one client it is like this :

Server code :

public class Server {

int clientNumber = 1;
ServerSocket mServer = new ServerSocket(9090);
try {
    while (true) {
        new TheServer(mServer.accept(), clientNumber++).start();
    }
} finally {
    mServer.close();
}
}

private static class TheServer extends Thread {
private Socket client;
private int clientNumber;

public TheServer(Socket client, int clientNumber) {
    this.client = client;
    this.clientNumber = clientNumber;
}

public void run() {

        try {
                DataOutputStream dos = new DataOutputStream(client.getOutputStream());
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(System.in));

                dos.writeUTF(numberString);

                while (true) {
                String message = br.readLine();
                dos.writeUTF(message);
            }

        } catch (IOException e) { }
}

}

The clients are added to the server as I expect.

If I have one client, the --- dos.writeUTF(message); --- give the desired result inside client console, so in server console I write down (A) and press enter, then the (A) is printed inside #1 Client, then I write down (B) in server console and press enter, then the (B) is printed inside #1 Client, it seems good.

But if the second client join the server, the result inside both clients console is hold for one time press and is fired on second enter press. To simplify : Inside server console I press (A) and press enter, nothing is happening on clients consoles, then I press (B) inside server console again, and now the first message (A) and second message (B) are printed one (A) inside #1 Client and one (B) inside #2 Client and this is not the behavior that I expect.

What I expect: When 2 Clients exist and server send message (A), I need all Clients (here there are 2 clients) get the message together. Imagine you are playing a game online, If I have a character (like a ball) and I move it inside a game field, all the other players have to see my character moving. I wish I was clear.

I think I have to make an array to keep the clients and send message to that array maybe...

So how can I solve it. If the client code is needed please tell me.


问:
EditText not displaying value on adapter call and EditText loses value when listView is Scrolled.
My 1st problem is that in my Activity I'm passing an Amount in my Adapter to use it to set the Edit Text value inside my adapter but it's not showing.
My 2nd problem is that when I change the value of my Edit Text inside my adapter, the value loses when I scroll the List View.

Here my code in adapter:

```<code>public class CustomListView_InvoiceList extends BaseAdapter {

private Context mContext;
private List<InvoiceList> invoiceLists;
private float TotalPaymentAmount;

public CustomListView_InvoiceList(Context mContext, List<InvoiceList> invoiceLists, Float totalPaymentAmount) {
    this.mContext = mContext;
    this.invoiceLists = invoiceLists;
    this.TotalPaymentAmount = totalPaymentAmount;
}

public static class ViewHolder {
    CheckBox SelectInvoiceCB, PayFull, PayPartial;
    TextView SalesInvoiceNo, InvoiceDate, InvoiceAmount, AmountDue, DueDate, CreditMemoID, CreditMemoDate, CreditMemoReason;
    LinearLayout LL2, LL3;
    EditText TotalAmount;
    ImageView CaptureForm;
}

@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
    //View v = View.inflate(mContext, R.layout.sales_invoice_custom,null);
    final ViewHolder holder;

    if (view == null) {
        view = View.inflate(mContext, R.layout.sales_invoice_custom, null);
        holder = new ViewHolder();

        holder.SelectInvoiceCB = (CheckBox) view.findViewById(R.id.selectInvoiceCB);
        holder.SalesInvoiceNo = (TextView) view.findViewById(R.id.SINo);
        holder.InvoiceDate = (TextView) view.findViewById(R.id.SIDate);
        holder.InvoiceAmount = (TextView) view.findViewById(R.id.SIAmount);
        holder.AmountDue = (TextView) view.findViewById(R.id.SIAmountDue);
        holder.DueDate = (TextView) view.findViewById(R.id.SIdueDate);
        holder.PayFull = (CheckBox) view.findViewById(R.id.SIFull);
        holder.PayPartial = (CheckBox) view.findViewById(R.id.SIPartial);
        holder.TotalAmount = (EditText) view.findViewById(R.id.SITotalAmount);
        holder.CreditMemoID = (TextView) view.findViewById(R.id.creditMemoID);
        holder.CreditMemoDate = (TextView) view.findViewById(R.id.creditMemoDate);
        holder.CreditMemoReason = (TextView) view.findViewById(R.id.creditMemoReason);
        holder.LL2 = (LinearLayout) view.findViewById(R.id.ll2);
        holder.LL3 = (LinearLayout) view.findViewById(R.id.ll3);

        holder.SelectInvoiceCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setSelectInvoice(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
            }
        });

        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayFull(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayPartial(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                }
            }
        });

        view.setTag(holder);
        view.setTag(R.id.SITotalAmount, holder.TotalAmount);
        view.setTag(R.id.selectInvoiceCB, holder.SelectInvoiceCB);
        view.setTag(R.id.SIFull, holder.PayFull);
        view.setTag(R.id.SIPartial, holder.PayPartial);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    InvoicePopulate(view,holder, position);

    return view;
}

public void InvoicePopulate(final View view, final ViewHolder holder, final int position) {
    dbHelper = new DBHelper(mContext);

    Calendar c = Calendar.getInstance();
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    final String formattedDate = df1.format(c.getTime());

    try {
        dbHelper.openDataBase();

        // LAYOUT VISIBILITY FOR CREDIT MEMOs
        try {
            if (invoiceLists.get(position).getCredit_Memo_ID().equals(null) || invoiceLists.get(position).getCredit_Memo_ID().isEmpty()
                    || invoiceLists.get(position).getCredit_Memo_ID().length() < 1
                    || invoiceLists.get(position).getCredit_Memo_ID().trim().equals("")){
                holder.CreditMemoID.setVisibility(View.GONE);
                holder.CreditMemoDate.setVisibility(View.GONE);
                holder.CreditMemoReason.setVisibility(View.GONE);
                holder.LL2.setVisibility(View.GONE);
                holder.LL3.setVisibility(View.GONE);
            } else {
                holder.LL2.setVisibility(View.VISIBLE);
                holder.LL3.setVisibility(View.VISIBLE);
                holder.CreditMemoID.setVisibility(View.VISIBLE);
                holder.CreditMemoDate.setVisibility(View.VISIBLE);
                holder.CreditMemoReason.setVisibility(View.VISIBLE);

                holder.CreditMemoID.setText(invoiceLists.get(position).getCredit_Memo_ID());
                holder.CreditMemoDate.setText(invoiceLists.get(position).getCredit_Memo_Date().substring(0,10));
                holder.CreditMemoReason.setText(invoiceLists.get(position).getCredit_Memo_Reason());
            }
        } catch (Exception e) {
            e.getMessage();
        }

        holder.SalesInvoiceNo.setText(invoiceLists.get(position).getSales_Invoice_ID());
        holder.InvoiceDate.setText(invoiceLists.get(position).getInvoice_Date());
        holder.DueDate.setText(invoiceLists.get(position).getDue_Date());

        float invAmount = 0;
        invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
        holder.InvoiceAmount.setText(String.format("%,.2f",invAmount));
        holder.AmountDue.setText(String.format("%,.2f",invAmount));
        //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());

        holder.TotalAmount.setTag(position);
        holder.SelectInvoiceCB.setTag(position); // This line is important.
        holder.PayFull.setTag(position); // This line is important.
        holder.PayPartial.setTag(position); // This line is important.

        holder.TotalAmount.setText(invoiceLists.get(position).getAmount_Paid());
        holder.SelectInvoiceCB.setChecked(invoiceLists.get(position).isSelectInvoice());
        holder.PayFull.setChecked(invoiceLists.get(position).isPayFull());
        holder.PayPartial.setChecked(invoiceLists.get(position).isPayPartial());

        try {
            if (invoiceLists.get(position).getAmount_Paid().toString().equals("") ||
                    invoiceLists.get(position).getAmount_Paid().toString().equals("0.0") ||
                    Float.parseFloat(invoiceLists.get(position).getAmount_Paid().toString()) < 1) {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = 0;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("Without AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            } else {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = Math.round(Float.parseFloat(invoiceLists.get(position).getAmount_Paid())*100.00)/(float)100.00;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("With AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            }

            holder.AmountDue.setText(String.format("%,.2f",invAmountDue));
            //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());
        } catch (Exception e) {
            e.getMessage();
        }

        /*final float finalInvAmount = invAmountDue;
        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_FULL";
                        holder.TotalAmount.setText(String.valueOf(Math.round(finalInvAmount*100.00)/100.00));
                        //holder.TotalAmount.setText(holder.InvoiceAmount.getText().toString());
                    }
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_PARTIAL";
                        holder.TotalAmount.setText("0.00");
                    }
                }
            }
        });*/

        if (TotalPaymentAmount >= Float.parseFloat(String.valueOf(invAmountDue))) {
            holder.SelectInvoiceCB.setChecked(true);
            holder.PayFull.setChecked(true);
            holder.PayFull.setClickable(true);
            holder.PayPartial.setClickable(true);

            holder.TotalAmount.setText(String.valueOf(Math.round(invAmountDue * 100.00) / 100.00));

            System.out.println("TotalPaymentAmount: " + TotalPaymentAmount);
            System.out.println("invAmountDue: " + invAmountDue);

            if (Float.parseFloat(String.valueOf(invAmountDue)) < 1) {
                Log.e("Computations : ", TotalPaymentAmount + " + " + String.valueOf(Float.parseFloat(String.valueOf(invAmountDue))));
                Log.e("Equals ", "TotalPaymentAmount = " + TotalPaymentAmount);
            } else {
                TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
            }
        } else {
            if (TotalPaymentAmount < 1) {
                holder.TotalAmount.setText("0.00");
                /*holder.PayFull.setClickable(false);
                holder.PayPartial.setClickable(false);*/

            } else {
                holder.SelectInvoiceCB.setChecked(true);
                holder.PayPartial.setChecked(true);
                holder.PayFull.setClickable(true);
                holder.PayPartial.setClickable(true);
                holder.TotalAmount.setText(String.valueOf(Math.round(TotalPaymentAmount * 100.00) / 100.00));

                if ((TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue))) < 0) {
                    TotalPaymentAmount = (float) 0.0;
                } else {
                    TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
                }
            }
        }

    } catch (Exception e) {
        e.getMessage();
        System.out.println("Custom Invoice List: " + e);
    } finally {
        dbHelper.close();
    }

}
</code>```

答:
First, I recommend using RecyclerView instead of ListView, a simple implementation will avoid the problem of scrolling.
I recommend these links:

https://developer.android.com/training/material/lists-cards.html
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

Second, the method invoicePopulate * opens the SQLite database every time a view is created, this gives a serious performance problem because with the scroll the views are recreated and you generate multiple instances in the end you will end up with an error and you will not be able to access to the database. For this I recommend that you calculate the data previously and pass it to the adapter already ready.

It is best to use the adapters to only show information, if you need to calculate try to do it before.

Body:
My 1st problem is that in my Activity I'm passing an Amount in my Adapter to use it to set the Edit Text value inside my adapter but it's not showing.
My 2nd problem is that when I change the value of my Edit Text inside my adapter, the value loses when I scroll the List View.

Here my code in adapter:

public class CustomListView_InvoiceList extends BaseAdapter {

private Context mContext;
private List<InvoiceList> invoiceLists;
private float TotalPaymentAmount;

public CustomListView_InvoiceList(Context mContext, List<InvoiceList> invoiceLists, Float totalPaymentAmount) {
    this.mContext = mContext;
    this.invoiceLists = invoiceLists;
    this.TotalPaymentAmount = totalPaymentAmount;
}

public static class ViewHolder {
    CheckBox SelectInvoiceCB, PayFull, PayPartial;
    TextView SalesInvoiceNo, InvoiceDate, InvoiceAmount, AmountDue, DueDate, CreditMemoID, CreditMemoDate, CreditMemoReason;
    LinearLayout LL2, LL3;
    EditText TotalAmount;
    ImageView CaptureForm;
}

@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
    //View v = View.inflate(mContext, R.layout.sales_invoice_custom,null);
    final ViewHolder holder;

    if (view == null) {
        view = View.inflate(mContext, R.layout.sales_invoice_custom, null);
        holder = new ViewHolder();

        holder.SelectInvoiceCB = (CheckBox) view.findViewById(R.id.selectInvoiceCB);
        holder.SalesInvoiceNo = (TextView) view.findViewById(R.id.SINo);
        holder.InvoiceDate = (TextView) view.findViewById(R.id.SIDate);
        holder.InvoiceAmount = (TextView) view.findViewById(R.id.SIAmount);
        holder.AmountDue = (TextView) view.findViewById(R.id.SIAmountDue);
        holder.DueDate = (TextView) view.findViewById(R.id.SIdueDate);
        holder.PayFull = (CheckBox) view.findViewById(R.id.SIFull);
        holder.PayPartial = (CheckBox) view.findViewById(R.id.SIPartial);
        holder.TotalAmount = (EditText) view.findViewById(R.id.SITotalAmount);
        holder.CreditMemoID = (TextView) view.findViewById(R.id.creditMemoID);
        holder.CreditMemoDate = (TextView) view.findViewById(R.id.creditMemoDate);
        holder.CreditMemoReason = (TextView) view.findViewById(R.id.creditMemoReason);
        holder.LL2 = (LinearLayout) view.findViewById(R.id.ll2);
        holder.LL3 = (LinearLayout) view.findViewById(R.id.ll3);

        holder.SelectInvoiceCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setSelectInvoice(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
            }
        });

        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayFull(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayPartial(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                }
            }
        });

        view.setTag(holder);
        view.setTag(R.id.SITotalAmount, holder.TotalAmount);
        view.setTag(R.id.selectInvoiceCB, holder.SelectInvoiceCB);
        view.setTag(R.id.SIFull, holder.PayFull);
        view.setTag(R.id.SIPartial, holder.PayPartial);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    InvoicePopulate(view,holder, position);

    return view;
}

public void InvoicePopulate(final View view, final ViewHolder holder, final int position) {
    dbHelper = new DBHelper(mContext);

    Calendar c = Calendar.getInstance();
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    final String formattedDate = df1.format(c.getTime());

    try {
        dbHelper.openDataBase();

        // LAYOUT VISIBILITY FOR CREDIT MEMOs
        try {
            if (invoiceLists.get(position).getCredit_Memo_ID().equals(null) || invoiceLists.get(position).getCredit_Memo_ID().isEmpty()
                    || invoiceLists.get(position).getCredit_Memo_ID().length() < 1
                    || invoiceLists.get(position).getCredit_Memo_ID().trim().equals("")){
                holder.CreditMemoID.setVisibility(View.GONE);
                holder.CreditMemoDate.setVisibility(View.GONE);
                holder.CreditMemoReason.setVisibility(View.GONE);
                holder.LL2.setVisibility(View.GONE);
                holder.LL3.setVisibility(View.GONE);
            } else {
                holder.LL2.setVisibility(View.VISIBLE);
                holder.LL3.setVisibility(View.VISIBLE);
                holder.CreditMemoID.setVisibility(View.VISIBLE);
                holder.CreditMemoDate.setVisibility(View.VISIBLE);
                holder.CreditMemoReason.setVisibility(View.VISIBLE);

                holder.CreditMemoID.setText(invoiceLists.get(position).getCredit_Memo_ID());
                holder.CreditMemoDate.setText(invoiceLists.get(position).getCredit_Memo_Date().substring(0,10));
                holder.CreditMemoReason.setText(invoiceLists.get(position).getCredit_Memo_Reason());
            }
        } catch (Exception e) {
            e.getMessage();
        }

        holder.SalesInvoiceNo.setText(invoiceLists.get(position).getSales_Invoice_ID());
        holder.InvoiceDate.setText(invoiceLists.get(position).getInvoice_Date());
        holder.DueDate.setText(invoiceLists.get(position).getDue_Date());

        float invAmount = 0;
        invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
        holder.InvoiceAmount.setText(String.format("%,.2f",invAmount));
        holder.AmountDue.setText(String.format("%,.2f",invAmount));
        //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());

        holder.TotalAmount.setTag(position);
        holder.SelectInvoiceCB.setTag(position); // This line is important.
        holder.PayFull.setTag(position); // This line is important.
        holder.PayPartial.setTag(position); // This line is important.

        holder.TotalAmount.setText(invoiceLists.get(position).getAmount_Paid());
        holder.SelectInvoiceCB.setChecked(invoiceLists.get(position).isSelectInvoice());
        holder.PayFull.setChecked(invoiceLists.get(position).isPayFull());
        holder.PayPartial.setChecked(invoiceLists.get(position).isPayPartial());

        try {
            if (invoiceLists.get(position).getAmount_Paid().toString().equals("") ||
                    invoiceLists.get(position).getAmount_Paid().toString().equals("0.0") ||
                    Float.parseFloat(invoiceLists.get(position).getAmount_Paid().toString()) < 1) {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = 0;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("Without AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            } else {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = Math.round(Float.parseFloat(invoiceLists.get(position).getAmount_Paid())*100.00)/(float)100.00;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("With AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            }

            holder.AmountDue.setText(String.format("%,.2f",invAmountDue));
            //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());
        } catch (Exception e) {
            e.getMessage();
        }

        /*final float finalInvAmount = invAmountDue;
        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_FULL";
                        holder.TotalAmount.setText(String.valueOf(Math.round(finalInvAmount*100.00)/100.00));
                        //holder.TotalAmount.setText(holder.InvoiceAmount.getText().toString());
                    }
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_PARTIAL";
                        holder.TotalAmount.setText("0.00");
                    }
                }
            }
        });*/

        if (TotalPaymentAmount >= Float.parseFloat(String.valueOf(invAmountDue))) {
            holder.SelectInvoiceCB.setChecked(true);
            holder.PayFull.setChecked(true);
            holder.PayFull.setClickable(true);
            holder.PayPartial.setClickable(true);

            holder.TotalAmount.setText(String.valueOf(Math.round(invAmountDue * 100.00) / 100.00));

            System.out.println("TotalPaymentAmount: " + TotalPaymentAmount);
            System.out.println("invAmountDue: " + invAmountDue);

            if (Float.parseFloat(String.valueOf(invAmountDue)) < 1) {
                Log.e("Computations : ", TotalPaymentAmount + " + " + String.valueOf(Float.parseFloat(String.valueOf(invAmountDue))));
                Log.e("Equals ", "TotalPaymentAmount = " + TotalPaymentAmount);
            } else {
                TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
            }
        } else {
            if (TotalPaymentAmount < 1) {
                holder.TotalAmount.setText("0.00");
                /*holder.PayFull.setClickable(false);
                holder.PayPartial.setClickable(false);*/

            } else {
                holder.SelectInvoiceCB.setChecked(true);
                holder.PayPartial.setChecked(true);
                holder.PayFull.setClickable(true);
                holder.PayPartial.setClickable(true);
                holder.TotalAmount.setText(String.valueOf(Math.round(TotalPaymentAmount * 100.00) / 100.00));

                if ((TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue))) < 0) {
                    TotalPaymentAmount = (float) 0.0;
                } else {
                    TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
                }
            }
        }

    } catch (Exception e) {
        e.getMessage();
        System.out.println("Custom Invoice List: " + e);
    } finally {
        dbHelper.close();
    }

}


问:
Can't export data from SQLite database from my Database from another activity
I am trying to export data from one activity to a 'csv' file from my Database class (DBHelper.java) but getting the following error:

```<code>no such table: SQLiteExample.db (Sqlite code 1): , while compiling: SELECT * FROM SQLiteExample.db, (OS error - 2:No such file or directory)
                                                                               android.database.sqlite.SQLiteException: no such table: SQLiteExample.db (Sqlite code 1): , while compiling: SELECT * FROM SQLiteExample.db, (OS error - 2:No such file or directory)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
</code>```

This is my code from my reporting activity (ExportJobCard.java)

```<code> public void exportDataBaseIntoCSV() {

    DBHelper db = new DBHelper(this);
    File exportDir = new File(Environment.getExternalStorageDirectory(), "/JOBCARDSDATABASE");

    if (!exportDir.exists()) {
        exportDir.mkdirs();
    }

    File file = new File(exportDir, "csvfilename.csv");

    try {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        SQLiteDatabase sql_db = db.getReadableDatabase();
        Cursor curCSV = sql_db.rawQuery("SELECT * FROM " + DBHelper.DATABASE_NAME, null);
        csvWrite.writeNext(curCSV.getColumnNames());

        while (curCSV.moveToNext()) {
            //Which column you want to export you can add over here...
            String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2)};
            csvWrite.writeNext(arrStr);
        }

        csvWrite.close();
        curCSV.close();
    } catch (Exception sqlEx) {
        Log.e("Error:", sqlEx.getMessage(), sqlEx);
    }
}
</code>```

If I add the above code directly in my JobCard.class where the user inputs the data and hits save it works,  but I would like to have a different activity for the reporting as I have 2 databases which I need to get reports from.

I am not sure what I am doing wrong here, cause if it works from the above mentioned activity the surely it should work if i just do from another activity?

This is my database class (DBHelper.java)

```<code>public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "SQLiteExample.db";
private static final int DATABASE_VERSION = 2;

public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_GENDER = "gender";
public static final String PERSON_COLUMN_AGE = "age";

public DBHelper(Context context) {
    super(context, DATABASE_NAME , null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
    onCreate(db);
}

public boolean insertPerson(String name,
                            String gender,
                            int age) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);

    db.insert(PERSON_TABLE_NAME, null, contentValues);
    return true;
}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}

public boolean updatePerson(Integer id,
                            String name,
                            String gender,
                            int age) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);

    contentValues.put(PERSON_JOBDESCRIPTION, jobdescription);
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deletePerson(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(PERSON_TABLE_NAME,
            PERSON_COLUMN_ID + " = ? ",
            new String[] { Integer.toString(id) });
}

public Cursor getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " +
            PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)});
    return res;
}

public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM " + PERSON_TABLE_NAME, null );
    return res;
}
}
</code>```

Could someone please help me with this issue?

答:
Your problem can be from different issues.i faced it before and i try to help you

When you create a sqlite database you should register it into manifest file if you do that but you face it again uninstall and reinstall your app because you database already created so for next version of your database such as new table,because the database already exist your debugger won't create new one or replace new one on old one so although you edited your database but something that already exist in your phone is old one.
so uninstall and re install your app in order to create new sqlite data base .
if you again faced this problem check your syntax it's definitely your syntax error.
and also i think another problem is here

```<code>"CREATE TABLE " + PERSON_TABLE_NAME +
 "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                  PERSON_COLUMN_GENDER + " TEXT, " +
                     PERSON_COLUMN_AGE + " INTEGER)"
</code>```

replace this instead

```<code>"CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER);"
</code>```

you forgot to add ";"

hope i did help you.

Body:
I am trying to export data from one activity to a 'csv' file from my Database class (DBHelper.java) but getting the following error:

no such table: SQLiteExample.db (Sqlite code 1): , while compiling: SELECT * FROM SQLiteExample.db, (OS error - 2:No such file or directory)
                                                                               android.database.sqlite.SQLiteException: no such table: SQLiteExample.db (Sqlite code 1): , while compiling: SELECT * FROM SQLiteExample.db, (OS error - 2:No such file or directory)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)

This is my code from my reporting activity (ExportJobCard.java)

 public void exportDataBaseIntoCSV() {

    DBHelper db = new DBHelper(this);
    File exportDir = new File(Environment.getExternalStorageDirectory(), "/JOBCARDSDATABASE");

    if (!exportDir.exists()) {
        exportDir.mkdirs();
    }

    File file = new File(exportDir, "csvfilename.csv");

    try {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        SQLiteDatabase sql_db = db.getReadableDatabase();
        Cursor curCSV = sql_db.rawQuery("SELECT * FROM " + DBHelper.DATABASE_NAME, null);
        csvWrite.writeNext(curCSV.getColumnNames());

        while (curCSV.moveToNext()) {
            //Which column you want to export you can add over here...
            String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2)};
            csvWrite.writeNext(arrStr);
        }

        csvWrite.close();
        curCSV.close();
    } catch (Exception sqlEx) {
        Log.e("Error:", sqlEx.getMessage(), sqlEx);
    }
}

If I add the above code directly in my JobCard.class where the user inputs the data and hits save it works,  but I would like to have a different activity for the reporting as I have 2 databases which I need to get reports from.

I am not sure what I am doing wrong here, cause if it works from the above mentioned activity the surely it should work if i just do from another activity?

This is my database class (DBHelper.java)

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "SQLiteExample.db";
private static final int DATABASE_VERSION = 2;

public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_GENDER = "gender";
public static final String PERSON_COLUMN_AGE = "age";

public DBHelper(Context context) {
    super(context, DATABASE_NAME , null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
    onCreate(db);
}

public boolean insertPerson(String name,
                            String gender,
                            int age) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);

    db.insert(PERSON_TABLE_NAME, null, contentValues);
    return true;
}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}

public boolean updatePerson(Integer id,
                            String name,
                            String gender,
                            int age) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);

    contentValues.put(PERSON_JOBDESCRIPTION, jobdescription);
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deletePerson(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(PERSON_TABLE_NAME,
            PERSON_COLUMN_ID + " = ? ",
            new String[] { Integer.toString(id) });
}

public Cursor getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " +
            PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)});
    return res;
}

public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM " + PERSON_TABLE_NAME, null );
    return res;
}
}

Could someone please help me with this issue?

Body:
Your problem can be from different issues.i faced it before and i try to help you

When you create a sqlite database you should register it into manifest file if you do that but you face it again uninstall and reinstall your app because you database already created so for next version of your database such as new table,because the database already exist your debugger won't create new one or replace new one on old one so although you edited your database but something that already exist in your phone is old one.
so uninstall and re install your app in order to create new sqlite data base .
if you again faced this problem check your syntax it's definitely your syntax error.
and also i think another problem is here

"CREATE TABLE " + PERSON_TABLE_NAME +
 "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                  PERSON_COLUMN_GENDER + " TEXT, " +
                     PERSON_COLUMN_AGE + " INTEGER)"

replace this instead

"CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER);"

you forgot to add ";"

hope i did help you.


问:
how to read the data without database name
If possible to read the data from sql without database name only Server name and table name using c#?? </p>

答: No, this is not possible. SQL tables are stored in SQL databases. And you could perfectly fine have two tables with the same name in two different databases on the same server. So with only the table name and the server name you won't know which one of two tables to read.</p>

ContentLicense: CC BY-SA 2.5


问:
How to call one template from child theme while another is in parent?
I want to use this code:

```<code><?php
$post = $wp_query->post;

if ( in_category( 'video' ) ) {
  include( TEMPLATEPATH.'/single-video.php' );
}
else {
  include( TEMPLATEPATH.'/single.php' );
}
?>
</code>```

I put this in single.php in child theme directory, and while its correctly calling single.php from parent directory, it is not calling single-video.php from child theme directory because of the incorection TEMPLATEPATH.'/.

What should I put instead of that to call signle-video.php template from the child theme directory?

答: use the associated function get_template_directory() path to the active child theme. The constant TEMPLATEPATH get the path to the parent theme</p>

Body:
I want to use this code:

<?php
$post = $wp_query->post;

if ( in_category( 'video' ) ) {
  include( TEMPLATEPATH.'/single-video.php' );
}
else {
  include( TEMPLATEPATH.'/single.php' );
}
?>

I put this in single.php in child theme directory, and while its correctly calling single.php from parent directory, it is not calling single-video.php from child theme directory because of the incorection TEMPLATEPATH.'/.

What should I put instead of that to call signle-video.php template from the child theme directory?


问:
Gson: Directly convert String to JsonObject (no POJO)
Can't seem to figure this out.
I'm attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject. Is there a way to go directly from a String to JsonObject?

I've tried the following (Scala syntax):

```<code>val gson = (new GsonBuilder).create

val a: JsonObject = gson.toJsonTree("""{ "a": "A", "b": true }""").getAsJsonObject
val b: JsonObject = gson.fromJson("""{ "a": "A", "b": true }""", classOf[JsonObject])
</code>```

but a fails, the JSON is escaped and parsed as a JsonString only, and
b returns an empty JsonObject.

Any ideas?

答:
Just encountered the same problem.  You can write a trivial custom deserializer for the JsonElement class:

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(
        JsonElement.class,
        new JsonDeserializer<JsonElement>() {
            @Override
            public JsonElement deserialize(JsonElement arg0,
                    Type arg1,
                    JsonDeserializationContext arg2)
                    throws JsonParseException {

                return arg0;
            }
        } );
String str = "{ \"a\": \"A\", \"b\": true }";
Gson gson = gson_builder.create();
JsonElement element = gson.fromJson(str, JsonElement.class);
JsonObject object = element.getAsJsonObject();
</code>```

Body:
Can't seem to figure this out.
I'm attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject. Is there a way to go directly from a String to JsonObject?

I've tried the following (Scala syntax):

val gson = (new GsonBuilder).create

val a: JsonObject = gson.toJsonTree("""{ "a": "A", "b": true }""").getAsJsonObject
val b: JsonObject = gson.fromJson("""{ "a": "A", "b": true }""", classOf[JsonObject])

but a fails, the JSON is escaped and parsed as a JsonString only, and
b returns an empty JsonObject.

Any ideas?

Body:
Just encountered the same problem.  You can write a trivial custom deserializer for the JsonElement class:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(
        JsonElement.class,
        new JsonDeserializer<JsonElement>() {
            @Override
            public JsonElement deserialize(JsonElement arg0,
                    Type arg1,
                    JsonDeserializationContext arg2)
                    throws JsonParseException {

                return arg0;
            }
        } );
String str = "{ \"a\": \"A\", \"b\": true }";
Gson gson = gson_builder.create();
JsonElement element = gson.fromJson(str, JsonElement.class);
JsonObject object = element.getAsJsonObject();


问:
Swift: fatal error: Index out of range
I'm getting an "Index out of range" when populating a UITableView.
I don't know why it gives me error. I have a condition statement on my cell creation function which checks for the count of each array and then adds a custom cell on index 0.

If anyone knows about this problem, please tell me the solution. I've been working on it for days and can't seem to figure this one out.

```<code>var homeArr: [services] = []
var autoArr: [services] = []

Alamofire.request(url_specialist_request_url, method: .post, parameters: parameters).responseJSON {
    response in

    if response.data != nil {
        let json = JSON(data: response.data!)
        let json_count = json.count

        // print(json)

        self.homeArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.autoArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.personalArr.append(services(service_name:"",service_icon:"",service_category:""))

        for i in 0 ..< json_count {
            let categoryId = json[i]["category_id"].string!
            if(categoryId == "1") {
                self.homeArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else if(categoryId == "2") {
                self.autoArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else {
                self.personalArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            }
        }

        self.tableView.reloadData()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell

    let home_dict = self.homeArr[indexPath.row]
    // ** Index out of range on the following line **
    let auto_dict = self.autoArr[indexPath.row]

    if(self.homeArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Home"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = home_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
        }
    }

    if(self.autoArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Personal"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = auto_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
        }
    }

    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return(homeArr.count + arrAuto.count)
}
</code>```

This is what I want to achieve

Home Arr cell

value1

value2

Auto Arr cell

value1

value2

答:
Create two sections One for HomeArr and one for AutoArr. I believe for each section you wanna show a additional cell with some title. So below code should help you.

```<code>extension ViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return (homeArr.count > 0) ?  homeArr.count + 1 : 0
        }
        else {
            return (autoArr.count > 0) ?  autoArr.count + 1 : 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
        if indexPath.section == 0 {
            if (indexPath.row == 0)
            {
                cell.serviceLabel!.text = "Home"
                cell.contentView.backgroundColor = UIColor.blue
            } else {
                let home_dict = self.homeArr[indexPath.row - 1]
                cell.serviceLabel!.text = home_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
            }
        }
        else {
            if (indexPath.row == 0)
            {
                cell.serviceLabel!.text = "Personal"
                cell.contentView.backgroundColor = UIColor.blue
            } else {
                let auto_dict = self.autoArr[indexPath.row - 1]
                cell.serviceLabel!.text = auto_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
            }
        }
        return cell
    }
}
</code>```

EDIT:

As pointed out by rmaddy in comments below

Why the extra row in each section? Why not use a section header
  instead?

As we are not aware of OP's exact requirement I am updating my code to show section title as well.

```<code> extension ViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return homeArr.count
        }
        else {
            return autoArr.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
        if indexPath.section == 0 {
            let home_dict = self.homeArr[indexPath.row]
            cell.serviceLabel!.text = home_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
        }
        else {
            let auto_dict = self.autoArr[indexPath.row]
            cell.serviceLabel!.text = auto_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
        }
        return cell
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "Home Arr cell"
        }
        else {
            return "Auto Arr cell"
        }
    }
}
</code>```

Title: Swift: fatal error: Index out of range

Body:
I'm getting an "Index out of range" when populating a UITableView.
I don't know why it gives me error. I have a condition statement on my cell creation function which checks for the count of each array and then adds a custom cell on index 0.

If anyone knows about this problem, please tell me the solution. I've been working on it for days and can't seem to figure this one out.

var homeArr: [services] = []
var autoArr: [services] = []

Alamofire.request(url_specialist_request_url, method: .post, parameters: parameters).responseJSON {
    response in

    if response.data != nil {
        let json = JSON(data: response.data!)
        let json_count = json.count

        // print(json)

        self.homeArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.autoArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.personalArr.append(services(service_name:"",service_icon:"",service_category:""))

        for i in 0 ..< json_count {
            let categoryId = json[i]["category_id"].string!
            if(categoryId == "1") {
                self.homeArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else if(categoryId == "2") {
                self.autoArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else {
                self.personalArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            }
        }

        self.tableView.reloadData()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell

    let home_dict = self.homeArr[indexPath.row]
    // ** Index out of range on the following line **
    let auto_dict = self.autoArr[indexPath.row]

    if(self.homeArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Home"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = home_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
        }
    }

    if(self.autoArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Personal"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = auto_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
        }
    }

    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return(homeArr.count + arrAuto.count)
}

This is what I want to achieve

Home Arr cell

value1

value2

Auto Arr cell

value1

value2

Body:
Create two sections One for HomeArr and one for AutoArr. I believe for each section you wanna show a additional cell with some title. So below code should help you.

extension ViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return (homeArr.count > 0) ?  homeArr.count + 1 : 0
        }
        else {
            return (autoArr.count > 0) ?  autoArr.count + 1 : 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
        if indexPath.section == 0 {
            if (indexPath.row == 0)
            {
                cell.serviceLabel!.text = "Home"
                cell.contentView.backgroundColor = UIColor.blue
            } else {
                let home_dict = self.homeArr[indexPath.row - 1]
                cell.serviceLabel!.text = home_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
            }
        }
        else {
            if (indexPath.row == 0)
            {
                cell.serviceLabel!.text = "Personal"
                cell.contentView.backgroundColor = UIColor.blue
            } else {
                let auto_dict = self.autoArr[indexPath.row - 1]
                cell.serviceLabel!.text = auto_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
            }
        }
        return cell
    }
}

EDIT:

As pointed out by rmaddy in comments below

Why the extra row in each section? Why not use a section header
  instead?

As we are not aware of OP's exact requirement I am updating my code to show section title as well.

 extension ViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return homeArr.count
        }
        else {
            return autoArr.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
        if indexPath.section == 0 {
            let home_dict = self.homeArr[indexPath.row]
            cell.serviceLabel!.text = home_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
        }
        else {
            let auto_dict = self.autoArr[indexPath.row]
            cell.serviceLabel!.text = auto_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
        }
        return cell
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "Home Arr cell"
        }
        else {
            return "Auto Arr cell"
        }
    }
}


问:
Add domain to all vimeo videos by API
We need to add domains to all of our videos. But I cant find a API call to add a domain to all of the videos - only one video at a time.

Right now I am doing two steps:
https://api.vimeo.com/me/videos....
Here I get all of our videos and their IDs and a hell of lot of stuff I dont need.

Then I loop through all of the videoIDs and call
https://api.vimeo.com/videos/{videoId}/privacy/domains/{newDomain} for each video.

This results in 1200 put requests which is not good. Furthermore I am not sure if we get banned with to many requests.

Is there som APIs that I have missed which supports what I am trying to do ?

Any help is appreciated.

答: Instead of using the API to do this, I suggest setting the default video privacy for all your videos at https://vimeo.com/settings/videos/upload_defaults - this includes the ability to add domain privacy.</p>

Title: Add domain to all vimeo videos by API