Okay, so my app will find the word you type into the text box from a database inside my website.. and it will find the "word" if there is more than 1 "word" it will go through each and pick a random "reply"
How can I do it so that if it can't find the word "hey" it will look for similar things like "he" etc?
Here's my PHP:
<?php
// Connect to database
mysql_connect("server", "db username", "db password");
mysql_select_db("db405677000");
// If something is received
if($_POST)
{
if($_POST['action'] == "ask")
{
// Filter it to prevent SQL injections
$text = mysql_real_escape_string($_POST['stringdata']);
// Search it on the database
$q = mysql_query("SELECT `reply` FROM `poka` WHERE `word` = '$text' ORDER BY RAND()");
// Show result
if($r = mysql_fetch_assoc($q))
echo $r['reply'];
else
echo "Cannot find a reply";
}
elseif($_POST['action'] == "teach")
{
// Filter it to prevent SQL injections
$word = mysql_real_escape_string($_POST['word']);
$answer = mysql_real_escape_string($_POST['answer']);
// Insert it to the database
if( mysql_query("INSERT INTO `poka` VALUES(NULL, '$word', '$answer')") )
echo "ok";
else
echo "fail";
}
}
?>
And here is my java part where it actually gets the response:
public void responseGet(String textRequest)
{
EditText textbox = (EditText)findViewById(R.id.chat);
textbox.setText("");
TableLayout chatbox = (TableLayout)findViewById(R.id.chatbox);
if(canReply == false)
{
TableRow tr1 = new TableRow(this);
tr1.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(this);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://monaiz.net/get.php");
String responseStr = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("stringdata", textRequest));
nameValuePairs.add(new BasicNameValuePair("action", "ask"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity( );
responseStr = EntityUtils.toString( entity ).replace("\\", "");
} catch (Exception e) {
// TODO Auto-generated catch block
}
textview.setText(responseStr);
// textview.getTextColors(R.color.)
textview.setTextColor(Color.BLACK);
textview.setGravity(Gravity.LEFT);
tr1.addView(textview);
// Convert dp to px
int padding_in_dp = 7;
final float scale = getResources().getDisplayMetrics().density;
int padding_in_px = (int) (padding_in_dp * scale + 0.5f);
tr1.setPadding(padding_in_px, 0, padding_in_px, 0);
tr1.setBackgroundResource(R.drawable.pokaspeak);
tr1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent startNewActivityOpen = new Intent(main.this, TeachmeDialog.class);
startActivityForResult(startNewActivityOpen, 0);
}
});
chatbox.addView(tr1, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
canReply = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ScrollView s = (ScrollView) findViewById(R.id.SV);
s.fullScroll(View.FOCUS_DOWN);
}
},100);
}
}
You can use PHP function called metaphone.
There is also a function called soundex that return a numerical code for a word that represents its sound. Words that sound similar will have the same soundex code. You could have a table with words and their soundex codes that you could use to look up similar sounding words. You could then sort them using their levenshtein distance
Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
In MySQL you can make use of the SOUNDEX function. You just need to change your where clause in the query from
...WHERE `word` = '$text'...
to
...WHERE soundex(word) = soundex('$text')...
or even better you can use SOUNDS LIKE operator as
...WHERE word sounds like '$text'...
Hope this helps
Related
Im trying to run some WMI queries using JACOB, and so far i've been successfull in getting the services and processes however i need to query the registry to see if a certain key is there
i've stummbled across this link
but i dont understand how to implement it
in order to query the services i've used the following code
ActiveXComponent wmi = null;
wmi = new ActiveXComponent("WbemScripting.SWbemLocator"); <-- side question what is the WbemScripting...
variantParameters[0] = new Variant("localhost");
variantParameters[1] = new Variant("root\\cimv2"); <-- what is this root?
String query = "Select ExitCode,Name,ProcessId,StartMode,State,Status from Win32_Service where State='Running' and Name='MSDTC'";
Variant vCollection = wmiconnect
.invoke("ExecQuery", new Variant(query));
is there a place with decent documentation for this?
and how to implement queries on the registry?
Thanks
UPDATE
Im trying a new implementation where i try to call the StdRegProv
and i have the following code
int HKEY_LOCAL_MACHINE = 0x80000002;
String strKeyPath = "SYSTEM\\CurrentControlSet\\Services";
String [] sNames = new String [5];
ActiveXComponent wmi = new ActiveXComponent("WbemScripting.SWbemLocator");
// no connection parameters means to connect to the local machine
Variant variantParameters[] = new Variant[4];
variantParameters[0] = new Variant("192.168.1.2");
variantParameters[1] = new Variant("root\\default");
variantParameters[2] = new Variant("admin");
variantParameters[3] = new Variant("pass");
Dispatch services = wmi.invoke("ConnectServer", variantParameters).toDispatch();
Dispatch oReg = Dispatch.call(services, "Get", "StdRegProv").toDispatch();
Variant ret = Dispatch.call(oReg, "EnumKey", HKEY_LOCAL_MACHINE, strKeyPath, sNames);
System.out.println("EnumKey: HKEY_LOCAL_MACHINE\\"+strKeyPath+"="+ret);
I was hoping to get the sNames array filled with data but its just nulls
I was unable to do it with Jacob but succeeded using j-interop library
here is the code that cost me so much suffering
IJIAuthInfo authInfo = new JIDefaultAuthInfoImpl("remoteComputerIpAddress", "wmiUserName", "wmiUserPassword");
IJIWinReg registry = null;
try {
registry = JIWinRegFactory.getSingleTon().getWinreg(authInfo, "remoteComputerIpAddress", true);
JIPolicyHandle policyHandle = registry.winreg_OpenHKLM();
JIPolicyHandle policyHandle2 = registry.winreg_OpenKey(policyHandle, "SOFTWARE\\wisemon",
IJIWinReg.KEY_ALL_ACCESS);
// JIPolicyHandle policyHandle3 =
// registry.winreg_OpenKey(policyHandle2,"wisemon",IJIWinReg.KEY_ALL_ACCESS);
System.out.println("Printing first 1000 entries under HKEY_LOCAL_MACHINE\\BCD00000000...");
for (int i = 0; i < 1; i++) {
// String[] values = registry.winreg_EnumKey(policyHandle3,i);
// Object[] values = registry.winreg_EnumValue(policyHandle3,i);
Object[] values = registry.winreg_QueryValue(policyHandle2, "name", 100);
Object[] values2 = registry.winreg_QueryValue(policyHandle2, "date", 100);
System.out.println(new String((byte[]) values[1]));
System.out.println(new String((byte[]) values2[1]));
}
} catch (UnknownHostException | JIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("Closing registry connection");
registry.closeConnection();
}
I am sending a POST request using HTMLUnit that sends keywords as parameters. An example of the URL is:
website.com/foo/bar/api?keywords=word1,word2,word3&language=en
The problem is my application is dynamically picking these words and the amount of words can go up to 10 or 20 or even more. How do you append a Set of words as values to a HTTP request. My code at the moment is:
requestSettings = new WebRequest(new URL("website.com/foo/bar/api?"),
HttpMethod.POST);
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
requestSettings.getRequestParameters()
.add(new NameValuePair("keywords[]", itr.next()));
}
requestSettings.getRequestParameters().add(new NameValuePair("language", "en"));
System.out.println(requestSettings.getUrl().toString());
response = webClient.getPage(requestSettings).getWebResponse();
This code does not return a valid respone. What am I doing wrong here?
Give this a try:
using (var client = new WebClient())
{
var dataObject = new {
KeyWords = "one, two, three"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataObject);
var response = client.UploadString("yourUrl", json);
}
I am developing an android app to create a new Quote in vTiger(ver 5.4) CRM server.
I was able to generate the new quote but the product_id and quantity that I sent for addition in quote details were not added in it. The other details are being shown in the new quote except the list of products, their quantities and pricing.
I have also studied the vTiger webservices tutorial but it was not helpful in this case.
I found an accepted answer of similar question but it is in php not in Android/JAVA.
This is how I am sending the details required to create a new quote in vTiger server.:-
try {
objectJson.put("subject", subject);
objectJson.put("account_id", accountId);
objectJson.put("bill_street", address);
objectJson.put("assigned_user_id", "19x1");
objectJson.put("conversion_rate", "1.000");
objectJson.put("currency_id", "21x1");
objectJson.put("hdnTaxType", "group");
objectJson.put("productid", productId);
objectJson.put("quantity", quantity);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("element", "UTF-8") + "="
+ URLEncoder.encode(objectJson.toString(), "ISO-8859-1");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8"); //moduleName='Quotes'
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=create");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
}
catch(Exception ex)
{
}
The above code helps me to generate the quote without product details.
After studying the above mentioned php answer, I changed the URL that I was using in my code to this:- http://vtiger_url/webservice.php?total=23000&operation=create. This helped me to add the total amount to the newly created quote but I wasn't successful to add rest of the details using this method.
The answer you have found seems to be suitable, even if it's a php solution. The problem you descirbed:
I have tried this too but unfortunately I am not able to access Inventoryproductrel table.
maybe already indicates a lack of proper authentication or missing privileges. So my suggestion is to
Find out why you can't access the table Inventoryproductrel. Try to access that table using your authentication privileges (sessionID), examine the response for any hints and try to solve the table isn't accessible issue.
Finally follow the suggestions from this answer.
Just another hint. If you can successfully access that table via you web browser, than I would sniff the request and have a look at the http parameters and their values. Based on those findings you can modify your request.
Always consider, the web browser can only do the same as you android application.
These lines were added in existing code:-
JSONArray pdoInformation = new JSONArray();
try{
// Added these lines in try block to send product details
for(int i=0; i<productIds.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productIds.get(i) );
obj.put("qty", quantities.get(i));
obj.put("listprice", listprices.get(i));
pdoInformation.put(obj);
}
objectJson.put("pdoInformation", pdoInformation);
}
Here product details were needed to be sent in a JSONArray with name as "pdoInformation".
for loop is used to send multiple product details.
Here productIds, quantities and listprices are three mandatory product details stored as ArrayList.
Why don't you use the web service to create products as well? That should be supported as per the documentation.
Once you create the products and get their ids, you can create a quote object that includes these ids. The objects and their fields are not very well documented for the rest APIs, so you could use the query/describe APIs to get as much information as possible about what data needs to be supplied for creating the different objects.
From the description of the Quotes module, you would need to include item_details which will contain the product and quantity information. The exact field name and format can be obtained by the describe API as described in the web service documentation
To get a description of the vTiger objects
String modeleName = "Quotes"; //Use Products if you want a description of the Products module
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=describeobject");
// Send GET data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
} catch(Exception ex) {
}
Note that it's pretty much the same as what you are doing, only the url & parameters are different, and the request type is GET instead of POST
To create a product, you would follow the same procedure as you did for the quote, only the url and parameters would be different
#help as far i understand your question is how to send JsonObject with data to specified Server is that correct ? if it is the correct then i suggest you to use Volley library for networking and here are many examples that may useful to you .http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ and http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Just go through it. It provides easiest way to perform networking operations and also cancellation of request is also possible with this library.
Sample Code:
final String URL = "SERVER_URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
Using this code you can send your data to your server and at server side you can use php code to receive this jsondata and parse it.
Thanks.
I'm pretty new to Django and Japplet, this is my first project with them.
The Japplet takes some images from the django static folder, and permits the user to add some lines and markers.
At the end of this, when the button "save" on the JApplet is clicked, it should do some POST call to the Django server, to save the markes and lines.
Actually I'm only testing with markers, and I can't get it done.
Here is the Model of a marker:
class Point(models.Model):
id_edificio = models.ForeignKey(Building)
RFID = models.CharField(max_length=200)
x = models.IntegerField()
y = models.IntegerField()
piano = models.IntegerField()
ingresso = models.BooleanField()
His View:
def point(request, id_edificio, RFID, x, y, piano):
point = csrf_exempt(point)
if request.method == 'POST':
get_object_or_404(Building, pk=id_edificio)
p = Point()
p.id_edificio = id_edificio
p.RFID = RFID
p.x = x
p.y= y
p.piano = piano
p.ingresso = True
p.save()
I haven't implemented a template, because I don't need access to this view with web browser.
Urls:
url(r'^buildings/generate/point', 'buildings.views.point'),
JApplet save method:
private void saveData(MarkerArrayList markers, PathArrayList paths) {
String response;
URL endpoint = null;
try {
endpoint = new URL("http://127.0.0.1:8000/buildings/generate/point");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
for(Marker m: markers) {
Reader data = new StringReader("id_edificio="+id_building+"&"+m.toString());
try {
Post.postData(data, endpoint);
} catch (Exception e) {e.printStackTrace();}
}
}
Marker toString() method:
public String toString() {
return "RFID="+ RFID + "&" +
"x=" +
"y=" + y + "&" +
"piano=" + floor + "&";
}
I assume that my java method Post is correct. If you want to see it, ask me ;)
Error from Django server on POST:
[28/Sep/2012 07:21:46] "POST /buildings/generate/point HTTP/1.1" 403 2294
I don't know wath to try know, I'm in your hands.
Tahnk you
The number of errors was totally incredible.
So this is the new View for markers, for now I will ignore csrf token:
#csrf_exempt
def point(request):
if request.method == 'POST':
p = Point()
building = Building.objects.get(pk = request.POST["id_edificio"])
p.id_edificio = building
p.RFID = request.POST["RFID"]
p.x = request.POST["x"]
p.y= request.POST["y"]
p.piano = request.POST["piano"]
p.ingresso = request.POST["ingresso"]
p.save()
And it works! There was also minor errors in Marker toString() method (as 'X' instead of 'x'), but they were only minor errors.
So I am writing an Android application, and part of it is supposed to use GPS to acquire longitude/latitude. And those values are supposed to post to a PHP server I also have running. The function I have posting is as follows:
public void doAll() {
Double locLat, locLon;
try {
locLat = locManager.getLastKnownLocation(locProvider).getLatitude();
locLon = locManager.getLastKnownLocation(locProvider).getLongitude();
} catch (NullPointerException e) {
locLat = -1.0;
locLon = -1.0;
}
try {
HttpClient client = new DefaultHttpClient();
//we put all the parameters in the URL itself
HttpPost request = new HttpPost("http://fatalatour.com/database.php?function=get_all&latitude="+Double.toString(locLat)+"&longitude="+Double.toString(locLon));
ResponseHandler <String> responseHandler = new BasicResponseHandler();
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(locLat)));
//nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(locLon)));
//request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = client.execute(request, responseHandler);
Log.i("HOMI_RESPONSE", response.toString());
}
There is other code withing that but I believe that is all that actually affects the posting of locLat and locLon.
For the server end I have:
function get_all() {
$lat = trim($_GET['latitude']);
$lon = trim($_GET['longitude']);
// DEBUG
$f = fopen('debug.log', 'a');
fprintf($f, 'get_all: '.print_r($_REQUEST, true)."\n");
$result = mysql_query("SELECT * FROM homi_table");
$num = 0; //# of homicides
while ($row = mysql_fetch_assoc($result)) {
$d = distance($row['latitude'], $row['longitude'], $lat, $lon, "K");
if ($d < 100) { //number to change for distance filter
$num += 1;
echo "fatality:".$row['slug']."~".strtoupper($row['name']).", Age ".$row['age']."\n".$row['date']."\nhttp://projects.latimes.com/homicide/post/".$row['slug']."~".$row['latitude']."~".$row['longitude'];
// GH: limiting the number of results to 100
if ($num == 100) {
break;
}
}
};
echo $num;
fprintf($f, "get_all: returning: ".$num."\n");
}
Right now the issue seems to be the handling of $lat and $lon. When i hard code in a static number for each of those in the PHP the app works, yet when I leave it variable (as it should be), it fails. Any help would be greatly appreciated!
In Android application you are using POST request, in PHP you read GET parameters. Nothing else come to my mind.
The URL you've constructed looks like an HTTP Get, not a Post. Post would have the data being posted in the body of the request.
If you don't mind the parameters being exposed in the URL, I would simply change HTTPPost to HTTPGet in the Android code. If you don't want that stuff to be in the URL, you'll have to rework the Android post a little bit (something similar to your commented out code I believe) and change the php code to access the $_POST variable instead.