Unreachable code - unreachable-code

public void onClick(View v) {
String uname=tv1.getText().toString();
String pass=tv2.getText().toString();
//String copmare=uname.concat(pass);
Cursor cur = db.query("accountTable", // Where are we looking?
new String[]{ "colProject" }, // What do we want back?
"colName = ? AND colPass = ?", // What are we matching?
new String[]{ uname, pass }, // What to put in the "holes"?
null, null, null); // Everything else default...
if (cur != null) {
cur.moveToNext();
}
return;
Intent i = new Intent(FirstAssignmentActivity.this,success.class);
i.putExtra("v1", cur.getString(0));
startActivity(i);
}
Why do I have unreachable code?

You write return ;, so control will exit the function at that point and not reach the final 3 lines of the function (Intent i, etc)

You are returning from the method. None of the code after that will execute.
if (cur != null) {
cur.moveToNext();
}
return; // AFTER THIS NOTHING WILL EXECUTE

Related

Wikipedia page parsing program caught in endless graph cycle

My program is caught in a cycle that never ends, and I can't see how it get into this trap, or how to avoid it.
It's parsing Wikipedia data and I think it's just following a connected component around and around.
Maybe I can store the pages I've visited already in a set and if a page is in that set I won't go back to it?
This is my project, its quite small, only three short classes.
This is a link to the data it generates, I stopped it short, otherwise it would have gone on and on.
This is the laughably small toy input that generated that mess.
It's the same project I was working on when I asked this question.
What follows is the entirety of the code.
The main class:
public static void main(String[] args) throws Exception
{
String name_list_file = "/home/matthias/Workbench/SUTD/nytimes_corpus/NYTimesCorpus/2005/01/02/test/people_test.txt";
String single_name;
try (
// read in the original file, list of names, w/e
InputStream stream_for_name_list_file = new FileInputStream( name_list_file );
InputStreamReader stream_reader = new InputStreamReader( stream_for_name_list_file , Charset.forName("UTF-8"));
BufferedReader line_reader = new BufferedReader( stream_reader );
)
{
while (( single_name = line_reader.readLine() ) != null)
{
//replace this by a URL encoder
//String associated_alias = single_name.replace(' ', '+');
String associated_alias = URLEncoder.encode( single_name , "UTF-8");
String platonic_key = single_name;
System.out.println("now processing: " + platonic_key);
Wikidata_Q_Reader.getQ( platonic_key, associated_alias );
}
}
//print the struc
Wikidata_Q_Reader.print_data();
}
The Wikipedia reader / value grabber:
static Map<String, HashSet<String> > q_valMap = new HashMap<String, HashSet<String> >();
//public static String[] getQ(String variable_entity) throws Exception
public static void getQ( String platonic_key, String associated_alias ) throws Exception
{
//get the corresponding wikidata page
//check the validity of the URL
String URL_czech = "https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=" + associated_alias + "&submit=Search";
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException e)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
BufferedReader wiki_data_pagecontent = new BufferedReader(
new InputStreamReader(
wikiInputStream ));
String line_by_line;
while ((line_by_line = wiki_data_pagecontent.readLine()) != null)
{
// if we can determine it's a disambig page we need to send it off to get all
// the possible senses in which it can be used.
Pattern disambig_pattern = Pattern.compile("<div class=\"wikibase-entitytermsview-heading-description \">Wikipedia disambiguation page</div>");
Matcher disambig_indicator = disambig_pattern.matcher(line_by_line);
if (disambig_indicator.matches())
{
//off to get the different usages
Wikipedia_Disambig_Fetcher.all_possibilities( platonic_key, associated_alias );
}
else
{
//get the Q value off the page by matching
Pattern q_page_pattern = Pattern.compile("<!-- wikibase-toolbar --><span class=\"wikibase-toolbar-container\"><span class=\"wikibase-toolbar-item " +
"wikibase-toolbar \">\\[<span class=\"wikibase-toolbar-item wikibase-toolbar-button wikibase-toolbar-button-edit\"><a " +
"href=\"/wiki/Special:SetSiteLink/(.*?)\">edit</a></span>\\]</span></span>");
Matcher match_Q_component = q_page_pattern.matcher(line_by_line);
if ( match_Q_component.matches() )
{
String Q = match_Q_component.group(1);
// 'Q' should be appended to an array, since each entity can hold multiple
// Q values on that basis of disambig
put_to_hash( platonic_key, Q );
}
}
}
wiki_data_pagecontent.close();
// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
for (Map.Entry<String, HashSet<String> > entry : q_valMap.entrySet())
{
System.out.println(entry.getKey()+" : " + Arrays.deepToString(q_valMap.entrySet().toArray()) );
}
}
// add Q values to their arrayList in the hash map at the index of the appropriate entity
public static HashSet<String> put_to_hash(String key, String value )
{
HashSet<String> valSet;
if (q_valMap.containsKey(key)) {
valSet = q_valMap.get(key);
} else {
valSet = new HashSet<String>();
q_valMap.put(key, valSet);
}
valSet.add(value);
return valSet;
}
// add Q values to their arrayList in the hash map at the index of the appropriate entity
public static void print_data()
{
System.out.println("THIS IS THE FINAL DATA SET!!!");
// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
for (Map.Entry<String, HashSet<String> > entry : q_valMap.entrySet())
{
System.out.println(entry.getKey()+" : " + Arrays.deepToString(q_valMap.entrySet().toArray()) );
}
}
Dealing with disambiguation pages:
public static void all_possibilities( String platonic_key, String associated_alias ) throws Exception
{
System.out.println("this is a disambig page");
//if it's a disambig page we know we can go right to the Wikipedia
//get it's normal wiki disambig page
String URL_czech = "https://en.wikipedia.org/wiki/" + associated_alias;
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException e)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
// parse the input stream using Jsoup
Document docx = Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");
//this can handle the less structured ones.
Elements linx = docx.select( "p:contains(" + associated_alias + ") ~ ul a:eq(0)" );
for (Element linq : linx)
{
System.out.println(linq.text());
String linq_nospace = URLEncoder.encode( linq.text() , "UTF-8");
Wikidata_Q_Reader.getQ( platonic_key, linq_nospace );
}
}

