Getting INVALID_COUNTRY_CODE exception when trying to parse phone number without country code - libphonenumber

I am using libphonenumber jar (version 7) and trying to parse phone number without setting Region. I saw following code as recommended.
PhoneNumber phoneNumber = phoneUtil.parse(numberStr, ""));
However, this is throwing INVALID_COUNTRY_CODE exception. Did something change in the latest version? How can I get region code (US) for given number like ("+1-xxx-xxx-xxxx")?

I used libphonenumber 7.0.8 and it worked:
public static void main(final String[] args) {
String numberStr = "+1 650-253-0000"; // Google
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
try {
PhoneNumber phoneNumber = phoneUtil.parse(numberStr, null);
System.out.println(geocoder.getDescriptionForNumber(phoneNumber, Locale.ENGLISH));
} catch (NumberParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It worked using:
phoneUtil.parse(numberStr, null);
phoneUtil.parse(numberStr, "");
phoneUtil.parse(numberStr, "ZZ");
Output is always Mountain View, CA - so the number was parsed successfully.
From the javadoc you can find this information:
If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.

Related

Various errors using VisionServiceClient in XamarinForms

I am trying to create a simple Xamarin forms app which allows the user to browse for or take a photo and have azure cognitive services tag the photo using a custom vision model.
I am unable to get the client to successfully authenticate or find a resource per the error message in the exception produced by the VisionServiceClient. Am I missing something? What would be the correct values to use for the arguments to VisionServiceClient?
All keys have been removed from the below images, they are populated.
Exception thrown in VS2017:
'Microsoft.ProjectOxford.Vision.ClientException' in System.Private.CoreLib.dll
Call to VisionServiceClient:
private const string endpoint = #"https://eastus2.api.cognitive.microsoft.com/vision/prediction/v1.0";
private const string key = "";
VisionServiceClient visionClient = new VisionServiceClient(key, endpoint);
VisualFeature[] features = { VisualFeature.Tags, VisualFeature.Categories, VisualFeature.Description };
try
{
AnalysisResult temp = await visionClient.AnalyzeImageAsync(imageStream,
features.ToList(), null);
return temp;
}
catch(Exception ex)
{
return null;
}
VS Exception Error:
Azure Portal for cognitive services:
Custom Vision Portal:
It looks like you're confusing the Computer Vision and the Custom Vision APIs. You are attempting to use the client SDK for the former using the API key of the latter.
For .NET languages, you'll want the Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction NuGet package.
Your code will end up looking something like this:
ICustomVisionPredictionClient client = new CustomVisionPredictionClient()
{
ApiKey = PredictionKey,
Endpoint = "https://southcentralus.api.cognitive.microsoft.com"
};
ImagePrediction prediction = await client.PredictImageAsync(ProjectId, stream, IterationId);
Thank you to cthrash for the extended help and talking with me in chat. Using his post along with a little troubleshooting I have figured out what works for me. The code is super clunky but it was just to test and make sure I'm able to do this. To answer the question:
Nuget packages and classes
Using cthrash's post I was able to get both the training and prediction nuget packages installed, which are the correct packages for this particular application. I needed the following classes:
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models
Endpoint Root
Following some of the steps Here I determined that the endpoint URL's only need to be the root, not the full URL provided in the Custom Vision Portal. For instance,
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/
Was changed to
https://southcentralus.api.cognitive.microsoft.com
I used both the key and endpoint from the Custom Vision Portal and making that change I was able to use both a training and prediction client to pull the projects and iterations.
Getting Project Id
In order to use CustomVisionPredictionClient.PredictImageAsync you need a Guid for the project id and an iteration id if a default iteration is not set in the portal.
I tested two ways to get the project id,
Using project id string from portal
Grab the project id string from the portal under the project settings.
For the first argument to PredictImageAsync pass
Guid.Parse(projectId)
Using the training client
Create a new CustomVisionTrainingClient
To get a list of <Project> use
TrainingClient.GetProjects().ToList()
In my case I only had a single project so I would just need the first element.
Guid projectId = projects[0].Id
Getting Iteration Id
To get the iteration id of a project you need the CustomVisionTrainingClient.
Create the client
To get a list of <Iteration> use
client.GetIterations(projectId).ToList()
In my case I had only a single iteration so I just need the first element.
Guid iterationId = iterations[0].Id
I am now able to use my model to classify images. In the code below, fileStream is the image stream passed to the model.
public async Task<string> Predict(Stream fileStream)
{
string projectId = "";
//string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.2/Training/";
string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/";
string trainingKey = "";
//string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/";
string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
string predictionKey = "";
CustomVisionTrainingClient trainingClient = new CustomVisionTrainingClient
{
ApiKey = trainingKey,
Endpoint = trainingEndpoint
};
List<Project> projects = new List<Project>();
try
{
projects = trainingClient.GetProjects().ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to get projects:\n\n" + ex.Message);
return "Unable to obtain projects.";
}
Guid ProjectId = Guid.Empty;
if(projects.Count > 0)
{
ProjectId = projects[0].Id;
}
if (ProjectId == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project ID");
return "Unable to obtain project id.";
}
List<Iteration> iterations = new List<Iteration>();
try
{
iterations = trainingClient.GetIterations(ProjectId).ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to obtain iterations.");
return "Unable to obtain iterations.";
}
foreach(Iteration itr in iterations)
{
Debug.WriteLine(itr.Name + "\t" + itr.Id + "\n");
}
Guid iteration = Guid.Empty;
if(iterations.Count > 0)
{
iteration = iterations[0].Id;
}
if(iteration == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project iteration.");
return "Unable to obtain project iteration";
}
CustomVisionPredictionClient predictionClient = new CustomVisionPredictionClient
{
ApiKey = predictionKey,
Endpoint = predictionEndpoint
};
var result = await predictionClient.PredictImageAsync(Guid.Parse(projectId), fileStream, iteration);
string resultStr = string.Empty;
foreach(PredictionModel pred in result.Predictions)
{
if(pred.Probability >= 0.85)
resultStr += pred.TagName + " ";
}
return resultStr;
}

ArcGIS version 100.3.0 android token

Below is the code I'm using for setting user credentials on ServiceFeatureTable.
ServiceFeatureTable featureTablePolygons = new ServiceFeatureTable(polygonUrl);
featureTablePolygons.setCredential(UserCredential.createFromToken(gisToken, referer));
//query feature from the table
final ListenableFuture<FeatureQueryResult> queryResultPolygons = featureTablePolygons.queryFeaturesAsync(query);
queryResultPolygons.addDoneListener(() -> {
try {
FeatureCollection featureCollection = new FeatureCollection();
FeatureQueryResult result = queryResultPolygons.get();
FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
featureCollectionTable.setRenderer(new SimpleRenderer(new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.translucent_red), new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 1))));
featureCollection.getTables().add(featureCollectionTable);
FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);
mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
if (result.iterator().hasNext()) {
Feature feature = result.iterator().next();
Envelope envelope = feature.getGeometry().getExtent();
mMapView.setViewpointGeometryAsync(envelope);
} else {
}
} catch (InterruptedException | ExecutionException e) {
Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
}
});
But this is not working. If I'm using AuthenticationManager then it's working fine but I don't want to use username and password in my code.
If you're manually getting the token, you can create a UserCredential object using createFromToken() and set it on the ServiceFeatureTable with setCredential().
However, many workflows for getting a token are handled by the Runtime (e.g. username + password, or OAuth via a Portal). Take a look at the AuthenticationManager documentation to get started.
Lastly, I think you'll get more eyes on your questions over at the ArcGIS Runtime SDK for Android forums.

