samedi 28 février 2015

Whats wrong whit the array?


<html>

<head>

<title> Random </title>

<script type="text/javascript" language="JavaScript">

var typeFont = new Array ( "cooper","Fixedsys","Edwardian Script ITC", "Gill Sans MT", "Kozuka Gothic Pro", "Lucida Sans", "Adobe Gothic Std", "Adobe Naskh", "Algerian","Arial Unicode MS");

function font()
{
head6.style.fontFamily = typeFont[ Math.floor( Math.random * 10 ) ];
}
</script>
</head>

<body>

<center>
<h1 onmouseover="font()" onmouseout="font" id="head6" > this is the text </h1>
</center>

</body>


i am trying to change the font every time the mouse is over o out and this function whit head6.style.fontFamily = typeFont[3] but its doesnt whit the array. Thank you.


Java: is there an int method like charAt()?

I don't want "charAt(1);" to return the character at position 1 in the string... I want it to report all instances of "matching = 1;"


Take for example



int matching = 1;
int notMatching = 0;
int HI = matching;
int IH = notMatching;
int searchString = theString.charAt(notMatching);

int count = 0;
int index = 0;

while (0 < theString.length())
{
int = theString.charAt(matching);
if (theString.charAt(notMatching) == searchString)
{
count = count + 1;
}
index = index + 1;
}


Not a great example but basically what I want, or what this program is supposed to do is take a user input:



HIHIIH



and report the instances of HI spelled as IH... so the return would be for instance;



System.out.println("HI was spelled as IH" + count + "times");



C++ Assign GradeBook

Hi and thanks in advanced. I'm working on this H.W. and I'm beginner. I keep on running on in M.S. VS Professional but keeps returning too many errors and I fix them, yet same issues not sure if what I had added to the code is wrong. The results should display its takes no more than 30 char. it should display total number of students received a grade, the average, and class average in one digit double value and GPA. Here is the code:



#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// constructor initializes courseName with string supplied as argument;
// initializes counter data members to 0
GradeBook::GradeBook(string name)
{
cout << "The Grade Book Constructor is called" << endl;
setCourseName(name); // validate and stores courseName
aCount = 0; // initialize count of A grades to 0
bCount = 0; // initialize count of B grades to 0
cCount = 0; // initialize count of C grades to 0
dCount = 0; // initialize count of D grades to 0
fCount = 0; // initialize count of F grades to 0
displayMessage();
cout << "The Grade Book," << getCourseName() << "Contains" << endl << endl < endl;
displatGradeReport(0);
cout << "*****The end of Grade Book Constructor.*****" << endl;
} // end GradeBook constructor

// function to set the course name; limits name to 25 or fewer characters
void GradeBook::setCourseName( string name )
{
if ( name.size() <= 30 ) // if name has 30 or fewer characters
courseName = name; // store the course name in the object
else // if name is longer than 30 characters
{ // set courseName to first 30 characters of parameter name
courseName = name.substr( 0, 30 ); // select first 25 characters
cerr << "Name \"" << name << "\" exceeds maximum length (30).\n"
<< "Limiting courseName to first 30 characters.\n" << endl;
} // end if...else
} // end function setCourseName

// function to retrieve the course name
string GradeBook::getCourseName()
{
return courseName;
} // end function getCourseName

// display a welcome message to the GradeBook user
void GradeBook::displayMessage()
{
// this statement calls getCourseName to get the
// name of the course this GradeBook represents
cout << "Welcome to the grade book for\n" << getCourseName() << "!\n"
<< endl;
} // end function displayMessage

// input arbitrary number of grades from user; update grade counter
void GradeBook::inputGrades()
{
int grade; // grade entered by user

cout << "Enter the letter grades." << endl;
cout << "Enter the EOF character to end input." << endl;
cout << "Use Ctl + D, or Ctl + Z)" << endl;

// loop until user types end-of-file key sequence
while ( ( grade = cin.get() ) != EOF )
{
// determine which grade was entered
switch ( grade ) // switch statement nested in while
{
case 'A': // grade was uppercase A
case 'a': // or lowercase a
++aCount; // increment aCount
break; // necessary to exit switch

case 'B': // grade was uppercase B
case 'b': // or lowercase b
++bCount; // increment bCount
break; // exit switch

case 'C': // grade was uppercase C
case 'c': // or lowercase c
++cCount; // increment cCount
break; // exit switch

case 'D': // grade was uppercase D
case 'd': // or lowercase d
++dCount; // increment dCount
break; // exit switch

case 'F': // grade was uppercase F
case 'f': // or lowercase f
++fCount; // increment fCount
break; // exit switch

case '\n': // ignore newlines,
case '\t': // tabs,
case ' ': // and spaces in input
break; // exit switch

default: // catch all other characters
cout << "****Incorrect letter grade entered.****" << endl;
cout << " Enter a new grade." << endl;
break; // optional; will exit switch anyway
} // end switch
} // end while
} // end function inputGrades

// display a report based on the grades entered by user
void GradeBook::displayGradeReport()
{
// output summary of results
// total grades
int gradeCount = aCount + bCount + cCount + dCount + fCount;
cout << "\n\nThe total number of students receive grade is" << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl;
} // end calculate number of grades received

// display class average
// if user entered at least one grade
if (gradeCount != 0)
{
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
} // end if
} // end function displayGradeReport
void GradeBook::displayGradeReport(int n)
{
// display summary of results
// calculate total grades
int gradeCount = aCount = bCount = cCount = dCount = fCount = n;
cout << "The total number of students receive grades is " << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl << endl;

// calculate total grades


// display class average
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
if (gradeCount != 0)
{
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
}
else
{
cout << "\nThe class average is: 0.0" << endl << endl << endl;
}
} // end function displayGradeReport


Here is the .h



#include <string> // program uses C++ standard string class
using namespace std;

// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook


And here is the file I'm executing from in the project


include // program uses C++ standard string class


using namespace std;



// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook

Printing odd numbered characters in a string without string slicing?

I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.


Define buttonnummer programmatically?

I'm trying to set the title of a button in Swift. The button title and number is random. I have button1..16. Swift doesn't accept 'button' with 'String doesn't have a member named 'setTitle'. How can I make Swift accept this?



var buttonNumber = arc4random_uniform(16) + 1
var targetNumber = arc4random_uniform(20) + 1
var button = "button\(buttonNumber)"
button.setTitle("\(targetNumber)", forState: UIControlState.Normal)

How to change the color of a JButton when the name of the JButton I want to color is in a string?

I have a random number method and random color method set up. I have 28 buttons and they all are named button_number. The random number picks the button. I have some basic code that obviously doesn't work because I can't change the background of the string but I don't know where to go from here.



static Random random = new Random();
static int rand1 = RandomRange.showRandomInteger(1, 28, random);
static String num = Integer.toString(rand1);
static String button = ("button_" + num);

button.setBackground(randomColor());

How to find the delimiter encountered in a string in JAVA

I have written simple program in Java which does manipulation of a given string.


The input string has some delimiters which are non-alphabets. I have used String Tokenizer to read and manipulate the individual words in a string.


Now I need to reconstruct this manipulated string with the same set of delimiters. Appreciate if any one can suggest me how to identify the delimiter.


In other words, this is what input is:


Text1 Text2 Text3 Text4 This is what my code does:


NewText1 NewText2 NewText3 NewText4


I made use of string tokenizer to identify the next token in this manner: StringTokenizer st = new StringTokenizer(str, ", 0123456789(*&^%$#@!-_)");


But now I would like to identify the delimiter that was encountered so that I can build my new string.


This is what I actually want:


NewText1 Delimiter1 NewText2 Delimiter2 NewText3 Delimiter3 NewText4 Delmiter4


Executing functions stored in a string

Lets say that there is a function in my Delphi app:

MsgBox and there is a string which has MsgBox in it.

