I am sending the arrays from jquery to controller, and this arrays I am getting as String in controller String getIdVal = ParamUtil.getString(resourceRequest, "getId");
The Values in String getIds are like getIdVal ="1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ";
I am trying to get the result but no successes.
(Considering 1 is key ABC is value).
I wanted to remove ABC(ie repeated values) from all keys and append only once at the end. And at the same time I want the keys of repeated values should be like this (1-2-3_ABC). Finally the String should look like this "1-2-3_ABC,4-5_NMO,6_XYZ"
here I am try8ing to split based on comma, but I dont know how to solve.
List<String> keysVals = new ArrayList<String>(Arrays.asList(getIdVal .split(",")));
String getKeyVal;
String[] getKeys;
String key;
String value;
for (String getKeysVals : keysVals) {
getKeyVal = getKeysVals;
getKeys = getKeyVal.split("\\_");
key = getKeys[0];
value = getKeyVal.substring(getKeyVal.lastIndexOf("_") + 1) .trim();
// i am not getting how to check for dublicate
}
Did you mean something like this?
private static String mergeKeys(String input) {
Map<String, StringBuilder> valKeys = new TreeMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
StringBuilder builder = valKeys.get(val);
if (builder == null)
valKeys.put(val, new StringBuilder(key));
else
builder.append('-').append(key);
}
StringJoiner result = new StringJoiner(",");
for (Entry<String, StringBuilder> entry : valKeys.entrySet())
result.add(entry.getValue().append('_').append(entry.getKey()).toString());
return result.toString();
}
Or this slow version of the same logic, using string = string + string (Yikes!):
private static String mergeKeys(String input) {
Map<String, String> valKeys = new LinkedHashMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
String prevKeys = valKeys.get(val);
valKeys.put(val, prevKeys == null ? key : prevKeys + "-" + key);
}
String result = "";
for (Entry<String, String> entry : valKeys.entrySet())
result += "," + entry.getValue() + "_" + entry.getKey();
return result.substring(1); // skip leading comma
}
TEST
System.out.println(mergeKeys("1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ"));
OUTPUT
1-2-3_ABC,4-5_NMO,6_XYZ
Related
I need help converting the following JS-function to vb.net please:
function testjs(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
What my code looks like at the moment:
Private Function questionmarkop(ByVal ph As String, ByVal dictatcurr As String, ByVal ophoc As String) As String
Return If(ph = dictatcurr, dictatcurr, ophoc)
End Function
Private Function testvb(ByVal s As String) As String
Dim dict As New Dictionary(Of Integer, String)
Dim data As Char() = s.ToCharArray
Dim currchar As Char = data(0)
Dim oldphrase As String = currchar
Dim out As String() = {currchar}
Dim code As Integer = 256
Dim phrase As String = ""
Dim ret As String = ""
For i As Integer = 1 To data.Length - 1
Dim currcode As Integer = Convert.ToInt16(data(i))
If currcode < 256 Then
phrase = data(i)
Else
phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar))
End If
ReDim Preserve out(out.Length)
out(out.Length - 1) = phrase
currchar = phrase(0)
dict.Item(code) = oldphrase + currchar
code += 1
oldphrase = phrase
Next
For Each str As String In out
ret = ret + str
Next
Return ret
End Function
When inputting the following string s: thisĂaveryshorttestđringtogiĆanexamplefČđackoĆrflow
The function should return: thisisaveryshortteststringtogiveanexampleforstackoverflow
The js function does exactly that, my vb function does not sadly.
The first time (or basically everytime) the if statement is not true, the next character will be wrong. So i figure there is something wrong with the line phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar)).
With the test string i provided everything works until this, after that i have the first false char.
Can someone help me figure out what i am doing wrong here?
Based on discussion in the comments, it seems like the issue was producing a VB translation for this line:
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
I have only passing familiarity with Javascript, but I believe the key here is that dict[currCode] will return a type of null or missing value if there is not already an entry in the dictionary with key currCode. The .NET dictionary has facilities that will let you get the same effect, though the exact implementation is a little different.
The direct VB equivalent to this ternary and assignment is (I believe):
phrase = If(dict.ContainsKey(currCode), dict(currCode), oldPhrase & currChar)
You can eliminate a key lookup on the dictionary by using Dictionary.TryGetValue:
If Not dict.TryGetValue(currCode, phrase) Then
phrase = oldPhrase & currChar
End If
I doubt the code is performance-sensitive enough to care about the difference, so I would recommend to use the alternative that you find more clear to read.
I have the following string :
DetailsParameters = "Id=1,UserId=1,2,3"
In entity framework stored procedure I am trying to split the above string as :
"Id=1" and "UserId=1,2,3"
Currently, I have the following code which is splitting the above mentioned string at comma which is incorrect.
if (DetailsParameters != "")
{
List<Details> adlist = new List<Details>();
DetailsParameters.Split(',').ToList().ForEach(delegate (string s)
{
adlist.Add(new Details()
{
AlarmLogId = AlarmLogId,
ParameterKey = s.Substring(0, s.IndexOf('=')),
ParameterValue = s.Substring(s.IndexOf('=') + 1, (s.Length - (s.IndexOf('=') + 1)))
});
});
context.Details.AddRange(adlist);
No need to get too complicated about it, you could do something like this:
//var DetailsParameters = "Id=1,UserId=1,2,3";
//var DetailsParameters = "UserId=1,2,3,Id=1";
var indexOf = DetailsParameters.IndexOf("UserId=");
//if the index of "UserId=" is at the start, it should find the other word "Id=" to split
if (indexOf == 0) indexOf = DetailsParameters.IndexOf("Id=", "UserId=".Length);
var firstParameter = DetailsParameters.Substring(0, indexOf);
var secondParameter = DetailsParameters.Substring(indexOf, DetailsParameters.Length - firstParameter.Length);
var firstParameterValue = firstParameter.Split('=')[1].Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries);
var secondParameterValues = secondParameter.Split('=')[1].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
I'm use four arrays to generate difference test case, like below
var phone = ['phone1', 'phone2', 'phone3'];
var browsers = ['chrome', 'firefox'];
var location = ['1324','2434','4234','1234','3243'];
var network = ['3g', '4g', 'wifi'];
var isLogin = ['service worker', 'no service worker'];
How do I write code that will generate the test case (180 difference case). I try for loop and recursion. I just can't seem to figure out a perfect way to do it. note I'm using javascript. can only use array for loop, can't use object due to some reason.
Can anyone give me some inspiration ?
I tried some scenario in Java(Approach can be applicable in same way for Javascript) with recursion, In this case I use 3 arrays and for 2 of them I use recursion.
public class Test3 {
static String[] names = { "Ram", "Shyam", "Mohan", "Rohan", "Saket" };
static String[] citys = { "Bhopal", "Indore", "Ujjan", "Dewas", "Rewa" };
static String[] addresses = { "add1", "add2", "add3", "add4", "add5" };
static StringBuffer buffer = new StringBuffer();
public static void main(String... strings) {
for (String a : names) {
System.out.println(testData(a)+"\n");
buffer.setLength(0);
}
}
public static String testData(String name) {
return generateData(name, 0, -1);
}
public static String generateData(String combination, int countA, int countB) {
if ((countA == names.length - 1) && (countB == names.length - 1)) {
return buffer.toString();
}
if (countB == addresses.length - 1) {
countA = countA + 1;
countB = -1;
}
countB = countB + 1;
buffer.append(combination + citys[countA] + addresses[countB] + "\n");
return generateData(combination, countA, countB);
}
}
Hope this will help!!
Currently I'm trying to generate a chap response in java. It works in php... but our backend needs it done in java.
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal)
I've managed to find some javascript code, but the response is off by a few characters.
function getPapPassword(){
//function to add value padding to a string of x length default : null padding
String.prototype.pad = function (length, padding) {
var padding = typeof padding === 'string' && padding.length > 0 ? padding[0] : '\x00'
, length = isNaN(length) ? 0 : ~~length;
return this.length < length ? this + Array(length - this.length + 1).join(padding) : this;
};
//function to convert hex to ascii characters
String.prototype.packHex = function () {
var source = this.length % 2 ? this + '0' : this
, result = '';
for (var i = 0; i < source.length; i = i + 2) {
result += String.fromCharCode(parseInt(source.substr(i, 2), 16));
}
return result;
};
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal);
}
return response;
}
Can anyone point me in the right direction or assist?
Thanks
Okay so what I've done is tried to convert from hex to ascii in java... here is my code.
public class App{
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
public static void main(String[] args) {
App app = new App();
System.out.println("ASCII : " + app.convertHexToString("9f9585f4e88305fde280c762925f37af"));
}
}
The php of the hex challenge output is: Ÿ•…ôèƒýâ€Çb’_7¯
The java output of the hex challenge is: ôèýâÇb_7¯
So I've found that the javascript is exactly the same as the java. Something is happening in php that is changing it. The php version works perfectly when I connect to the UAM with that chap response.
here is my recieved JSON string
"{Date:'15/05/2015',y:'6'},
{Date:'01/08/2015',y:'6'},
{Date:'02/08/2015',y:'6'},
{Date:'08/08/2015',y:'72'},
{Date:'09/08/2015',y:'6'},"
i have to make it exactly like that for my datasource in pie chart
var datas = [
{date:"02/02/2015",y:6},
{date:"15/05/2015",y:6},
{date:"01/08/2015",y:6},
{date:"02/08/2015",y:6}
];
here is working js fiddle js fiddle working for json
here is my c sharp code for making json
foreach (KeyValuePair<string, int> pair2 in dic)
{
int perce = pair2.Value;
var perct = ((double)perce / total) * 100;
int perc = Convert.ToInt32(perct);
string datesval = pair2.Key;
StringBuilder sb = new StringBuilder();
sb.Append("Date:'" + datesval + "',y:" + perc + "");
string newq = sb.ToString();
list.Add(newq);
}
StringBuilder sb2 = new StringBuilder();
foreach (string element in list)
{
for (int m = 0; m <= list.Count() - 1; m++)
{
sb2.Append("{" + list[m] + "},");
line = sb2.ToString();
}
break;
}
the string should be modified using javascript
remove (") double quote from start of string and add [ . also remove (,") from end and add ]
also show error Uncaught TypeError: undefined is not a function on line
$('#container').highcharts({
use string builder and eval , I am extentendinng the above from Line you built
string c = line;
StringBuilder builder = new StringBuilder(c);
// builder.Replace(",\"","]");
// builder[0] = '[';
TrimEnd(builder,',');
// builder.AppendFormat("[\"{0}\"]", builder.ToString());
string combine = "["+ builder.ToString();
string newcom = combine + "]";
return newcom;
}
static void TrimEnd(StringBuilder builder, char letter)
{
// ... If last char matches argument, reduce length by 1.
if (builder.Length == 0)
{
string c = "sorry";
}
else if (builder[builder.Length - 1] == letter)
{
builder.Length -= 1;
}
}
in succes of ajax do this
var v = eval(response.d);
now use this in pie chart
2nd error is because jquery files conflict with each other use jquery 1.9.1.js first then graph files