I have a question!
I am using StringTokenizer but I don't understand how i can take 'space' as a token!
this is an example of my method:
import java.util.*;
public class miaProva{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Write phrase");
String s=sc.next();
StringTokenizer st=new StringTokenizer(s, " ,.");
StringBuilder sb=new StringBuilder();
sb.append('>');
while(st.hasMoreTokens()){
sb.append(st.nextToken());
}
sb.append('<');
System.out.println(sb);
}
}
but when it finds 'space' it interrupts the execution of the method.
INPUT:
1) hi,how,are.you
2) hi,how are you
OUTPUT:
1) >hihowareyou<
2) >hihow<
thank you
Have you tried split method in the String class ?
In your sample, when you do sc.next(), it gives you the text separated by space.
So when you type "Hi,how you are" the sc.next() returns only "hi,how"
Its not a problem with StringTokenizer, use sc.nextLine() instead of sc.next(). That should give you the result you are epecting.
The scanner is using white space as its default delimiter. So when you call sc.next(), it only returns the first part of the input before the space. you can tell it to include the whole line like this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\r\n");
where "\r\n" matches newline on a Windows OS.
edit: It is better to use the lineSeparator method, so that is will work on any operating system.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.lineSeparator());
edit 2: Or better still (having read #Sathiesh's answer), use sc.nextLine().
Related
IoT modules can be created from the environment using :
ModuleClient.CreateFromEnvironmentAsync(settings)
However, there does not seem to be an equivalent method for devices. For now, I am setting the device connection string in the program to test it out, but is there a better way to read teh connection string from iotedge/config.yaml for all the edge devices deployed out there?
Methods to do so for .NET and python would be appreciated.
You can use a yaml parse library to deserialize the document, such as YamlDotNet. In fact, you can refer to YamlDocument in iot edge. But in the class, it does not provide a method to get the key value. Please refer to following code.
public class YamlDocument
{
readonly Dictionary<object, object> root;
public YamlDocument(string input)
{
var reader = new StringReader(input);
var deserializer = new Deserializer();
this.root = (Dictionary<object, object>)deserializer.Deserialize(reader);
}
public object GetKeyValue(string key)
{
if(this.root.ContainsKey(key))
{
return this.root[key];
}
foreach(var item in this.root)
{
var subItem = item.Value as Dictionary<object, object>;
if(subItem != null && subItem.ContainsKey(key))
{
return subItem[key];
}
}
return null;
}
}
And then you can get the device connection string from the config.yaml. If you use python, you can import yaml library to analysis the file.
StreamReader sr = new StreamReader(#"C:\ProgramData\iotedge\config.yaml");
var yamlString = sr.ReadToEnd();
var yamlDoc = new YamlDocument(yamlString);
var connectionString = yamlDoc.GetKeyValue("device_connection_string");
Console.WriteLine("{0}", connectionString);
To get the config file from the host, add the following to the docker deployment file. Note that the source file is config1.yaml which is the same as config.yaml except that it has read permissions for everyone not just root.
"createOptions": "{\"HostConfig\":{\"Binds\":[\"/etc/iotedge/config1.yaml:/app/copiedConfig.yaml\"]}}"
With the above line in place, the copiedConfig.yaml file can be used in the container, along with #Michael Xu's parsing code to derive teh connection string.
Long term, one may want to use the device provisioning service anyway but hope this helps for folks using device conenction strings for whatever reason..
I am newbie to HL7. I am trying to construct HL7 message ORU_R01 type using HAPI 2.4. I got incorrect message format when I add patient details in the below code; otherwise the format is ok. How to fix this issue? is there any example to construct HL7 ORU message with PID,ORC,OBR and OBX?
Output without patient
MSH|^~\&|IM|ABC-ClinPath|ABC-vet|ABC-VetMed|20180412124041||ORU^R01
Output with patient (If I comment the patient details in the code)
PID||TEST|||^TESTlinPath|ABC-vet|ABC-VetMed|20180412124041||ORU^R01
import ca.uhn.hl7v2.model.v24.message.ORM_O01;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.group.ORM_O01_PATIENT;
public class CreateORUMessage {
private String sendingApplication = "IM";
private String sendingFacility = "ABC-ClinPath";
private String receivingApplication = "ABC-vet";
private String receivingFacility = "ABC-VetMed";
private void createHL7Message(){
try{
ORM_O01 order = new ORM_O01();
//ORU_R01 oru = new ORU_R01();
// Populate the MSH Segment
// Example - MSH|^~\&|HISA_8592|HISF_2603|||200706081131||ADT^A04|HL7O.1.11379|D|2.1
MSH mshSegment = order.getMSH();
mshSegment.getFieldSeparator().setValue("|");
mshSegment.getEncodingCharacters().setValue("^~\\&");
mshSegment.getSendingApplication().getNamespaceID().setValue(sendingApplication);
mshSegment.getSendingFacility().getNamespaceID().setValue(sendingFacility);
mshSegment.getReceivingApplication().getNamespaceID().setValue(receivingApplication);
mshSegment.getReceivingFacility().getNamespaceID().setValue(receivingFacility);
mshSegment.getDateTimeOfMessage().getTimeOfAnEvent().setValue("20180412124041");
mshSegment.getMessageType().getMessageType().setValue("ORU");
mshSegment.getMessageType().getTriggerEvent().setValue("R01");
//PID - patient details
ORM_O01_PATIENT orm_pid = order.getPATIENT();
orm_pid.getPID().getPid5_PatientName(0).getGivenName().setValue("TEST");
orm_pid.getPID().getPid2_PatientID().getCx1_ID().setValue("TEST");
// Now, let's encode the message and look at the output
HapiContext context = new DefaultHapiContext();
Parser parser = context.getPipeParser();
String encodedMessage = parser.encode(order);
System.out.println("Printing ER7 Encoded Message:");
System.out.println(encodedMessage);
//String msg = order.encode();
//System.out.println(msg);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
new CreateORUMessage().createHL7Message();
}
}
I tried other way too, but it's not worked :(
String msg = order.encode();
System.out.println(msg);
Your problem most likely is, that the segment separator character in HL7 is CR, which just resets the cursor to the start of the line and the next line overwrites the previous one. This only affects writing the message to the console. Writing to file or sending over TCP should be fine without any further conversions.
I had the same problem in an application once, this is my solution below.
ORU_R01 outMessage = new ORU_R01();
outMessage.setParser(hapiContext.getPipeParser());
outMessage.initQuickstart("ORU", "R01", "T");
MSH mshSegment = outMessage.getMSH();
mshSegment.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("MIG-TOOL");
/* some code removed */
PID pidSegment = outMessage.getRESPONSE().getPATIENT().getPID();
pidSegment.getPid3_PatientIDInternalID(0).parse(reportData.getPatientId());
/* some more code removed */
LOGGER.trace("Generated message contents:\n" + replaceNewlines(outMessage.encode()));
And the code for replaceNewLines() is quite simple
private static String replaceNewlines(String input) {
return input.replaceAll("\\r", "\n");
}
I have only one edit text field to accept email or phone number. how to change the input type based on the 1st character ? based on user input i need to perform different operations.. The main thing is i should identify whether that is email or phone number. how to do this?
In your, EditText set a TextWatcher which calls a function to check if the text is email or is a phone number.
Get the text from your TextView like :
String text = textView.getText().toString();
Adding the listener to your TextView :
textView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(....){}
#Override
public void beforeTextChanged(...){}
#Override
public void afterTextChanged(Editable s) {
if(isEmail(text)){//do your stuff}
if(isPhone(text)){//do your stuff}
}
}
Your methods would look something like this:
public static boolean isEmail(String text) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern p = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
return m.matches();
}
public static boolean isPhone(String text) {
if(!TextUtils.isEmpty(text)){
return TextUtils.isDigitsOnly(text);
} else{
return false;
}
}
This might not be possible with just checking the first digit. Though you can put validations inside onTextChanged method.
Novo Lucas's answer is correct.
My Views :
First thing is that you can't know input type using the first letter cause some email addresses begin with numbers.
On button click you can identify type by knowing if the text contains only numbers or alphanumeric characters. For more info about code you can search it on Google. I will try to add code after some time. Good Luck
I'm using SimpleFileVisitor to search for a file. It works fine on Windows and Linux. However when I try using it on Unix like operating systems It doesn't work as expected. I would get errors like this:
java.nio.file.NoSuchFileException:
/File/Location/MyFolder/\u0082\u0096\u0096âĜu0099\u0081\u0097K
\u0097\u0099\u0096\u0097\u0085\u0099Ĝu0089\u0085
It looks like the obtained name is in different character encoding and maybe that is what causing the issue. It looks like in between the obtaining the name and trying to obtain the access to the file, the encoding is getting missed up. This result in calling preVisitDirectory once then visitFileFailed for every file it tries to visit. I'm not sure why the walkFileTree method is doing that. Any idea?
My using for SimpleFileVisitor code looks like this:
Files.walkFileTree(serverLocation, finder);
My SimpleFileVisitor class:
public class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private final List<Path> matchedPaths = new ArrayList<Path>();
private String usedPattern = null;
Finder(String pattern) {
this.usedPattern = pattern;
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void match(Path file) { //Compare pattern against file or dir
Path name = file.getFileName();
if (name != null && matcher.matches(name))
matchedPaths.add(file);
}
// Check each file.
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
match(file);
return CONTINUE;
}
// Check each directory.
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
match(dir);
return CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.println("Issue: " + e );
return CONTINUE;
}
Try using "Charset.defaultCharset()" when you create those "file" and "dir" strings you pass around. Otherwise, you could very likely mangle the names in the process of creating those strings to pass them to your visit methods.
You might also check your default encoding on the JVM your are running, if it is out of sync with the file system you are reading, your results will be, err, unpredictable.
I want to read different data from the console in a Dart server application, like:
forename : user inputs and enters
lastname : user inputs and enters
age : user inputs and enters
The following code works, but for 1 input item only:
var stream = new StringInputStream(stdin);
stream.onData = () {
voornaam = stream.readLine();
};
But I can't get it to work for multiple items.
Is there an easy way to do this in Dart ?
Thanks!
Since you're using a StringInputStream rather than just a standard InputStream, and because you're looking to read text. Unless there's a particular reason, I would recommend using the onLine handler over the onData. On data will basically try to 'stream' the information in that it's called immediately not on a new line itself. Try something like the following (note, not complete code, missing proper error handling etc.)
#import('dart:io');
main() {
var stream = new StringInputStream(stdin);
stream.onLine = () {
var str = stream.readLine().trim();
print(str.toUpperCase());
if(str == 'EXIT') exit(0);
};
}
One other note to point out, if you ever are data-streaming and using the onData handler, it is recommended that you then use the read method, as opposed to the readLine method to retrieve your content, again due to the nature of onData not waiting for a full line of text to be received before being called.
import 'dart:io';
void main() {
print('-----welcome-----');
print('what is your firstname');
var fname = stdin.readLineSync();
print('what is your lastname');
var lname = stdin.readLineSync();
print('what is your age');
int age = int.parse(stdin.readLineSync());
int left = 100 - age;
print('your name is $fname $lname and you are $age years');
}