I know what most of you are going to say is that its possible, but I think it is possible because I opened the compiled exe(compiled using delphi XE2) using a Resource Editor, and that resource editor was built for Delphi. In that, I could see most of the code I wrote, as I wrote it. So since the variables names, function names etc aren't changed during compile, there should a way to execute the functions from a string, but how? Any help will be appreciated.


Trying to pass a string as an argument for a class but it is being recognized as an array of chars instead in C++

I am having problems initializing Warrior Objects in my main function


The code for my Warrior Class is below



class Warrior{
public:

Warrior(const string& input_name, int& input_strength) :name(input_name), strength(input_strength) {};

string getname()const{
return name;
};

int getstrength(){
return strength;
};

void change_strength(int damg_taken){
strength -= damg_taken;
};

private:
string name;
int strength;
};


This is part of the code for the main function



Warrior cheetah("Tarzan", 10);
Warrior wizard("Merlin", 15);
Warrior theGovernator("Conan", 12);
Warrior nimoy("Spock", 15);
Warrior lawless("Xena", 20);
Warrior mrGreen("Hulk", 8);
Warrior dylan("Hercules", 3);


All of the Warrior initializations in the main function cause a error that is something like this:


Error:no instance of constructor "Warrior::Warrior" matches the argument list argument types are:(const char[7],int)


I read somewhere that strings in C++ are actually arrays of chars and that is why the warrior initialization are not working but I don't know how to change the constructor to make the program work. Also I am not allowed to change the main function because it was provided by the instructor.


Split String While Ignoring Escaped Character

I want to split a string along spaces, ignoring spaces if they are contained inside single quotes, and ignoring single quotes if they are escaped (i.e., \' ) I have the following completed from another question.



String s = "Some message I want to split 'but keeping this a\'s a single string' Voila!";
for (String a : s.split(" (?=([^\']*\'[^\"]*\')*[^\']*$)")) {
System.out.println(a);
}


The output of the above code is



Some
message
I
want
to
split
'but
keeping
this
a's a single string'
Voila!


However, I need single quotes to be ignored if they are escaped ( \' ), which the above does not do. Also, I need the first and last single quotes and forward slashes removed, if and only if it (the forward slashes) are escaping a single quote (to where 'this is a \'string' would become this is a 'string). I have no idea how to use regex. How would I accomplish this?


Generating all strings of length n from given alphabet. Python

So I am currently trying to define a function that will generate a list of all strings of length n from a given alphabet without using imports. I have stumbled upon this code:



def allstrings(alphabet, length):

c = [[]]
for i in range(length):
c = [[x]+y for x in alphabet for y in c]
return c


But this is returning a list of lists consisting of the strings, eg



all_strings({'a', 'b'}, 2)


returns



[['a', 'a'], ['a', 'b'], ['b', 'a'], ['b', 'b']]


But I require it to return a list of the generated strings, eg



['aa', 'ab', 'ba', 'bb']


I am unsure on how to do this. Any help is appreciated. Cheers


Calculate max even lengths of a string to be split

I know what I want but I have no idea if there's a technical name for this or how to go about calculating it.


Suppose I have a string:


ABCDEFGHI


This string can be split evenly into a "MAXIMUM" of 3 characters each sub-string.


Basically, I'm trying to find out how to split a string evenly into its maximum sub-lengths. A string of 25 characters can be evenly split into 5 parts consisting of 5 characters each. If I tried to split it into 4 or 6 pieces, I'd have an odd length string (a string with a size different from the others).



  • A string of 9 characters can be split into only 3 pieces of 3 characters each.

  • A string of 10 characters can be split into only 2 pieces of 5 characters each.

  • A string of 25 characters can be split into only 5 pieces of 5 characters each.

  • A string of 15 characters can be split into 3 pieces of 5 characters each OR 5 pieces of 3 characters each. A string of 11 characters cannot be split because one string will always be larger than the other.


So how do I go about doing this? I've thought of using the square root but that doesn't work for a string of "10" characters. Works for 9 and 25 just fine.


Any ideas? Is there a technical name for such a thing? I thought of "Greatest Common Divisor", but I'm not so sure.


Verify if String matches real number

I'm trying to verify if a String s match/is a real number. For that I created this method:



public static boolean Real(String s, int i) {

boolean resp = false;
//
if ( i == s.length() ) {
resp = true;
} else if ( s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
resp = Real(s, i + 1);
} else {
resp = false;
}
return resp;
}

public static boolean isReal(String s) {

return Real(s, 0);
}


But obviously it works only for round numbers. Can anybody give me a tip on how to do this?


P.S: I can only use s.charAt(int) e length() Java functions.


Iterate on files of a folder, with specific condition

Using this solution with dirent.h, I'm trying to iterate on specific files of the current folder (those which have .wav extension and begin with 3 digits) with the following code :


(Important note: as I use MSVC++ 2010, it seems that I cannot use #include <regex>, and that I cannot use this as well because no C++11 support)



DIR *dir;
struct dirent *ent;
if ((dir = opendir (".")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
//if substr(ent->d_name, 0, 3) ... // what to do here to
// check if those 3 first char are digits?
// int i = susbtr(ent->d_name, 0, 3).strtoi(); // error here! how to parse
// the 3 first char (digits) as int?

// if susbtr(ent->d_name, strlen(ent->d_name)-3) != "wav" // ...

}
closedir (dir);
} else {
perror ("");
return EXIT_FAILURE;
}


How to perform these tests with MSVC++2010 in which C+11 support is not fully present?


C check if last character of string is equal with X

im writing a sketch for my arduino and i would like to check the last character of my string.


For example:


If the input is cats- i want to see if the last char (in my case is "-") is actualy -


The code im using:


The serial event function



void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '.') {
stringComplete = true;
}
}
}


This is checking if the input string is completed by checking the input is equals with -. However this is working only with the console because the python script im using is sending everything together



void loop() {
if (stringComplete) {
Serial.println(inputString);
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0,0);
display.println("Altitude:");
display.println(inputString);
display.display();
// clear the string:
inputString = "";
stringComplete = false;
}


Any idea on how to check it?


Python3 .format() align usage

Can anyone help me to change the writing of these lines? I want to get my code to be more elegant using .format(), but I don't really know how to use it.


print("%3s %-20s %12s" %("Id", "State", "Population"))


print("%3d %-20s %12d" % (state["id"], state["name"], state["population"]))


Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.


//.....



Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;

String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}


}


This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!


Ascii string of bytes packed into bitmap/bitstring back to string?

I have a string that is packed such that each character was originally an unsigned byte but is stored as 7 bits and then packed into an unsigned byte array. I'm trying to find a quick way to unpack this string in Python but the function I wrote that uses the bitstring module works well but is very slow. It seems like something like this should not be so slow but I'm probably doing it very inefficiently...


This seems like something that is probably trivial but I just don't know what to use, maybe there is already a function that will unpack the string?



from bitstring import BitArray

def unpackString(raw):
msg = ''

bits = BitArray(bytes=raw)
mask = BitArray('0b01111111')

i = 0
while 1:
try:
iByte = (bits[i:i + 8] & mask).int
if iByte == 0:
msg += '\n'
elif iByte >= 32 and iByte <= 126:
msg += chr(iByte)
i += 7
except:
break

return msg

C Programming - Split a file content or a string to an array of string of the SAME size

I need an advice about C programming. I need to split a file (or its content) to an array of char. I found all over the internet different solutions to either split a file to different smaller files or split a string to an array but using delimiters with strtok()


The thing is : I need to split it et store it into an array of char but each elements must have the same siwe (64 bits)


Do you guys have any idea how I can do it ( Using the standard C library ) ? Any advices would be greatly appreciated.


TO be clearer : I managed to split a file into several smallers files of the same size example :