Xamarin Auth account store

I'm trying to implement Xamairn Auth with my app. I've installed the nuget package from https://www.nuget.org/packages/Xamarin.Auth.
Following their example I have the following code in the shared project.
public void SaveCredentials (string userName, string password)
{
if (!string.IsNullOrWhiteSpace (userName) && !string.IsNullOrWhiteSpace (password)) {
Account account = new Account {
Username = userName
};
account.Properties.Add ("Password", password);
AccountStore.Create ().Save (account, App.AppName);
}
}
When run on android, it saves the username and password but I'm getting the following message in the console:
"This version is insecure, because of default password.
Please use version with supplied password for AccountStore.
AccountStore.Create(Contex, string) or AccountStore.Create(string);"
I tried passing a parameter to the AccountStore.Create() method but it doesn't seem to take one. Something like this:
#if ANDROID
_accountStore = AccountStore.Create(Application.Context);
#else
_accountStore = AccountStore.Create();
#endif
Do I need to write android specific code to extend the create method.
I understand why you deleted the non-answer, I thought that would show interest in the question. I guess I should have upvoted the question instead. Anyways, here's the answer I found.
You can't use the PCL version for android. It doesn't have an option to add a password. I used the android specific version. Will call it using dependency service.
Here's an example:
Account account = null;
try
{
//account = AccountStore.Create(Application.ApplicationContext, "System.Char[]").FindAccountsForService("My APP").FirstOrDefault();
var aStore = AccountStore.Create(Application.ApplicationContext, "myownpassword");
// save test
account = aStore.FindAccountsForService(Constants.AppName).FirstOrDefault();
if (account == null)
account = new Account();
account.Username = "bobbafett";
account.Properties["pswd"] = "haha";
aStore.Save(account, Constants.AppName);
// delete test, doesn't seem to work, account is still found
var accts = aStore.FindAccountsForService(Constants.AppName);
int howMany = accts.ToList().Count;
foreach (var acct in accts)
{
aStore.Delete(acct, Constants.AppName);
}
account = aStore.FindAccountsForService(Constants.AppName).FirstOrDefault();
}
catch (Java.IO.IOException ex)
{
// This part is not invoked anymore once I use the suggested password.
int i1 = 123;
}
I was able to get it to work by implementing a getAccountStore method in android which has an option to add a password, then use DependencyService to call it.
public AccountStore GetAccountStore()
{
try
{
var acctStore = AccountStore.Create(Application.Context, "somePassword");
return acctStore;
}
catch (Java.IO.IOException ex)
{
throw ex;
}
}
Then in your pcl project call it as such:
if (Device.RuntimePlatform == Device.Android)
_accountStore = DependencyService.Get<IAccountStoreHelper>().GetAccountStore();
else
_accountStore = AccountStore.Create();