HTTP upload using WinInet

I'm doing http(PUT) upload using WinInet library, on WinXP its working fine but on Win7 its not working and the strange thing is 'InterWriteFile' function of WinInet files is returning true. Any help will be appreciated.
Thanks in Advance.
//this is the first function that is called when upload is requested.
void Upload()
{
//check if handle is already open or not
if(!m_hNetOpen)
{
//open interconnect: Initializes an application's use of the WinINet functions.
m_hNetOpen = InternetOpen("XYZ",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
INTERNET_INVALID_PORT_NUMBER);
//return if handle is NULL
if(m_hNetOpen == NULL)
{
return FALSE;
}
}
//we'll get user specified URL, could be some xyz.com too.
if(!m_hNetConnect)
{
//opens HTTP or FTP connection for a site requested...pchServerName requested
m_hNetConnect = InternetConnect(m_hNetOpen,
strServerName,
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
INTERNET_FLAG_PASSIVE,
dwContext);
//return if handle is NULL
if(m_hNetConnect == NULL)
{
return FALSE;
}
}
dwContext = 0;
//now, create HTTP request
m_hHttpConnect = HttpOpenRequest(m_hNetConnect,
"PUT",
strObjectName,
NULL,
NULL,
NULL,
INTERNET_FLAG_CACHE_IF_NET_FAIL,
dwContext);
//return if handle is NULL
if(m_hHttpConnect == NULL)
{
return FALSE;
}
//call UseHttpSendReqEx
BOOL bRet = UseHttpSendReqEx(m_hHttpConnect, strUploadFileName);
//if not suuceeded log the message
if(!bRet)
{
//Logmessage
}
if(m_hHttpConnect)
{
//close the handle
InternetCloseHandle(m_hHttpConnect);
}
return bRet;
}
//this function is will send HTTP request and writes data to internetfile
BOOL UseHttpSendReqEx(HINTERNET hConnect, char *upFile)
{
INTERNET_BUFFERS BufferIn = {0};
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
//buffer
BYTE strBuffer[20480] = {0};
BOOL bRead;
BOOL bRet = TRUE;
//get the size of structure
BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
//create file
m_hFile = CreateFile(upFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//check for invalid handle
if (m_hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
//get the file size
BufferIn.dwBufferTotal = GetFileSize(m_hFile, NULL);
//send request to HTTP server
if(!HttpSendRequestEx(hConnect, &BufferIn, NULL, HSR_INITIATE, 0))
{
//close the file handle
CloseHandle(m_hFile);
m_hFile = NULL;
return FALSE;
}
DWORD sum = 0;
do
{
//read the file that is to be uploaded
if (!(bRead = ReadFile(m_hFile, strBuffer, sizeof(strBuffer),
&dwBytesRead, NULL)))
{
bRet = FALSE;
break;
}
//write the internet file
bRet=InternetWriteFile(hConnect, strBuffer, dwBytesRead,
&dwBytesWritten);
if(!bRet)
{
DWORD d = GetLastError();
bRet = FALSE;
break;
}
memset(strBuffer, '\0', sizeof(strBuffer));
sum += dwBytesWritten;
}
while(dwBytesRead == sizeof(strBuffer)) ;
//This sleep was introduced as if we immediately after the above loop
//if we try to close the handle then file does not get created on the server
Sleep(100);
BOOL b = CloseHandle(m_hFile);
m_hFile = NULL;
return bRet;
}

How to solve this java.lang.NullPointerException

Hi I'm new to android programming, and i don't know or i really can't figure out why do i get this error message after i click the button on the app that i created
java.lang.NullPointerException at
com.example.dailydoseofhappiness.MainActivity.searchRecord(MainActivity.java:62)
at
com.example.dailydoseofhappiness.MainActivity.searchRecord(MainActivity.java:52)
here is the code fragment.
public void onClick(View arg){
if(arg.getId()==R.id.btnfortune){ //this is line 52
searchRecord(count);
}
}
public void searchRecord(int count)
throws SQLException
{
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"}; // this is line 62
rsCursor = dbm.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if(rsCursor.isAfterLast()==false){
lblmessageS.setText(rsCursor.getString(0));
}
rsCursor.close();
}
can anyone check this code fragment if whats wrong thank you very much
Try this searchRecord method. I added some silly checks so if any variable is null it will warn you:
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"}; // this is line 62
if (dbm == null)
throw new Exception("dbm object is null");
if (dbm.dbase == null)
throw new Exception("dbm.dbase is null");
rsCursor = dbm.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
if (rsCursor == null)
throw new Exception("rsCursor is null");
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
if (lblmessageS == null)
throw new Exception("lblmessageS is null");
lblmessageS.setText(rsCursor.getString(0));
}
rsCursor.close();
}