Zeddis@localhost $> ls -la -rw-rw-r--. 1 Zeddis Zeddis 64 28 févr. 23:17 filepart_number_10 -rw-rw-r--. 1 Zeddis Zeddis 64 28 févr. 23:17 filepart_number_11 -rw-rw-r--. 1 Zeddis Zeddis 64 28 févr. 23:17 filepart_number_12 [...]


but I need to store the content into an array, not files and each element's size has to be 64.


lets say I have a 2mb .txt file, I need to store its content to an array zhere its element's size is 64 bits.


I hope you understood since english is not my native language.


thanks in advance, Regards,


Trying to take two strings with values attached and subtract them

As shown, I have written this code and have assigned values for CASH and TOTAL. What I can not understand is why I get..... "Traceback (most recent call last): File "C:\Python27\Checkout Counter2.py", line 29, in change = cash - total TypeError: unsupported operand type(s) for -: 'str' and 'str'"


I've tried multiple ways to make this work, and I dont see any difference between that and when it finds the total.



print "Welcome to the checkout counter! How many items are you purchasing today?"
#NOI is number of items
NOI = int(raw_input())
productlist = []
pricelist=[]
for counter in range(NOI):
print"Please enter the name of product", counter+1
productlist.append(raw_input())

print"And how much does", productlist[len(productlist)-1], "cost?"
pricelist.append(float(raw_input()))
if pricelist[len(pricelist)-1] < 0:
pricelist.pop()
productlist.pop()
len(productlist)-1
len(pricelist)-1

print "Your order was:"
subtotal=0.00
for counter in range(NOI):
print productlist[counter],
print "$%0.2f" % pricelist[counter]
subtotal += pricelist[counter]
total = "$%0.2f" % float(subtotal + (subtotal * .09))
print "Your subtotal comes to", "$" + str(subtotal) + ".", " With 9% sales tax, your total is " + str(total) + "."
print "Please enter cash amount:"
cash = raw_input()
while True:
change = cash - total
if cash < total:
print "You need to give more money to buy these items. Please try again."
else:
print "I owe you back", "$" + float(change)

String searching in Rebol or Red

I'm interested in searching on a lot of long strings, to try and hack out a sed-like utility in rebol as a learning exercise. As a baby step I decided to search for a character:



>> STR: "abcdefghijklmopqrz"

>> pos: index? find STR "z"
== 18

>> pos
== 18


Great! Let's search for something else...



>> pos: index? find STR "n"
** Script Error: index? expected series argument of type: series port
** Where: halt-view
** Near: pos: index? find STR "n"

>> pos
== 18