How do I check whether a mobile device has already been registered

I'm using the Amazon AWS Ruby SDK for Amazon SNS but I'm having some trouble with devices already being registered. Sometimes when a device gets registered again I get an error like AWS::SNS::Errors::InvalidParameter Invalid parameter: Token Reason: Endpoint arn:aws:sns:us-east-1:**** already exists with the same Token, but different attributes.. How do I check whether an endpoint already exists and more importantly, how do I get the endpoint for a given token?
Credit to BvdBijl's idea, I made an extension method to delete the existing one if found and then add it.
using System;
using System.Text.RegularExpressions;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
namespace Amazon.SimpleNotificationService
{
public static class AmazonSimpleNotificationServiceClientExtensions
{
private const string existingEndpointRegexString = "Reason: Endpoint (.+) already exists with the same Token";
private static Regex existingEndpointRegex = new Regex(existingEndpointRegexString);
public static CreatePlatformEndpointResponse CreatePlatformEndpointIdempotent(
this AmazonSimpleNotificationServiceClient client,
CreatePlatformEndpointRequest request)
{
try
{
var result = client.CreatePlatformEndpoint(request);
return result;
}
catch (AmazonSimpleNotificationServiceException e)
{
if (e.ErrorCode == "InvalidParameter")
{
var match = existingEndpointRegex.Match(e.Message);
if (match.Success) {
string arn = match.Groups[1].Value;
client.DeleteEndpoint(new DeleteEndpointRequest
{
EndpointArn = arn,
});
return client.CreatePlatformEndpoint(request);
}
}
throw;
}
}
}
}
It looks like amazone resolved this issue.
I'm using RoR and used to have same problem when trying to register and existing GCM code I got an error message saying
"AWS::SNS::Errors::InvalidParameter Invalid parameter: Token Reason: Endpoint arn:aws:sns:us-east-1:**** already exists with the same Token, but different attributes."
although I used same (empty) attributes. Now when I send an existing GCM code (with same attributes as the original one) I get the endpoint arn and not the error message.
ListEndpointsByPlatformApplication only return 100 endpoints, you have to use nextToken to get more. Here is my implementation.
public void deleteEndpoint(string token, string PlatformApplicationArn)
{
ListEndpointsByPlatformApplicationRequest listRequest = new ListEndpointsByPlatformApplicationRequest();
listRequest.PlatformApplicationArn = PlatformApplicationArn;
Logger.Info("Deleting endpoint with token -> " + token);
var list = snsClient.ListEndpointsByPlatformApplication(listRequest);
do
{
foreach (var x in list.Endpoints.Where(x => x.Attributes["Token"] == token))
{
snsClient.DeleteEndpoint(new DeleteEndpointRequest() { EndpointArn = x.EndpointArn });
Logger.Info("Endpoint removed-> " + x.EndpointArn);
return;
}
listRequest.NextToken = list.NextToken;
list = snsClient.ListEndpointsByPlatformApplication(listRequest);
}
while (list.NextToken != null);
}

