Ncurses menu with linked string - c++

Id like to have linked string in my ncurses menu to something like:
/bin
/hello
/home
...
And i have vector of components named w_files which have variable name (bin, hello, home, ...) and when i do this:
chdir(w_actDir.c_str());
this->selected = 0;
unsigned int n_choices = w_files.size();
my_items = (ITEM **)calloc(n_choices+1, sizeof(ITEM *));
for(unsigned int i = 0; i < n_choices; ++i){
string toShow = w_files[i]->getName();
my_items[i] = new_item(toShow.c_str(), "");
}
my_menu = new_menu((ITEM**)my_items);
set_menu_mark(my_menu, "");
set_menu_win(my_menu, this->w_window);
set_menu_format(my_menu, LINES-5, 1);
int center = COLS/2;
set_menu_sub(my_menu, derwin(this->w_window, LINES-5, center-5, 3, 1));
post_menu(my_menu);
wrefresh(this->w_window);
its ok, result looks:
bin
hello
home
...
But when change line string toShow = w_files[i]->getName(); to string toShow = "/" + w_files[i]->getName();
Result is:
Can anybody help me, please?
Thank you.

Actually, after posting the comment I had an idea for an answer - the safest way would be appending to toShow string.
Code sample:
string toShow = "/";
toShow.append(w_files[i]->getName());

Related

Building a css grid with javascript: creating elements, storing them in arrays and append them to other elements

I recently build an masonry gallery with html and css. I used the display: grid; property to make it look like so. Now I am trying to create randomized layouts. Therefor I want to create elements with classes. I want to append / elements to the elements, store those elements inside an array and later append them inside my "masonry" . I put in different console.logs to see whats happening, but I get some either weird or undefined returns. Javascript can be as tricky as it can be fun for beginners, so I hope you guys can help me out.
Thank you all. :)
//arrays and variables
const figures = [];
let newFigures = "";
const divs = [];
let newDivs = "";
function makeCells(){
for(let i = 0; i < 33; i++){
newFigure = document.createElement("figure");
figures[i] = newFigure.classList.add("cell", "cell--" + i);
newDiv = document.createElement("div");
divs[i] = newDiv.setAttribute("id", i);
console.log("log1: " + newFigure.classList);
console.log("log2: " + figures[i]);
}
console.log("log3: " + divs);
console.log("log4: " + figures);
console.log("log5: " + divs);
for(let i=0; i<3; i++){
figures[i] = newFigure.appendChild(newDiv);
}
console.log("figures = " + figures);
console.log("divs = " + divs);
let z = {};
for(let i=0; i<3; i++){
z = figures[i];
document.getElementById("masonry").appendChild(z);
}
console.log(document.getElementById("masonry"));
}
Here is a picture of the corresponding console.logs.
Console Logs
This works as intended:
const figures = [];
let newFigure = "";
const divs = [];
let newDiv = "";
function makeCells(){
for(let i = 0; i < 33; i++){
newFigure = document.createElement("figure");
newDiv = document.createElement("div");
newFigure.appendChild(newDiv);
document.getElementById("masonry").appendChild(newFigure);
figures[i] = newFigure.classList.add("cell", "cell--" + i);
}
console.log(document.getElementById("masonry"));
}
Sorry to bother you guys.
I don't like this line of code, mainly because the add() method does not have a return value.
figures[i] = newFigure.classList.add("cell", "cell--" + i);
I would split it into two statements.
newFigure.classList.add("cell", "cell--" + i);
figures.push(newFigure);

How to convert a string to a Location Object Bukkit Plugin

I was wondering how I can convert a string (Loaded from the config). Convert into a Location object. I've already tried this code:
private Location StringToLocation(String input, Main plugin) {
Location world = new Location(Bukkit.getWorld(plugin.getConfig().getString("world")), 0, 0, 0);
int index;
int LengteString;
String[] myCoordinaat = { "", "", "" };
for (int iLoop = 0; iLoop < 2; iLoop++)
{
index = input.indexOf(",");
LengteString = input.length() - index;
myCoordinaat[iLoop] = input.substring(index, LengteString);
input = input.substring(0, index + 1);
}
myCoordinaat[2]=input;
Bukkit.getLogger().info("x: " + myCoordinaat[0] + " y:" + myCoordinaat[1] + " z:" + myCoordinaat[2]);
world.setX(Double.parseDouble(myCoordinaat[0]));
world.setY(Double.parseDouble(myCoordinaat[1]));
world.setZ(Double.parseDouble(myCoordinaat[2]));
return world;
}
Thanks in advance!
There is a very easy solution to your problem that doesn't even involve you parsing the location yourself.
//Save location
getConfig().set("path.to.location", loc);
saveConfig();
//Load location
Location location = (Location) getConfig().get("path.to.location");
You can basically store the object in the config and then restore it. Just keep in mind that the world needs to be loaded for the Location to be parsed.