What? :-(


Yeah, there was no "n" in the string I was searching. But what is the benefit of an interpreter blowing up instead of doing something sensible, such as returning a testable "null" char in pos?


I was told I should have done this:



>> if found? find STR "z" [pos: index? find STR "z"]
== 18

>> if found? find STR "n" [pos: index? find STR "n"]
== none

>> pos
== 18


Really? I have to search the string TWICE; the first time just to be sure it is "safe" to search AGAIN?


So I have a three-part question:




  1. How would a wizard implement my search function? I presume there is a wizardly better way better than this....




  2. Is Red going to change this? Ideally I'd think find should return a valid string position or a NULL if it hits end of string (NULL delimited, may I presume?). The NULL is FALSE so that would set up for a really easy if test.




  3. What is the most CPU effective way to do a replace once I have a valid index? There appear to so many choices in Rebol (a good thing) that it is possible to get stuck in choosing or stuck in a suboptimal choice.




Name of enumeration value in Swift, does not return String. :( description)

someone already said that to print a name out of an enum you have to implement something like this:


enum itemlist: Int { case nothing = 0, healingpotion, manapotion



var description : String {
get {
switch(self) {
case .nothing:
return "---"
case .healingpotion:
return "Healingpotion"
case .manapotion:
return "Manapotion"
}
}
}


}


when i call this parameter it stil returns the number. what am i missing?


player.item1.description // result 1 and not healingpotion


php remove string: fa fa-phone famouse

I want to remove the strings fa and fa-phone of the string: "fa famouse fa-phone".


I tried:



preg_replace('/fa.+$/','', 'fa famouse fa-phone');


But now it removes all strings with fa.


Extracting value nodes from XML C string representation

I have a string representation of an xml line. What is the best method to retrieve the inside node values as strings?



char *str = "<heading>Reminder</heading><body>Don't forget me this weekend!</body>"

Java , add new string object if the length of the chain exceeds a number of character

I'm trying to add a new String in arraylist if the lenght of this one is too big.


like that;



private void createLore(String s) {
ArrayList<String> a = new ArrayList<String>();
if(s.lenght > maximumLenght) {
a.add(s /TODO new object with same string
//it's like a new line .. possible to detect a space ?
//This avoids the cut of a text


Thank's !


include once inside echo [on hold]

I have two headers which I'd like to display according to account type; "a" for admin type and "b" for regular user type. I already have the enum set 'a','b'. Now, for the php after connecting to the database, I have:



<?php
while ($row = mysql_fetch_array($sql)){
$name = $row["name"];
$accounttype = $row["accounttype"];
if($accounttype == "a"){
$header = include_once "header_a.php";
}
if($accounttype == "b"){
$header = include_once "header_b.php";
}
}
?>


As for the html, I have:



<html>
<body>

<?php echo $accounttype; ?>

</body>
</html>


Edit: For some reason this worked like a charm... not sure why nor how.



<?php
while ($row = mysql_fetch_array($sql)){
$name = $row["name"];
$accounttype = $row["accounttype"];
if($accounttype == "a"){
include_once "header_a.php";
}
if($accounttype == "b"){
include_once "header_b.php";
}
include_once "header_".$accounttype.".php";
}
?>

<html>
<body>

<?php echo $header; ?>

</body>
</html>

Mysql error Unknown column in where clause

Friends, i am new to the world of php and database programming. I apologize ahead if i fail to communicate well using the right terminologies.


Table 1



Id | name | lastName | age
===============================
1 | Jane | Kot | 20
2 | Ann | Ama | 17

Table 2



Id | lastName | bonus | sex
==============================
1 | kot | 50% | male
2 | Jack | 20% | male

I want to join the two tables where table1.lastName = table2.lastName. In the illustration above, I would be looking forward to having “1 Jane 20 (all from table1) 1 50% male (all from table2) returned. But I would choose to display any of the data, hyper-linking it to display the entire record in another page using the common field (lastName)


Example: Jane, displayed in page1.php, when clicked will display the combined record in page2.php. Jane (now hyper-linked in page1.php) ---------clicked---------> 1 Jane 20 1 50% male (displayed in page2.php) Please help me. I apologize for my poor mode of expressing my problem. Thanks


CODE FOR PAGE1.PHP



$sql = "SELECT * FROM table1, table2 WHERE table1.lastname = table_2.lastname";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) {
echo '<table border="1">';
echo '<tr>';
echo '<td>'. $row['name'].'<br>'.'</td>';
echo '<td><a href="page2.php? lastName=' . $row['lastName'] . '">VIEW DETAILS</a></td>';
echo'</tr>';
echo'</table>';
}
?>


CODE FOR PAGE2.PHP



$lastName = mysql_real_escape_string($_GET['lastName']);
$sql =mysql_query ('SELECT name, age, bonus, sex FROM table_1 c join table_2 f on c.lastname = f.lastname where c.lastname = $lastname ' )
or die(mysql_error());
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
while ($row) {
// Echo page content
echo $row['name'].'<br>';
echo $row['age'];
echo $row['sex'];
echo $row['bonus'];
}
?>


When i clicked on "View Details" in page1.php, I get this error Unknown column '$lastname' in 'where clause'


Reverse vs Reverse! in Ruby when comparing palindrome

I know that reverse creates a new string with the characters of the string in reverse and that reverse! mutates (reverses) the current string in place. My question is why, when for example testing for a palindrome, this occurs?:



a = "foobar"
a == a.reverse # => false
a == a.reverse! # => true


Is it because it is the same object in memory, therefore == just checks if they have the same memory location?


Thanks!


Creating a new integer with the value of another integer being added to its name

I need to try and integrate the value of a integer into the name of a new integer I need to create. For example create a integer with the value of 32 with the name integer1. Then I create a new integer called integer+the value of integer 1 added to its name so the new integer name is integer32(so its called integer + the value of integer1).


If the question is not clear enough comment me questions on this post so I can answer them.


What use does the == operator have for String?

In Java, if one is to check if two Strings are equal, in the sense that their values are the same, he/she needs to use the equals method. E.g. :



String foo = "foo";
String bar = "bar";
if(foo.equals(bar)) { /* do stuff */ }


And if one wants to check for reference equality he needs to use the == operator on the two strings.



if( foo == bar ) { /* do stuff */ }


So my question is does the == operator have it's use for the String class ? Why would one want to compare String references ?


Edit: What I am not asking : How to compare strings ? How does the == work ? How does the equals method work?


What I am asking is what uses does the == operator have for String class in Java ?


Format string not working in C# getter

I need to format data string from format "dd.mm.yyyy" to be "yyyymmdd". I'm trying to do this following way, but this return unchanged string.



private string _pe1;
public string PassportEnd1 {
get { return String.Format("{0:yyyymmdd}", this._pe1); }
set { this._pe1 = value; }
}

String Manipulation in C#, Avoiding the right char, wrong place

I'm developing an app thats used for receiving a feed and presenting the data in a much nicer way. Currently I fetch the string, pass the string to a method that changes it into a list to make the data more easier to access. This was working fine throughout my app until I encountered this problem.


Sample Data:



[{"FirstName":"Bill","LastName":"Jones","UserName":"ourbilly","Played":"game306","Win":1.40,"City":"UK"}]



The above data would be broken down and presented like such



KEY | Value
FirstName : Bill
LastName : Jones
UserName : ourbilly
Played : game306
Win : 1.40
City : UK


This works, this is perfect. However I've just encountered a problem.. What if the value or key itself contained : inside of it.. for example



[{"FirstName":"Bi:ll","LastName":"Jones","UserName":"our:billy","Played":"game306","Win":1.40,"City":"UK"}]



The above data would be broken down and presented like such



KEY | Value
FirstName : Bi
ll : LastName
Jones : UserName
our : billy
Played : game306
Win : 1.40
City : UK


Which is actually incorrect, I'm unsure how to tackle this problem.. Below is the code that I'm using for making this list and for clearing up the string before returning it to present



public static ListWithDuplicates FetchFieldData(string data)
{
string[] words = cleanString(data).Split(':');

var list = new ListWithDuplicates();

for (int i = 0; i < words.Length;i++)
{
list.Add(words[i], words[i + 1]);
i++;
}

return list;
}

private static string cleanString(string messyString)
{
string[] toRemove ={ "{", "}", "\\", "\"", "[", "]" };

foreach (var s in toRemove)
{
messyString = messyString.Replace(s, "");
}
messyString = messyString.Replace(",", ":");
return messyString;
}

String is empty but still have length greater than 0

I am checking for html tags in a file using this regex:



/<([a-zA-Z]+(-[a-zA-Z]+)?(.*)?)>/


The file is:



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<div id="div">
<p class="class">Hello World</p>
</div>
</body>
</html>


Here is the result: (which is what i need)



string(4) "html"
string(4) "head"
string(20) "meta charset="utf-8""
string(18) "title>Title"
string(4) "body"
string(12) "div id="div""
string(30) "p class="class">Hello World"
string(14) ""
string(7) ""
string(7) ""


There's some "empty" strings that do not have content inside of them, but empty() returns false, and strlen() does not return 0, what is this?


When string object creates? [on hold]

I am bit confused about string object creation in below cases



String s=new String("A");
s=s+"B";


or



String s=new String("A");
s+"B";


or



String s=new String("A");
s=s.concat("B");


or



String s=new String("A");
s.concat("B");

How to implode newlines/break lines to a space?

How to implode newlines/break lines to a space?


given these $strings:



The quick brown
fox jumps
over the lazy
dog


imploding those strings with a blank space



$keys = implode(' ', array_keys($strings));


I have this:



The quick brownfox jumpsover the lazydog


And I'm trying to have this:



The quick brown fox jumps over the lazy dog


Any lights? Thank you.


if echo xxx -> echo xxx

This is my Code;


$output = curl_exec($ch); curl_close($ch); $temperatur = explode('T":', $output); echo substr($temperatur[1], 0, 4);


the echo substr gives me a number (e.g. 44). Is there a way in php to check if this number is under 50 and if yes, echo "blablaba".


I did something like this, but it wont work



$output = curl_exec($ch);
curl_close($ch);
$temperatur = explode('T":', $output);

$check = substr($temperatur[1], 0, 4);

if ($check < "50") {
echo "blabalabla";
}


Thank you for your help!


Overwrite a string in C

I am new to programming and I'm trying to create a code that converts a decimal into any base between 2 and 16. But I don't know how to write in a new value in my string.



void base_conversion(char s[], int x, int b) {
int j, y;
j = 0;
// your code here
while(b > 1 && b < 17) {

if (x < 0) {
x = (-x);
}else if(x == 0) {
s[j] = '\0';
}
x = (x/b);

while(x > 0) {

y = (x%b);


if (y == 10) {
s[j] = 'A';
}else if(y == 11) {
s[j] = 'B';
}else if(y == 12) {
s[j] = 'C';
}else if(y == 13) {
s[j] = 'D';
}else if(y == 14) {
s[j] = 'E';
}else if(y == 15) {
s[j] = 'F';
}else{
s[j] = y;
}
}
}j = j + 1;
}

std::string and const char *

If I use



const char * str = "Hello";


there is no memory allocation/deallocaton needed in runtime


If I use



std::string str = "Hello";


will be there an allocation via new/malloc inside string class or not? I could find it in assembly, but I am not good at reading it.


If answer is "yes, there will be malloc/new", why? Why can there be only pass through to inner const char pointer inside std::string and do actual memory allocation if I need to edit edit string?


Regex, allow white-spaces?

In Python, using regex, how would I allow a user to have either have or not have white-space in their string?


vendredi 27 février 2015

How to avoid duplicate items on a listview

I have a string array of 3 elements and i have to display it on a listView having three columns,but,before each add have to avoid duplicate addition of elements to listview.


Following is the code where i add elements to the list.



arr[0] = ip;
arr[1] = hostname;
arr[2] = macaddres;
// Logic for Ping Reply Success
ListViewItem item;
if (this.InvokeRequired)
{

this.Invoke(new Action(() =>
{

item = new ListViewItem(arr);

//**needed trick here to check for duplicate addition**
lstLocal.Items.Add(item);
int count = lstLocal.Items.Count;
toolStripStatusLabel4.Text = string.Format(count.ToString() + " Item(s)");
}
}));
}


The Containskey() and Contains()didn't work for me.


Thai string manipulation issues caused by incorrect string length

I am trying to highlight some substring in a Thai text:



high = high.Insert(myString.Index + myString.Length + "<b>" + currentLength, "</b>");


The issue is, that the myString string contains a special Thai character ("เงินฝาก"). The given string should have a length of 7, but the length is resolved as 6. Which highlights the text only partially, not including the last character.


I've tried encoding the string (both the high and myString string). But it didn't work. Do you have any tips on how to handle this? I've also tried the replace method, but to no avail.


Thanks in advance!


How do you concatenate a string with a variable/pass to link?

I'm trying to make a simple page to send IR codes to an app on my phone (OneRemoteToControlThemAll). This is how the dev of the app shows to communicate with it via html, which works 100% fine.


>"Send codes using URI "otrta://code?id=xxx" or "otrta://script?id=xxx" - use it for HTML layouts!"



<button type="button"><a href="otrta://code?id=12372">Left</a></button>


But, this only works with a pre-entered id. So, I want to have a text box with a button that when the button is clicked it sends the code entered in the box. I've looked around for different methods and tried many, none quite working. Here's my most recent attempt:



<script type="text/javascript">
function myfunction()
{
var code = "otrta://code?id=" + document.getElementById("textbox1").value;
return code;
}
</script>


html:



<input type="text" name="textbox1" Id="textbox1" style="width: 194px"/>
<button type="button" id="submit"><a href="javascript:myfunction();">Submit</a></button>


Right now on chrome on my PC this takes me to a page and outputs otrta://code?id=1234 or whatever numbers I had entered. On my phone the button does nothing. Any solutions on how to make it act the same as the others and work? It doesn't need to be perfect form, just something that will work, thanks for any help.


How to find the a certain index of a string [Python]

I am creating a program that is a hybrid of the Vigenere Cipher and the RSA Algorithm. For the code, I need to find certain indexes of a string. E.G. encrypted = '10134585588147, 3847183463814, 18517461398', where there are 3 indexes each separated by commas. Now I want to get the second index, how would I do this. This is just an example and I need to be able to get certain indexes without knowing how long the encrypted string is.


Thanks for helping.


How to slice several strings in a list?

I have a list like



my_list = ['#005', '#003', '#002']


and I'd like a list with ['005','003','002']. What I'm looking for is something like map([:1], mylist).Does it exist?


Changing endianness of hexadecimal char array

I'm using a code snippet like the following (from this question):



char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
char const byte = data[i];

string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}


It works; however, it produces a string like F0000000 (for example).


Firstly, what endianness is this?


Secondly, how could I change the code to change the endianness of the output?


Thank you very much in advance.


How do I add whitespaces between operators after reading them from text file?

I read a text file that contains strings that aren't formatted. I want to save the contents of that file then format the contents and save it into a different text file. Basically how do I change this: "intVal=15;" into this: "intVal = 15;"


note: this is for a compiler


String to Image convertion in php and store in mysql database

I want to store an image(which is passed by an android developer) into mysql database. I'm working in PHP. Plz help me someone to script php code.


Actualy I asked half question. Main problem area is that how to store image in upload folder?


Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.


//.....



Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;

String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}


}