How to create SubCommunities using the Social Business Toolkit Java API?

In the SDK Javadoc, the Community class does not have a "setParentCommunity" method but the CommunityList class does have a getSubCommunities method so there must be a programmatic way to set a parent Community's Uuid on new Community creation. The REST API mentions a "rel="http://www.ibm.com/xmlns/prod/sn/parentcommunity" element". While looking for clues I check an existing Subcommunity's XmlDataHandler's nodes and found a link element. I tried getting the XmlDataHandler for a newly-created Community and adding a link node with href, rel and type nodes similar to those in the existing Community but when trying to update or re-save the Community I got a bad request error. Actually even when I tried calling dataHandler.setData(n) where n was set as Node n=dataHandler.getData(); without any changes, then calling updateCommunity or save I got the same error, so it appears that manipulating the dataHandler XML is not valid.
What is the recommended way to specify a parent Community when creating a new Community so that it is created as a SubCommunity ?
The correct way to create a sub-community programatically is to modify the POST request body for community creation - here is the link to the Connections 45 infocenter - http://www-10.lotus.com/ldd/appdevwiki.nsf/xpDocViewer.xsp?lookupName=IBM+Connections+4.5+API+Documentation#action=openDocument&res_title=Creating_subcommunities_programmatically_ic45&content=pdcontent
We do not have support in the SBT SDK to do this using CommunityService APIs. We need to use low level Java APIs using Endpoint and ClientService classes to directly call the REST APIs with the appropriate request body.
I'd go ahead and extend the class CommunityService
then go ahead and add CommunityService
https://github.com/OpenNTF/SocialSDK/blob/master/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/communities/CommunityService.java
Line 605
public String createCommunity(Community community) throws CommunityServiceException {
if (null == community){
throw new CommunityServiceException(null, Messages.NullCommunityObjectException);
}
try {
Object communityPayload;
try {
communityPayload = community.constructCreateRequestBody();
} catch (TransformerException e) {
throw new CommunityServiceException(e, Messages.CreateCommunityPayloadException);
}
String communityPostUrl = resolveCommunityUrl(CommunityEntity.COMMUNITIES.getCommunityEntityType(),CommunityType.MY.getCommunityType());
Response requestData = createData(communityPostUrl, null, communityPayload,ClientService.FORMAT_CONNECTIONS_OUTPUT);
community.clearFieldsMap();
return extractCommunityIdFromHeaders(requestData);
} catch (ClientServicesException e) {
throw new CommunityServiceException(e, Messages.CreateCommunityException);
} catch (IOException e) {
throw new CommunityServiceException(e, Messages.CreateCommunityException);
}
}
You'll want to change your communityPostUrl to match...
https://greenhouse.lotus.com/communities/service/atom/community/subcommunities?communityUuid=2fba29fd-adfa-4d28-98cc-05cab12a7c43
and where the Uuid here is the parent uuid.
I followed #PaulBastide 's recommendation and created a SubCommunityService class, currently only containing a method for creation. It wraps the CommunityService rather than subclassing it, since I found that preferrable. Here's the code in case you want to reuse it:
public class SubCommunityService {
private final CommunityService communityService;
public SubCommunityService(CommunityService communityService) {
this.communityService = communityService;
}
public Community createCommunity(Community community, String superCommunityId) throws ClientServicesException {
Object constructCreateRequestBody = community.constructCreateRequestBody();
ClientService clientService = communityService.getEndpoint().getClientService();
String entityType = CommunityEntity.COMMUNITY.getCommunityEntityType();
Map<String, String> params = new HashMap<>();
params.put("communityUuid", superCommunityId);
String postUrl = communityService.resolveCommunityUrl(entityType,
CommunityType.SUBCOMMUNITIES.getCommunityType(), params);
String newCommunityUrl = (String) clientService.post(postUrl, null, constructCreateRequestBody,
ClientService.FORMAT_CONNECTIONS_OUTPUT);
String communityId = newCommunityUrl.substring(newCommunityUrl.indexOf("communityUuid=")
+ "communityUuid=".length());
community.setCommunityUuid(communityId);
return community;
}
}

Resources