Can't get the proper Index to return

Alright, so firstly I want to thank everyone for helping me so much in the last couple weeks, here's another one!!!
I have a file and I'm using Regex to find how many times the term "TamedName" comes up. That's the easy part :)
Originally, I was setting it up like this
StreamReader ff = new StreamReader(fileName);
String D = ff.ReadToEnd();
Regex rx = new Regex("TamedName");
foreach (Match Dino in rx.Matches(D))
{
if (richTextBox2.Text == "")
richTextBox2.Text += string.Format("{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
else
richTextBox2.Text += string.Format("\n{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
}
and it was returning completely incorrect index points, as pictured here
I'm fairly confident I know why it's doing this, probably because converting everything from a binary file to string, obviously not all the characters are going to translate, so that throws off the actual index count, so trying to relate that back doesn't work at all... The problem, I have NO clue how to use Regex with a binary file and have it translate properly :(
I'm using Regex vs a simple search function because the difference between each occurrence of "TamedName" is WAY too vast to code into a function.
Really hope you guys can help me with this one :( I'm running out of ideas!!
The problem is that you are reading in a binary file and the streamreader does some interpretation when it reads it into a Unicode string. It needed to be dealt with as bytes.
My code is below.(Just as an FYI, you will need to enable unsafe compilation to compile the code - this was to allow a fast search of the binary array)
Just for proper attribution, I borrowed the byte version of IndexOf from this SO answer by Dylan Nicholson
namespace ArkIndex
{
class Program
{
static void Main(string[] args)
{
string fileName = "TheIsland.ark";
string searchString = "TamedName";
byte[] bytes = LoadBytesFromFile(fileName);
byte[] searchBytes = System.Text.ASCIIEncoding.Default.GetBytes(searchString);
List<long> allNeedles = FindAllBytes(bytes, searchBytes);
}
static byte[] LoadBytesFromFile(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
//BinaryReader br = new BinaryReader(fs);
//StreamReader ff = new StreamReader(fileName);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
fs.Close();
return ms.ToArray();
}
public static List<long> FindAllBytes(byte[] haystack, byte[] needle)
{
long currentOffset = 0;
long offsetStep = needle.Length;
long index = 0;
List<long> allNeedleOffsets = new List<long>();
while((index = IndexOf(haystack,needle,currentOffset)) != -1L)
{
allNeedleOffsets.Add(index);
currentOffset = index + offsetStep;
}
return allNeedleOffsets;
}
public static unsafe long IndexOf(byte[] haystack, byte[] needle, long startOffset = 0)
{
fixed (byte* h = haystack) fixed (byte* n = needle)
{
for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext < hEnd; hNext++)
for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)
if (++nInc == nEnd)
return hNext - h;
return -1;
}
}
}
}

Display Unread Missed calls in android listView

I want to get the details of the unread missed calls list in my android app.
I came up with this code but this shows the whole list of my missed calls not only those which are unread.
lv= (ListView)findViewById(R.id.listView1);
List<String> lst=new ArrayList<String>();
String miss_read="read";
String unread_condition=miss_read+"=0";
String[] projection = {CallLog.Calls.NUMBER,CallLog.Calls.CACHED_NAME,CallLog.Calls.TYPE};
//String[] projection = {Integer.parseInt(CallLog.Calls.MISSED_TYPE};
//String where = (CallLog.Calls.TYPE+CallLog.Calls.NEW+"="+CallLog.Calls.MISSED_TYPE);
String where = (CallLog.Calls.NEW+" = "+"new"+" AND "+CallLog.Calls.TYPE+" = "+CallLog.Calls.MISSED_TYPE);
Cursor c = this.getContentResolver().query(CallLog.Calls.CONTENT_URI,projection,where, null, null);
int i=0;
if(c.moveToFirst())
{
do
{
if(CallLog.Calls.IS_READ!="is_read")
lst.add(c.getString(0)+"not read");
//i++;
}while(c.moveToNext());
}
ArrayAdapter<String> adpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lst);
lv.setAdapter(adpt);
does anybody provide me the solution for my problem...??
Try this.
String[] projection = new String[] { CallLog.Calls.NUMBER,
CallLog.Calls.TYPE, CallLog.Calls.NEW };
String where = (CallLog.Calls.NEW + " = " + "1" + " AND "
+ CallLog.Calls.TYPE + " = " + CallLog.Calls.MISSED_TYPE);
Cursor c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
projection, where, null, null);