This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!


Swing - make new line for String



  • code



    String error = "";

    if(jTextField1.getText().length == 0){
    error += "Please enter your first name.\n";
    }

    if(jTextField2.getText().length == 0){
    error += "Please enter your last name.\n";
    }

    jLabel3.setText(error);



  • From above code, my output is the following:

    Please enter your first name. Please enter your last name.




  • My expected output:

    Please enter your first name.

    Please enter your last name.




  • I also tried the following: jLabel3.setText(error + "\n");

    However, it doesn't works.




  • How do I make a new line break in string?




VB Script date formats "YYYYMMDDHHMMSS"

As title surgest I need to fomat the now () function to display on the format "YYYYMMDDHHMMSS"


I did have a play about trying to split it out but this drops leading zeros that I need to retain


example below mydt was "27/02/2015 13:02:27"



mydt = now()

MSGBOX Year(mydt)& Month(mydt)& Day(mydt)& Hour(mydt)& Minute(mydt)& second(mydt)


this returns "201522713227"


i need it to return "20150227130227" i could use a if < 10 but there must be a slicker way


JavaFX Autocomplete Curly Brackets

I am making my own text editor in JavaFX and I want to have bracket completion. Like in Netbuns. I have tried using a ChangeListener on the TextArea and checking if the last character is a bracket and append the char like this:



textArea.textProperty().addListener(new ChangeListener<String>()
{
@Override
public void changed(final ObservableValue<? extends String> observable, final String oldValue, final String newValue)
{
if (textArea.getText().charAt(textArea.getText().length()-1) == '{')
{
textArea.appendText("}");
}
}
});


But since it's only checking the last character in the textArea, this doesn't work for code where there are brackets inside brackets. Does anyone know a way to fix this? It may also be helpful to note that I am using JDK 1.7.0_55 and my school refuses to update to JDK 8. Any help will be appreciated.


String searching in Rebol or Red

While this is a real question, and one which I think applies to red as well as r2, I will confess I wouldn't mind 20 points, either.


I'm interested in search/replace operations on strings, with a mind to try to hack out a sed-like utility in rebol as a learning exercise, at least. So I imagine the utility doing a lot of searching on a lot of long strings. As a baby step/learning experience I decided to search for a character:



>> pos: index? find STR "z"
== 18
>> pos
== 18


Impressive! Rebol is so powerful!:-) Let's search for something else...



>> pos: index? find STR "n"
** Script Error: index? expected series argument of type: series port
** Where: halt-view
** Near: pos: index? find STR "n"


What? :-(



>> pos
== 18


Yeah, there was no "n" in the string I was searching. But so what, what is the benefit of an interpreter blowing up instead of doing something sensible, such as returning a testable "null" char in pos? Or, I'm sure there are other civilized ways this could be handled.


I was told I should have done this:



>> if found? find STR "z" [pos: index? find STR "z"]
== 18

>> if found? find STR "n" [pos: index? find STR "n"]
== none
>> pos
== 18


Really? I have to search the string TWICE; the first time just to be sure it is "safe" to search AGAIN? Can you imagine the laughter if the original sed had been discovered to have been implemented this senselessly?


So I have a two part question, or maybe three: (1) How would a wizard implement my search function? I presume there is a wizardly better way better than this.... (2) Is red going to fix this ...ummm...er...ahhh..."feature"? Ideally I'd think find should return a valid string position or a NULL if it hits end of string (NULL delimited, may I presume?). The NULL is FALSE so that would set up for a really easy if test. (3) What is the most CPU effective way to do a replace once I have a valid index? There appear to so many choices in rebol (a good thing) that it is possible to get stuck in choosing or stuck in a suboptimal choice. (4) I wasn't going to actually ask this, as it sounds a bit snarky, but I'm honestly curious: how could such an obviously ...ummm....er...suboptimal implementation of find go decades without being addressed?


P.S. If I don't care I don't say anything... I care about rebol and, especially, red; I would like red to get it right out of the gate and I don't think requiring a programmer to search a string TWICE, or face an ugly death, is how we want to present to the world.


How to add string value to timestamp in C# [on hold]

i have textedit1.text it has a value 2 in my winform,..and then i have timedit called timePekerjaanStart value 04:00:00 . the case is i wanna addition between textedit1 and timePekerjaanStart ,i catch the result in timestamp called timePekerjaanEnd. so , i wanna get the result timePekerjaanEnd = textedit1 + timePekerjaanStart as like 2 + 04:00:00 = 06:00:00


Simple PHP string check not working

I hate to even post this question, but I can't seem to get this to work for me. I can echo $the_page directly before the if statement, but yet the if statement always comes up "else". Any ideas? Thank you in advance.



<?php if(is_page('sp')){$the_page = 1;} else { };

if($the_page === 1) { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#form-interest option:first:contains('---')").html('Área De Interés*:');
});
</script>
<?php } else { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#form-interest option:first:contains('---')").html('Area of Interest*:');
});
</script>
<?php } ?>

String methods not working b/w utf-8 string and a java string

I am reading a file from android device using BufferedReader(new InputStreamReader(fis, "UTF-8")); and building a string using string builder. Resulting string has blank characters before every character. Thus string methods such as replace, indexof not working when used with java string. Code: String FILENAME = "sedata_file"; FileInputStream fis = null; BufferedReader d;