How significant is the benefit of checking IsClientScriptIncludeRegistered?

How significant is the benefit of checking IsClientScriptIncludeRegistered before RegisterClientScriptInclude?
From an example in the documentation:
' Check to see if the include script is already registered.
If (Not cs.IsClientScriptIncludeRegistered(cstype, csname)) Then
cs.RegisterClientScriptInclude(cstype, csname, ResolveClientUrl(csurl))
End If
Which states:
Note that if the logic to check for the existing client script include
were removed, there would still not be duplicate client scripts in the
rendered page because the RegisterClientScriptInclude method checks
for duplicates. The benefit of checking is to reduce unnecessary
computation.
I'm wondering about the highlighted sentence. What unnecessary computation?
To me it seems the other way around. Using IsClientScriptIncludeRegistered before RegisterClientScriptInclude should/would check for the registered script two times (thus added unnecessary computation instead of reduced).
What am I missing here?
The IsClientScriptIncludeRegistered is simple check in Dictionary if the script all ready register, is a very fast check, with out many code.
public bool IsClientScriptIncludeRegistered(Type type, string key)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return ((this._registeredClientScriptBlocks != null) &&
this._registeredClientScriptBlocks.Contains(
CreateScriptIncludeKey(type, key, false)));
}
The RegisterClientScriptInclude from the other hand, contains a little more code until is reach the check of the existing.
internal void RegisterClientScriptInclude(Control control, Type type, string key, string url)
{
IScriptManager scriptManager = this._owner.ScriptManager;
if ((scriptManager != null) && scriptManager.SupportsPartialRendering)
{
scriptManager.RegisterClientScriptInclude(control, type, key, url);
}
else
{
this.RegisterClientScriptInclude(type, key, url);
}
}
internal void RegisterClientScriptInclude(Type type, string key, string url, bool isResource)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (string.IsNullOrEmpty(url))
{
throw ExceptionUtil.ParameterNullOrEmpty("url");
}
string script = "\r\n<script src=\"" + HttpUtility.HtmlAttributeEncode(url) + "\" type=\"text/javascript\"></script>";
this.RegisterScriptBlock(CreateScriptIncludeKey(type, key, isResource), script, ClientAPIRegisterType.ClientScriptBlocks);
}
internal void RegisterScriptBlock(ScriptKey key, string script, ClientAPIRegisterType type)
{
switch (type)
{
case ClientAPIRegisterType.ClientScriptBlocks:
this.RegisterScriptBlock(key, script, ref this._registeredClientScriptBlocks, ref this._clientScriptBlocks, false);
break;
case ClientAPIRegisterType.ClientScriptBlocksWithoutTags:
this.RegisterScriptBlock(key, script, ref this._registeredClientScriptBlocks, ref this._clientScriptBlocks, true);
break;
case ClientAPIRegisterType.ClientStartupScripts:
this.RegisterScriptBlock(key, script, ref this._registeredClientStartupScripts, ref this._clientStartupScripts, false);
break;
case ClientAPIRegisterType.ClientStartupScriptsWithoutTags:
this.RegisterScriptBlock(key, script, ref this._registeredClientStartupScripts, ref this._clientStartupScripts, true);
break;
}
if (this._owner.PartialCachingControlStack != null)
{
foreach (BasePartialCachingControl control in this._owner.PartialCachingControlStack)
{
control.RegisterScriptBlock(type, key, script);
}
}
}
private void RegisterScriptBlock(ScriptKey key, string script, ref ListDictionary scriptBlocks, ref ArrayList scriptList, bool needsScriptTags)
{
if (scriptBlocks == null)
{
scriptBlocks = new ListDictionary();
scriptList = new ArrayList();
}
if (!scriptBlocks.Contains(key))
{
Tuple<ScriptKey, string, bool> tuple = new Tuple<ScriptKey, string, bool>(key, script, needsScriptTags);
scriptBlocks.Add(key, null);
scriptList.Add(tuple);
}
}