extract domain between two words

I have in a log file some lines like this:
11-test.domain1.com Logged ...
37-user1.users.domain2.org Logged ...
48-me.server.domain3.net Logged ...
How can I extract each domain without the subdomains? Something between "-" and "Logged".
I have the following code in c++ (linux) but it doesn't extract well. Some function which is returning the extracted string would be great if you have some example of course.
regex_t preg;
regmatch_t mtch[1];
size_t rm, nmatch;
char tempstr[1024] = "";
int start;
rm=regcomp(&preg, "-[^<]+Logged", REG_EXTENDED);
nmatch = 1;
while(regexec(&preg, buffer+start, nmatch, mtch, 0)==0) /* Found a match */
{
strncpy(host, buffer+start+mtch[0].rm_so+3, mtch[0].rm_eo-mtch[0].rm_so-7);
printf("%s\n", tempstr);
start +=mtch[0].rm_eo;
memset(host, '\0', strlen(host));
}
regfree(&preg);
Thank you!
P.S. no, I cannot use perl for this because this part is inside of a larger c program which was made by someone else.
EDIT:
I replace the code with this one:
const char *p1 = strstr(buffer, "-")+1;
const char *p2 = strstr(p1, " Logged");
size_t len = p2-p1;
char *res = (char*)malloc(sizeof(char)*(len+1));
strncpy(res, p1, len);
res[len] = '\0';
which is extracting very good the whole domain including subdomains.
How can I extract just the domain.com or domain.net from abc.def.domain.com ?
is strtok a good option and how can I calculate which is the last dot ?
#include <vector>
#include <string>
#include <boost/regex.hpp>
int main()
{
boost::regex re(".+-(?<domain>.+)\\s*Logged");
std::string examples[] =
{
"11-test.domain1.com Logged ...",
"37-user1.users.domain2.org Logged ..."
};
std::vector<std::string> vec(examples, examples + sizeof(examples) / sizeof(*examples));
std::for_each(vec.begin(), vec.end(), [&re](const std::string& s)
{
boost::smatch match;
if (boost::regex_search(s, match, re))
{
std::cout << match["domain"] << std::endl;
}
});
}
http://liveworkspace.org/code/1983494e6e9e884b7e539690ebf98eb5
something like this with boost::regex. Don't know about pcre.
Is the in a standard format?
it appears so, is there a split function?
Edit:
Here is some logic.
Iterate through each domain to be parsed
Find a function to locate the index of the first string "-"
Next find the index of the second string minus the first string "Logged"
Now you have the full domain.
Once you have the full domain "Split" the domain into your object of choice (I used an array)
now that you have the array broken apart locate the index of the value you wish to reassemble (concatenate) to capture only the domain.
NOTE Written in C#
Main method which defines the first value and the second value
`static void Main(string[] args)
{
string firstValue ="-";
string secondValue = "Logged";
List domains = new List { "11-test.domain1.com Logged", "37-user1.users.domain2.org Logged","48-me.server.domain3.net Logged"};
foreach (string dns in domains)
{
Debug.WriteLine(Utility.GetStringBetweenFirstAndSecond(dns, firstValue, secondValue));
}
}
`
Method to parse the string:
`public string GetStringBetweenFirstAndSecond(string str, string firstStringToFind, string secondStringToFind)
{
string domain = string.Empty;
if(string.IsNullOrEmpty(str))
{
//throw an exception, return gracefully, whatever you determine
}
else
{
//This can all be done in one line, but I broke it apart so it can be better understood.
//returns the first occurrance.
//int start = str.IndexOf(firstStringToFind) + 1;
//int end = str.IndexOf(secondStringToFind);
//domain = str.Substring(start, end - start);
//i.e. Definitely not quite as legible, but doesn't create object unnecessarily
domain = str.Substring((str.IndexOf(firstStringToFind) + 1), str.IndexOf(secondStringToFind) - (str.IndexOf(firstStringToFind) + 1));
string[] dArray = domain.Split('.');
if (dArray.Length > 0)
{
if (dArray.Length > 2)
{
domain = string.Format("{0}.{1}", dArray[dArray.Length - 2], dArray[dArray.Length - 1]);
}
}
}
return domain;
}
`