try {
fis = openFileInput(FILENAME);
d = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String st;
StringBuilder sb = new StringBuilder();
do {
st = d.readLine();
if (st != null) { sb.append(st); sb.append('\n'); }
} while (st != null);
completest = sb.toString();
completest.replaceAll("zap" , "nap");


Appreciate it, had lost lots of hours to this.


Java , add new string object if the length of the chain exceeds a number of character

I'm trying to add a new String in arraylist if the lenght of this one is too big.


like that;



private void createLore(String s) {
ArrayList<String> a = new ArrayList<String>();
if(s.lenght > maximumLenght) {
a.add(s /TODO new object with same string
//it's like a new line .. possible to detect a space ?
//This avoids the cut of a text


Thank's !


include once inside echo

I have two headers which I'd like to display according to account type; "a" for admin type and "b" for regular user type. I already have the enum set 'a','b'. Now, for the php after connecting to the database, I have:



<?php
while ($row = mysql_fetch_array($sql)){
$name = $row["name"];
$accounttype = $row["accounttype"];
if($accounttype == "a"){
$header = include_once "header_a.php";
}
if($accounttype == "b"){
$header = include_once "header_b.php";
}
}
?>


As for the html, I have:



<html>
<body>

<?php echo $accounttype; ?>

</body>
</html>

determine if string has unique characters

The problem asks to "implement an algorithm to determine if a string has all unique character.


I saw the solution, but don't quite understand.



public boolean isUniqueChars(String str){
if(str.length()>256) return false;
boolean[] char_set = new boolean[256];
for(int i=0; i<str,length;i++){
int val=str.charAt(i);
if(char_set[val])
return false;
char_set[val]=true;
}
return true;
}


Do we not use parseIntor(int)converter in front of the code? (str.charAt[i] will be automatically change to int?) What does boolean[] char set=new boolean[256] mean? Why do we need to set char_set[val]=true?


Ruby how to print part of the file name

I have two questions regarding Ruby.


For the below code#1, I am trying to print all the file names inside a folder, but "puts text" will gave me "/folder1/folder2/filename1.txt" for example. How can I just print just "filename1" without the directory and the .txt


number1:



Dir.glob('/folder1/folder2/*.txt').each do |text|
puts text


number2: i am trying to combine two array



a = [16,5,6,8,7]
b = [people,men,guys,boys,you]


the output will look like:



people:16, men:5, guys:6, boys:8, you:7


i converted a to string by using .to_s but i still can't combine them.


Creating a new integer with the value of another integer being added to its name

I need to try and integrate the value of a integer into the name of a new integer I need to create.


For example:



Dim integer1 As Int32 = 32


Then I create a new integer called integer+the value of integer 1 added to its name so the new integer name is integer32(so its called integer + the value of integer1).


If the question is not clear enough comment me questions on this post so I can answer them.


What is going on in this simple C code?

I am in the process of teaching myself C. I have the following code that prints a string char by char forwards and backwards:



#include<stdio.h>
#include<string.h>

main(){
char *str;
fgets(str, 100, stdin);
//printf("%i", strlen(str));
int i;

for(i = 0; i < strlen(str) - 1; i++){
printf("%c", str[i]);
}
for(i = strlen(str); i > -1; i--){
printf("%c", str[i]);
}
}


When run, it gives me the following output (assuming I typed "hello"):



cello
ollec


In addition, if I uncomment the 7th line of code, I get the following output (assuming I typed "hello"):



6 ♠


For the life of me, I cannot figure out what I am doing that is causing the first character in the output to change. In the second example, I know that the string length would be 6 because 'h' + 'e' + 'l' + 'l' + 'o' + '\0' = 6. That is fine, but where is the spade symbol coming from? Why is it only printing one of them?


It is pretty obvious to me that I have some kind of fundamental misunderstanding of what is happening under the hood here and I cant find any examples of this elsewhere. Can anyone explain what is going wrong here?


What use does the == operator have for String?

In Java, if you want to compare Strings by value you need to use the String.equals method. This leads me to my question.


Why is the == operator not overridden to do the deep comparison ? Does it actually have any uses ? Why would one compare String references ?


Edit: I am not asking what the == operator does. I am not asking how to compare Strings in Java.


I am asking what uses does the == operator have for String in Java, if any at all.


Overloading [] in subclassed C++ string

What is the proper thing for me to return here?



char BCheckString::operator[](int index)
{
if (index < 0 || this->length() <= index)
{
throw IndexOutOfBounds();
???Do I need to return something here???
}
else
{
return ?????;
}
}


I tried return this[index] but VS2013 says: "no suitable conversion function from "BCheckString" to "char" exists. And I have no idea what to return after the throw.


I have:



class BCheckString : public string
{
private:
bool checkBounds();
public:
BCheckString(string initial_string);
char operator[](int index);
class IndexOutOfBounds{};
};


and



BCheckString::BCheckString(string initial_string) : string(initial_string)
{
}

char BCheckString::operator[](int index)
{
if (index < 0 || this->length() <= index)
{
//throw IndexOutOfBounds();
cout << "index out of bounds" << endl;
return 'A';
}
else
{
return 'A';
}
}


Obviously this is homework ;)


Most Efficient Way to Replace Multiple Characters in a String

Let's say there is a string of any length, and it only contains the letters A through D:



s1 = 'ACDCADBCDBABDCBDAACDCADCDAB'


What is the most efficient/fastest way to replace every 'B' with an 'X' and every 'C' with a 'Y'.


Heres what I am doing now:



replacedString = ''
for i in s1:
if i == 'B':
replacedString += 'X'
elif i == 'C':
replacedString += 'Y'
else:
replacedString += i


This works but it is obviously not very elegant. The probelm is that I am dealing with strings that can be ones of milliions of characters long, so I need a better solution.


I can't think of a way to do this with the .replace() method. This suggests that maybe a regular expression is the way to go. Is that applicable here as well? If so what is a suitable regular expression? Is there an even faster way?


Thank you.


Get first name and last name out of a full name QString

I have a QT Project where I get the full name as a QString variable fullName from user input. I'd like to store the first name (firstName) and last name (surname) in their own QString variables by extracting them from fullName .


The user input could end up adding their middle names as well so I need to to work for all kind of examples like that, eg. user input: Barry Michael Doyle would have to give firstName the value of Barry and surname the value of Doyle.


I'm not very good at QString Manipulation as I've only recently started using the Qt Library. I'd appreciate all the help I could get.


Sending nested FormData on AJAX

I need to send some data using ajax and FormData, because I want to send a file and some other parameters. The way I usually send data is this:



$.ajax({
type: 'POST',
url: 'some_url',
dataType: 'json',
processData:false,
contentType:false,
data:{
Lvl_1-1: 'something',
Lvl_1-2: 'something',
Lvl_1-3: {
Lvl_1-3-1: "something",
Lvl_1-3-2: "something",
Lvl_1-3-3: "something",
},
},
...
});


If I don't use FormData(), I have no problem, but when using FormData(), only the data on Lvl1 is ok, but anything nested is displayed as string like this



<b>array</b> <i>(size=3)</i>
'Lvl1-1' <font color='#888a85'>=&gt;</font> <small>string</small>
<font color='#cc0000'>'Something'</font>
<i>(length=23)</i>
'Lvl1-2' <font color='#888a85'>=&gt;</font> <small>string</small>
<font color='#cc0000'>''Something''</font> <i>(length=3)</i>
'Lvl1-3' <font color='#888a85'>=&gt;</font> <small>string</small>
<font color='#cc0000'>'[object Object]'</font> <i>(length=17)</i>


If I use FormData() to encode the data inside Lvl1-3, instead of [object Object] I get [object FormData]


How do I get an array instead of string on Lvl1-3?


NOTE: If the file is on top level (Lvl_1) I can send the file with no problems using FormData(). I didn't wrote the code of the file attached because that's not the problem, nested data is. I just mentioned the file because that's why I'm using FormData().


Repeating Characters in the Middle of a String

Here is the problem I am trying to solve but having trouble solving:


Define a function called repeat_middle which receives as parameter one string (with at least one character), and it should return a new string which will have the middle character/s in the string repeated as many times as the length of the input (original) string. Notice that if the original string has an odd number of characters there is only one middle character. If, on the other hand, if the original string has an even number of characters then there will be two middle characters, and both have to be repeated (see the example).


Additionally, if there is only one middle character, then the string should be surrounded by 1 exclamation sign in each extreme . If, on the other hand, the original string has two middle characters then the output (or returned) string should have two exclamation signs at each extreme.


As an example, the following code fragment:



print repeat_middle("abMNcd")`


should produce the output:



!!MNMNMNMNMNMN!!

Looping through an array and placing something every somewhat steps into an array

So I have been busy working on an assignment lately, now I'm programming in Visual Basic, Using Visual Studio 2013 Update 4, and I'm working in the .NET Framework.


Here's my problem/question: What I want to accomplish is that I run through an array of 81 (length) consisting of only characters. I want to iterate through this array and after 9 steps of my for-loop I want to save those 9 characters into a string.


With this I mean I want to save characters 0-8 in a string, then 9-17 in another string, and so on…


(Array will be filled in my program)



Dim charactersArray(81) as character

For intIndex as integer = 0 to 81
'Add 9 characters into a string
Next


I have tried a-lot to accomplish this but have failed to find a solution yet, I have searched all over the internet but I couldn't find a solution. So hopefully anybody here can help me out. :D


(Pretty much I'm asking you to make a little algorithm for me :/ )


What is the difference between gets() and scanf()


#include <stdio.h>

int main()
{
char text[100];
int length = 0;

gets(text);

while (text[length] != '\0')
length++;

printf("%d",length);
}


I was trying to count the letters in an string using the above program. it worked. But, when i tried the same program with scanf() instead of gets(), it didn`t work. pls help me...


Escaping strings in msqli fetch assc

I've spent 16 hours easy trying to fix this code our "backend" developer wrote. I do front end, but I've inherited this. This app stores user input and then outputs it from the database. It breaks if there are single or double quotes. I'm near certain it's from this file but I cannot for the life of me figure it out and I'm at the end of my rope trying to fix it.



include('dbconx.php');

$data = json_decode($_POST['pageData']);

# find entry that matches the currently selected page and get all of its data
//$query = "SELECT * FROM pages WHERE modNum = '0' AND pageNum = '1' AND courseName = 'chum";
$query = "SELECT * FROM pages WHERE modNum = '".$data->{'modNumber'}."' AND pageNum = '".$data->{'pageNumber'}."' AND courseName = '".$data->{'course'}."'";
$result = mysqli_query($db_conx, $query) or die(mysqli_error($db));

//error is ultimately here
while($row = mysqli_fetch_assoc($result)){
// $dataDecoded = json_decode($row['pageData']);
// $dataEncoded = json_encode($dataDecoded);
// echo $dataEncoded;

$dataDecoded = json_decode(real_escape_string($row['pageData']));
$dataEncoded = json_encode($dataDecoded);
echo $dataEncoded;
}
?>

<?php
#close db link
mysqli_close($db_conx);

How do you get the numerical value from a string of digits?

I need to add certain parts of the numerical string.


for example like.


036000291453


I want to add the numbers in the odd numbered position so like


0+6+0+2+1+5 and have that equal 14.


I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.


How to give value of string to another string in matlab

I have a simple question. I want to calculate training heart rate.And I have some values. RHR means that resting heart rate. INTEN means fitnes level and I give values 0.55,0.65,0.8 for low, medium and high fitness level I wrote that code



Gender=input('Please input your gender: ');
Age=input('Please input your age: ');
RHR=input('Please enter your resting heart rate: ');
INTEN=input('Please enter your fitness level(low,medium or high): ');
male=Male;
female=Female;
low=0.55;
medium=0.65;
high=0.8;
if INTEN==0.55
INTENT=0.55;
elseif INTENT==medium
INTENT=0.65;
else
INTENT=0.8;
end
if Gender==Male
THR=((220-Age)-RHR)*INTEN+RHR;
elseif Gender==Female
THR=((206-0.88*Age)-RHR)*INTEN+RHR;
end
disp('The recommended training heart rate is ',num2str(THR))


But it gave error why?


How to strip whitespace from element in list

I read over a file, scraped all the artist names from within the file and put it all in a list. Im trying to pull out one artist only from the list, and then removing the space and shuffling all the letters (word scrabble).



artist_names = []
rand_artist = artist_names[random.randrange(len(artist_names))] #Picks random artist from list]
print(rand_artist)


howevever when i print rand_artist out, sometimes i get an artist with lets say 2 or 3 words such as "A Northern Chorus" or "The Beatles". i would like to remove the whitespace between the words and then shuffle the words.


Another Codewars Oddity

I ran across an odd thing working on a Codewars problem. Here are the instructions:



Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.


The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' '). Examples:




weirdcase( "String" )#=> returns "StRiNg"
weirdcase( "Weird string case" );#=> returns "WeIrD StRiNg CaSe"


Here's my code:



def weirdcase string

@case = []

# Ternary:
string.each_char { |c|
# string.index(c).even? ? @case.push(c.upcase) : @case.push(c.downcase)
c =~ /[[:alpha:]]/ ? (string.index(c).even? ? (@case.push(c.upcase)) : (@case.push(c.downcase))) : (string.index(c) + 1)
}

# If/Then:
# string.each_char { |c|
#if string.index(c).even? && c != " "
# if c =~ /[[:alpha:]]/ && string.index(c).even?
# then @case.push(c.upcase)
# else @case.push(c.downcase)
# end }

@case.join

end
p "TEST"
p weirdcase "this is a test"
p weirdcase "thisisatest"
p weirdcase " th is is a t es t"


The results:



"TEST"
"ThIsIsATesT"
"ThIsIsATEsT"
"tHIsIsAtest"
weirdcase
should return the correct value for multiple words
Expected: "ThIs Is A TeSt", instead got: "ThIsIsATesT"
0 Passed
1 Failed
0 Errors

Process took 171ms to complete


And here are the tests:



describe 'weirdcase' do
#it 'should return the correct value for a single word' do
# Test.assert_equals(weirdcase('This'), 'ThIs');
# Test.assert_equals(weirdcase('is'), 'Is');
#end
it 'should return the correct value for multiple words' do
Test.assert_equals(weirdcase('This is a test'), 'ThIs Is A TeSt');
end
end


I've tried writing this code a few different ways, and I keep getting the same result: instead of "ThIs Is A TeSt" for a result, I instead get "ThIsIsATesT" or some other variation where the alternating capitalization seems to fail once it reaches the word "test", which makes no sense to me - it seems to go against what the methods are supposed to do. I also tried it in irb, and saw the same result so I don't think its a Codewars bug.


I'm still relatively new at Ruby. Can anyone help me find the thing(s) I must be overlooking and/or explain how this code came to this result ?


What is the easiest way to find out character repetition in a string using JS?

I have a string consist of 7 digits, I need a function that returns "true" if the string created by repetition of just 2 digits, something like :



check('9669669'); // true
check('0000001'); // true
check('5555555'); // false
check('1111123'); // false


I want to know the easiest way. thanks.


R regex to remove all except letters, apostrophes and specified multi-character strings

Is there an R regex to remove all except letters, apostrophes and specified multi-character strings? The "specified multi-character strings" are arbitrary and of arbitrary length. Let's say "~~" & && in this case (so ~ & & should be removed but not ~~ & &&)


Here I have:



gsub("[^ a-zA-Z']", "", "I like~~cake~too&&much&now.")


Which gives:



## [1] "I like~~cake~toomuchnow"


And...



gsub("[^ a-zA-Z'~&]", "", "I like~~cake~too&&much&now.")


gives...



## "I like~~cake~too&&much&now"


How can I write an R regex to give:



"I like~~caketoo&&muchnow"


EDIT Corner cases from Casimir and BrodieG...


I'd expect this behavior:



x <- c("I like~~cake~too&&much&now.", "a~~~b", "a~~~~b", "a~~~~~b", "a~&a")

## [1] "I like~~caketoo&&muchnow." "a~~b"
## [3] "a~~~~b" "a~~~~b"
## [5] "aa"


Neither of the current approaches gives this.


Find what word appeared more than once

I have a text file, where each line is a set of comma separated words. I need to know if a word was repeated and if so, in what lines it was repeated. Example:



word1, word2, word3, word4, word5
word6, word4, word7, word8


output:



word4: 1,2


I am experimenting with a perl script which creates a map from words to line numbers as it reads the file line by line, but I was wondering if there is a simpler approach.


How to Replace Words Outside Of Quotes

I would like to replace strings outside of quotes using str.replaceAll in Java but to leave words inside quotes untouched


If I replaced Apple with Pie:


Input: Apple "Apple"

Desired Output: Pie "Apple"


Note the words inside quotes were untouched


How would this be done? All help Appreciated!


Java - add more strings via UI and include in another string

so I am creating a java application using netbeans, I currently have a jframe with some labels and text fields in, 6 to be exact, users would fill these in and then click the create button which adds them strings to another larger string that has a lot of formatting in, the second string called endform is written in BBcode for a forum, now what I am looking to do is add a button under these textfields to create another set of these labels and textfields and then where all the strings are put together in endform I need it to read the new variables the script has created. A further break down:



  • User fills in textfields 1-6

  • User creates another set of textfields and fills them in

  • App needs to include all textfields so 1-6a and 1-6b in the endtext string, however the user can add another set as many times as they want.


Thanks for your help.


split a string by the last patterns

I have some data like this:



vtab = read.table(textConnection("uid=123455,ou=usuarios,ou=gm,dc=intra,dc=planej,dc=gov,dc=de
uid=123456,ou=bsa,dc=plant,dc=gov,dc=de
uid=123457,ou=reg,ou=regfns,dc=sero,dc=gov,dc=de
uid=123458,ou=reg,ou=regbhe,dc=sero,dc=gov,dc=de
uid=123459,ou=sede,ou=regbsa,dc=sero,dc=gov,dc=de
uid=123450,ou=reg,ou=regbhe,dc=sero,dc=gov,dc=de"))


I would like split this data. Firstly split the data in two groups including just the uid= number and the third last description in dc=. Like thus:



[,1] [,2]
[1,] "123455" "plant"
[2,] "123456" "planej"
[3,] "123457" "sero"
[4,] "123458" "sero"
[5,] "123459" "sero"


Any helps are enjoyed :-)


Android:text from string array

Is it possible to set text of textview in xml from string array? (like android:text="@string/title[3]" if I want to set the third item) Or I have to do it programatically?


Thanks in advance.


Find a string and extract letter upfront to found string till another specifed string

Find a string and extract letter upfront to found string till another specifed string


Referring to the below line, I want to find the string 'Task' and print the letters upfront till next immediate (,) comma. in this case '192'



60132>, Exclusive Execution, 192 Task(s), Requested Resour


I have tried the below given way but it doesn't suits me as sometimes 'Task' string randomly changes its position in the line.



| awk -F ',' '{ print $2}' | grep -o '[0-9]\+'

is something wrong with my stringtokenizer generated array?

I'm trying to make a simple Piano sheet compiler/player, where the user feeds the program a string of piano code ex "G E F D D G...etc", which is then broken by the stringtokenizer method and stored individually in a String array called code. I've built a sheetPlayer method, which reads the array and based on multiple if statements would generate different sounds. everything seems ok but when I run the program no sound is played? and I accidentally found that if I was to directly initialize the code array ie code={"G","F"} the sound plays just find and im wondering if it's the stringtokenizer that is causing the problem?



public class PianoCompiler {

//public static Scanner reader=new Scanner(System.in);
//using input user should be able to feed the program sheet code ex"G G D E" with space in between
//and it should be store into sheetCode String
public static String sheetCode="G E G G E G A G F E D E F ";
//code Array should be able to read sheetCode String and break and store it into single letter components
public static String[] code=sheetCode.split(" ");

public static void sheetPlayer()
{
for(String key:code)
{
if(key=="G"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/g.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}
if(key=="F"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/f.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}

if(key=="E"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/e.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}

if(key=="D"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/d.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}


if(key=="C"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/c.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}
if(key=="B"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/b.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}

if(key=="A"){
try
{
String gongFile = "/Users/Raed/Music/PianoSounds/a.wav";
InputStream in = new FileInputStream(gongFile);
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
} catch(Exception e ){

}

}

try {
Thread.sleep(3000); //1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}

}
}

vbScript; how to replace spaces after certain character in string

I'm just wondering if there is a way to replace all blank spaces after a certain character in a string. Basically a string like;



str = "This is a test - 1, 2, 3, 4, 5"


I would like essentially remove all of the spaces after the '-'. I understand how to do the



replace(str," ","")


but that will remove every space, and I want to keep the 'This is a test -" intact for readability to the user. I have used



Instr(str,"-")


to get the position of that character but do not know how to then enact the replace function on the rest of the string starting from that point.


How to determine how many number of palindromes can be formed from a given string?

I have a problem where I need to find a palindrome with lowest lexicographical value from the Input string.



Sample input- Sample output-

aabcc acbca


Explanation- Out of all the palindromes cabac and acbca, acbca is lowest lexicographically.


P.S- I want to do it in java.


C++ string array and bools

im currently trying to make little recipe app. I have made a string array with 10 strings and 10 bools. When I for example type Cinnemon I want to make the _Cinnemon true. How do I do that? Also is this written correctly, or could I make it better im quite new to programming. Lastly how can I fix it so it dosent have anything to say wheter its small letters or big.


Heres the code:



std::cout << "Welcome, type your ingredients " << std::endl;
std::string ingredients[10]{"Cinnemon", "Milk", "Eggs", "Butter", "Tomatoes", "Salt", "Backing Soda", "Suggar", "Chicken", "Honny"};
bool _cinnemon, _milk, _eggs, _butter, _tomatoes, _salt, _backingSoda, _Suggar, _chicken, _honny;
std::string ingredient;
int i = -1;
while (i = -1) {
std::cin >> ingredient;
i++;
while (i < 9)
{
if (ingredient == ingredients[i]){
std::cout << "Type another if you have any more igredients else type Exit" << std::endl;
i++;
} if (ingredient == "Exit" || "exit"){
return 0;
} else{
i++;
}
}
}


Thnks in advance, sorry for the bad english my mother thoung is Norwegian


Convert String to DataGridViewTextBoxColumn using VB.Net and Access

Can't find anything on the internet, I'm thinking I'm missing something small.


I've got a list of column names in an access database, which should match DataGridViewTextBoxColumn I've created in my vb.net project. I want to use the column names in the access database to call the DataGridViewTextBoxColumn into my dgv. Sample code below:



Dim column1 As New DataGridViewTextBoxColumn
Dim column2 As New DataGridViewTextBoxColumn
Dim myheader As New DataGridViewTextBoxColumn

With column1
.Name = "column1"
.HeaderText = "Column 1"
.SortMode = DataGridViewColumnSortMode.NotSortable
.Width = 200
End With

With column2
.Name = "column2"
.HeaderText = "Column 2"
.SortMode = DataGridViewColumnSortMode.NotSortable
.Width = 400
End With

a = 0

Do While a < 2
myheader = ds.Tables("columnheadersdatabase").Rows(a).Item("J001") '//rows(a) = column1 and rows(a + 1) = column2
dgv.Columns.Add(myheader)
a += 1
Loop


the problem area is the below:



myheader = ds.Tables("columnheadersdatabase").Rows(a).Item("J001") '//rows(a) = column1 and rows(a + 1) = column2
dgv.Columns.Add(myheader)


I can seem to convert my access cell value to my DataGridViewTextBoxColumn (myheader). I tried using dim myheader as string, but that also doesn't work.


Has anybody got any ideas, any help will be much apprecated.