How do i delete or edit an Facebook Event?

i've googling all day , and is this event supported ? anyways, here is my code :
public bool updateEvents(String eventID, EventList toUpdate){
bool success = false;
if (String.IsNullOrWhiteSpace(eventID) != false && toUpdate != null)
{
Dictionary<String, String> eventInit = new Dictionary<string, string>();
DateTime start = DateTime.Parse(toUpdate.StartTime);
String startTime = start.ToString("s");
start = DateTime.Parse(toUpdate.EndTime);
String endTime = start.ToString("s");
eventInit.Add("name", toUpdate.EventName);
eventInit.Add("description", toUpdate.Description);
eventInit.Add("start_time", startTime);
eventInit.Add("end_time", endTime);
eventInit.Add("location", toUpdate.Location);
JSONObject js = api.Post(" https://graph.facebook.com/" + eventID, eventInit);
if (String.IsNullOrEmpty(js.Dictionary["ID"].String) == false)
{
success = true;
}
}
return success;
}
public bool deleteEvents(String eventID)
{
bool success = false;
if (String.IsNullOrWhiteSpace(eventID) == false)
{
JSONObject js = api.Delete("/"+eventID);
if (!String.IsNullOrEmpty(js.Dictionary["ID"].String))
{
success = true;
}
}
return success;
}
And the tricky part is that , it doesn't update, and if delete, it returns me a 404.
Here is a few things i've tried : /me/events/eventID , http://graph.facebook.com/eventID , /events/eventID ; /eventID ; Anyways, none of them works ... so , is it possible ?
You have a leading space in your code:
api.Post(" https: for the update as well as a https:// try just var js = api.Post(eventId, eventInit);
For the delete you have the wrong check
if (!String.IsNullOrEmpty(js.Dictionary["ID"].String))
{
success = true;
}
For the HTTP delete command you get back true/false from the api, not the id of what you deleted.

Resources