sending cyrillic text from flash as2 to database - character-encoding

I have a really big problem with saving data from Flash as2 to database. I tried solved it myself, read many topics on different forums but no result.
I have an Input Text field (mess_txt) in as2 project and Send button with the next code:
on(release){
var formData = new LoadVars();
formData.etext = mess_txt.text;
formData.sendAndLoad("sendmail.php", formData, "POST");
formData.onLoad = function(){
// receive actions...
}
}
Code in sendmail.php:
include("connect.php");
$text = $_POST['etext'];
$text = str_replace("\r", "<br/>", trim(strip_tags($text)));
$text = str_replace("\n", "", $text);
$text = str_replace("\"", """, $text);
$text = str_replace("'", "'", $text);
$query = "insert into reviews (text, status) values ('".$text."', 'new')";
mysql_query($query) or die (mysql_error());
mail("mail#gmail.com", "Title!", "Message text: ".$text);
When I use latin symbols both code works well but when I input cyrillic symbols in Input Text I have an empty string in PHP code.
In Input Text I use _self font and embed all glyphs. But I think that problem is in sending data because when send simple cyrillic string instead mess_txt.text I have an empty string as well.
Interesting, that when I used mb_detect_encoding($_POST['etext']) in PHP code I obtained ASCII not UTF
Please, help me!!!!
SOLVED!!!
I found how to solve this problem! May be it will be interesting for someone else...
Before sending data from as2 to php I transformed it from text to unicode codes. This is my function in as2 project:
on(release){
var txt = getRealText(mess_txt.text);
var formData = new LoadVars();
formData.etext = txt;
formData.sendAndLoad("sendmail.php", formData, "POST");
formData.onLoad = function(){
// receive actions...
}
function getRealText(str){
var newStr = "";
for(i=0, s=str.length; i<s; i++){
newStr += "&#"+ord(str.charAt(i))+";";
}
return newStr;
}
}
As result I sending string "тест" instead "тест".
In PHP file I received this string:
$text = html_entity_decode($_POST['etext'], ENT_NOQUOTES, 'UTF-8');
After that I obtained normal cyrillic (or any another) text.
Have a hope that this will be useful for someone!

Related

Replacing certain characters with other characters

I'm trying to set up my first discord bot to be able to replace certain letters with other letters, but I am extremely new to coding in javascript.
function debunkCommand(arguments, recievedMessage) {
if (arguments.length > 0) {
function strReplace(){
var myStr = argument;
var newStr = myStr.replace(/l/gi, "w");
var newStr = myStr.replace(/r/gi, "w");
receivedMessage.channel.send(newStr)
}
} else {
receivedMessage.channel.send("that's impossible to debunk")
}
}
expected to be able to write "!debunk hello" and have the bot send back a message saying "hewwo"
function debunkCommand(args, receivedMessage) {
if (args.length) {
/*
arguments is an array of strings, doing 'arguments.join(" ")' will join these strings into one
/[lr]+/gi will match any instances of 'l' or 'r'
it's also a good idea to rename your "arguments" parameter to "args", since "arguments" is already a standart js object
*/
receivedMessage.channel.send(args.join(" ").replace(/[lr]+/gi, "w"));
} else {
receivedMessage.channel.send("that's impossible to debunk");
};
};

How to create an "Open in Google Sheets" button

I already have an "export to CSV" button on my site. But I'd like to have an "Open in Google Sheets" button, which opens the CSV directly into Google Sheets.
That'll save the user a few steps, so they will no longer have to (1) download the CSV, and (2) import it into Google Sheets.
Any way to do this?
If you wanted to avoid the full API . . .
Use Google Script to import the CSV into a Google Sheet and set the script trigger to run on a sensible schedule (every, minute, hour, day etc.).
//adapted from http://stackoverflow.com/a/26858202/3390935
function importData() {
var ss = SpreadsheetApp.getActive();
var url = 'HTTP://YOURURL.COM/FILE.CSV';
var file = UrlFetchApp.fetch(url); // get feed
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
var sheet = ss.getActiveSheet();
// loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
};
// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
};
Make that sheet public and append /copy to the URL.
https://docs.google.com/spreadsheets/d/YOURGDOCID/copy
You can use the Google Sheets API.
This link provides guides for several programming languages, references, samples, etc. https://developers.google.com/sheets/
Good luck.

Writing a string to disk without any character conversion in Groovy

I have a String object, now because it comes a diff of a folder containing different file types, not everything in it is encoded in the same character set.
The correct codes are in the string, but whenever I try to access the string, groovy tries to be helpful and decode the string, which messes things up.
Now the following seems to do what I need
String decoded_diff = "String that contains codes from different character encodings"
patch_file_name = 'changes.patch'
patch_file = new File(pwd(), patch_file_name)
patch_file.delete()
max_block_size = 1024 * 1024
char[] char_buffer = new char[max_block_size]
block_start = 0
patch_length = decoded_diff.length()
while (true) {
block_size = Math.min(patch_length - block_start, max_block_size)
decoded_diff.getChars(block_start, block_start + block_size, char_buffer, 0)
block_start += block_size
byte[] byte_buffer = new byte[block_size]
for (int i = 0; i < block_size; i++) {
byte_buffer[i] = (int) char_buffer[i]
}
patch_file.append(byte_buffer)
if (block_start == patch_length) break
}
However, it is sloooow
Is there a faster way to achieve the same thing? The final patch file must be identical to the original diff to work. Unfortunately I can't send the file itself (jenkins currently doesn't support file parameters in pipeline jobs) so I have to escape it and send it as part of a json parameter list, hence this painful rigmarole on the receiving end.
Why not:
String decoded_diff = "String that contains codes from different character encodings"
patch_file_name = 'changes.patch'
patch_file = new File(pwd(), patch_file_name)
patch_file.delete()
patchFile.withOutputStream { os ->
os << decoded_diff.bytes
}

Avoiding formatting of DOORS object text using DXL

I am writing DXL script in which few object text has borders(like one complete row of table is copied).
I have to emphasize the "shall" word in shall.
But using findPlainText() method, it changes the formatting of object text which have borders.
Initially the objects before scripts run is:
After running the script to make "shall" word Bold, i wrote DXL script:
void Change_Shall(Object o, string objText)
{
int off=0
int len=0
string StartUpperText = ""
string FontText = ""
string StartText = ""
string FindText = ""
bool IsChanged = false
string OriginalObjText = objText
string UpperFontObjText = upper(objText)
while (findPlainText(UpperFontObjText, "SHALL", off, len, true, false))
{
StartUpperText = UpperFontObjText[0:off-1]
UpperFontObjText = UpperFontObjText[off+len:]
FindText = OriginalObjText[off:off+len-1]
StartText = OriginalObjText[0:off-1]
OriginalObjText = OriginalObjText[off+len:]
if(FontText == "")
FontText = StartText "{\\b " FindText "}"
else
FontText = FontText StartText "{\\b " FindText "}"
//print FindText "\t\t" UpperFontObjText "\n"
IsChanged = true
off = 0
len = 0
}
if(IsChanged == true)
o."Object Text" = richText FontText OriginalObjText
}
The object text with border after this script runs get changes like
How can formatting of object text with borders be avoided and border is preserved in the object text.
I'm not sure how you're getting "Object Text" from Object o, but my guess is you're using o."Object Text" "" to cast it as a string. Is that right?
If so, then that is stripping all the rich text (including your borders) before you do anything to it. Try using string objText = richTextWithOle o."Object Text", or string objText = richText o."Object Text", and then try removing the unnecessary parameter to your function string objText, as a reference to this already comes along with Object o
I'm assuming based on how your table looks that it is a RichText table, in which case I believe your code will still work, it's just that I suspect you're starting with a string stripped of richText and adding richtext to it. Sometimes Word OLE objects with tables can look like that too, in which case you'd have to use COM to manipulate the OLE.
Hope this helps.

Using the Blackberry JSON parser, how do I parse out "[" from string?

I'm using the JSON library floating around for Blackberry and following this answer in "How to parse the JSON response in Blackberry/J2ME?".
The problem I'm having is that I'm getting an error saying JSONObject has to begin with a "{". My JSON string is wrapped in [ ] , which is something the web service does.
Libraries I've used for Android and iPhone stripped that, so I was wondering what is the best way around this problem? I don't think I can just parse out all [ ] because I think those are used in multidimensional JSON strings.
Edit:
Here's an example:
[{"nid":"1","title":"test","image":"m0.jpg","by":"Presented by","by_name":"Inc.","summary":"..."}, {"nid":"6","title":"A","image":".jp[0.0] g","by":"Presented by","by_name":"Theatre","summary":""}]
If you are not sure about the validity of JSON data then use any JSON Validator, e.g. JSONLint.
And you have some unwanted character in your data, i.e. [, and ] in "image":".jp[0.0] g". I think those data are added by Eclipse while printing on console.
Data provided in example isn't represent a JSONObject, butit is an array. So start with constructing a JSONArray from the data and do the parsing. Below is an example code snippet (with modified data set):
String strJSONData = "[{\"nid\":\"1\",\"title\":\"test\"},{\"nid\":\"6\",\"title\":\"A\"}]";
final String CONS_NID = "nid";
final String CONS_TITLE = "title";
try {
JSONArray ja = new JSONArray(strJSONData);
if (ja != null) {
JSONObject arrObj;
for (int i = 0; i < ja.length(); i++) {
arrObj = (JSONObject) ja.get(i);
if (arrObj.has(CONS_NID)) {
System.out.println("ID: " + arrObj.getString(CONS_NID));
}
if (arrObj.has(CONS_TITLE)) {
System.out.println("Title: " + arrObj.getString(CONS_TITLE));
}
}
arrObj = null;
}
ja = null;
} catch (Exception exc) {
}
strJSONData = null;
If you know it is starting and ending with '[' and ']', then you can just check that, and take the substring in between and hand it to the parser.
String myJsonString = ...;
if(myJsonString.charAt(0) == '[' && myJsonString.charAt(myJsonString.length() - 1) == ']') {
realJsonParse(myJsonString.substring(1, myJsonString.length() - 1);
}

Resources