Search Results

Search found 20401 results on 817 pages for 'null coalescing operator'.

Page 20/817 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • C++ standard: dereferencing NULL pointer to get a reference?

    - by shoosh
    I'm wondering about what the C++ standard says about code like this: int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref; In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard? Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.

    Read the article

  • What are the best practices for implementing the == operator for a class in C#?

    - by remio
    While implementing an == operator, I have the feeling that I am missing some essential points. Hence, I am searching some best practices around that. Here are some related questions I am thinking about: How to cleanly handle the reference comparison? Should it be implemented through a IEquatable<T>-like interface? Or overriding object.Equals? And what about the != operator? (this list might not be exhaustive).

    Read the article

  • How Does iPhone Visual Voicemail Work From An Operator Perspective?

    - by Jasarien
    I'm hoping there are some Cell Phone Operator gurus here today. Would anyone be able to explain how Operators achieve the Visual Voicemail feature on the iPhone (and I assume other newer smart phones)? If a new cell phone operator that distributed SIM cards wanted to utilise the visual voicemail feature on unlocked iPhone's what services need to be in place to be able to support it? Is there an open spec or is it completely proprietary?

    Read the article

  • inserting null values in datetime column and integer column

    - by reggie
    I am using C# and developing a winform application. I have a project class which has the project attributes. the constructor of the project class is as follows: newProject = new Project(GCD_ID.IsNull() ? (int?)null : Convert.ToInt32(GCD_ID), txt_Proj_Desc.Text, txt_Prop_Name.Text, ST.ID.ToString().IsNull() ? null: ST.ID.ToString(), cmbCentre.Text, SEC.ID.ToString().IsNull() ? null : SEC.ID.ToString(), cmbZone.Text, FD.ID.ToString().IsNull() ? null : FD.ID.ToString(), DT.ID.ToString().IsNull() ? null : DT.ID.ToString(), OP.ID.ToString().IsNull() ? null : OP.ID.ToString(), T.ID.ToString().IsNull() ? null : T.ID.ToString(), CKV.ID.ToString().IsNull() ? null : CKV.ID.ToString(), STAT.ID.ToString().IsNull() ? null : STAT.ID.ToString(), MW.IsNull() ? (Double?)null : Convert.ToDouble(MW), txt_Subject.Text, Ip_Num.IsNull() ? (int?)null : Convert.ToInt32(Ip_Num), H1N_ID.IsNull() ? (int?)null : Convert.ToInt32(H1N_ID), NOMS_Slip_Num.IsNull() ? (int?)null : Convert.ToInt32(NOMS_Slip_Num), NMS_Updated.IsNull() ? (DateTime?)null : Convert.ToDateTime(NMS_Updated), Received_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Received_Date), Actual_IS_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Actual_IS_Date), Scheduled_IS_Date.IsNull() ? (DateTime?)null : Convert.ToDateTime(Scheduled_IS_Date), UpSt.ID.ToString().IsNull() ? null : UpSt.ID.ToString(), UpFd.ID.ToString().IsNull() ? null : UpFd.ID.ToString(), txtHVCircuit.Text, cmbbxSIA.Text); My problem is that i cannot insert values into the database when the datetime variables and the integer variables are null. all this data are assigned to the variable from textboxes on the form.. bELOW is the database function which takes in all the variables and insert them into the database. public static void createNewProject(int? GCD_ID, string Project_Desc, string Proponent_Name, int Station_ID, string OpCentre, int Sector_ID, string PLZone, int Feeder, int DxTx_ID, int OpControl_ID, int Type_ID, int ConnKV_ID, int Status_ID, double? MW, string Subject, int? Ip_Num, int? H1N_ID, int? NOMS_Slip_Num, DateTime? NMS_Updated, DateTime? Received_Date, DateTime? Actual_IS_Date, DateTime? Scheduled_IS_Date, int UP_Station_ID, int UP_Feeder_ID, string @HV_Circuit, string SIA_Required) { SqlConnection conn = null; try { //Takes in all the employee details to be added to the database. conn = new SqlConnection(databaseConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("createNewProject", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("GCD_ID", GCD_ID)); cmd.Parameters.Add(new SqlParameter("Project_Desc", MiscFunctions.Capitalize(Project_Desc))); cmd.Parameters.Add(new SqlParameter("Proponent_Name", MiscFunctions.Capitalize(Proponent_Name))); cmd.Parameters.Add(new SqlParameter("Station_ID", Station_ID)); cmd.Parameters.Add(new SqlParameter("OpCentre", OpCentre)); cmd.Parameters.Add(new SqlParameter("Sector_ID", Sector_ID)); cmd.Parameters.Add(new SqlParameter("PLZone", PLZone)); cmd.Parameters.Add(new SqlParameter("Feeder", Feeder)); cmd.Parameters.Add(new SqlParameter("DxTx_ID", DxTx_ID)); cmd.Parameters.Add(new SqlParameter("OpControl_ID", OpControl_ID)); cmd.Parameters.Add(new SqlParameter("Type_ID", Type_ID)); cmd.Parameters.Add(new SqlParameter("ConnKV_ID", ConnKV_ID)); cmd.Parameters.Add(new SqlParameter("Status_ID", Status_ID)); cmd.Parameters.Add(new SqlParameter("MW", MW)); cmd.Parameters.Add(new SqlParameter("Subject", Subject)); cmd.Parameters.Add(new SqlParameter("Ip_Num", Ip_Num)); cmd.Parameters.Add(new SqlParameter("H1N_ID", H1N_ID)); cmd.Parameters.Add(new SqlParameter("NOMS_Slip_Num", NOMS_Slip_Num)); cmd.Parameters.Add(new SqlParameter("NMS_Updated", NMS_Updated)); cmd.Parameters.Add(new SqlParameter("Received_Date", Received_Date)); cmd.Parameters.Add(new SqlParameter("Actual_IS_Date", Actual_IS_Date)); cmd.Parameters.Add(new SqlParameter("Scheduled_IS_Date", Scheduled_IS_Date)); cmd.Parameters.Add(new SqlParameter("UP_Station_ID", UP_Station_ID)); cmd.Parameters.Add(new SqlParameter("UP_Feeder_ID", UP_Feeder_ID)); cmd.Parameters.Add(new SqlParameter("HV_Circuit", HV_Circuit)); cmd.Parameters.Add(new SqlParameter("SIA_Required", SIA_Required)); cmd.ExecuteNonQuery(); } catch (Exception e) //returns if error incurred. { MessageBox.Show("Error occured in createNewProject" + Environment.NewLine + e.ToString()); } finally { if (conn != null) { conn.Close(); } } } My question is, how do i insert values into the database. please please help

    Read the article

  • MySQL load data null values

    - by SP1
    Hello, I have a file that can contain from 3 to 4 columns of numerical values which are separated by comma. Empty fields are defined with the exception when they are at the end of the row: 1,2,3,4,5 1,2,3,,5 1,2,3 The following table was created in MySQL: +-------+--------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------+------+-----+---------+-------+ | one | int(1) | YES | | NULL | | | two | int(1) | YES | | NULL | | | three | int(1) | YES | | NULL | | | four | int(1) | YES | | NULL | | | five | int(1) | YES | | NULL | | +-------+--------+------+-----+---------+-------+ I am trying to load the data using MySQL LOAD command: load data infile '/tmp/testdata.txt' into table moo fields terminated by "," lines terminated by "\n"; The resulting table: +------+------+-------+------+------+ | one | two | three | four | five | +------+------+-------+------+------+ | 1 | 2 | 3 | 4 | 5 | | 1 | 2 | 3 | 0 | 0 | | 1 | 2 | 3 | NULL | NULL | +------+------+-------+------+------+ The problem lies with the fact that when a field is empty in the raw data and is not defined, MySQL for some reason does not use the columns default value (which is NULL) and uses zero. NULL is used correctly when the field is missing alltogether. Unfortunately, I have to be able to distinguish between NULL and 0 at this stage so any help would be appreciated. Thanks S.

    Read the article

  • Android sqlight problem always null

    - by yoav.str
    every time i am using the db its null and i just dont get it i use this code for the SQL when I have quarry : public class GameSQLHelper { static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra" }; private static final String DB_PATH = "/countryCityGame/databases/"; private static final String DATABASE_NAME = "events.db"; private static final int DATABASE_VERSION = 1; private final Context mCtx; // Table name public static final String TABLE = "myDataBase"; // Columns public static final String LETTER = "letter"; public static final String TYPE = "type"; public static final String VALUE = "value"; //my database SQLiteDatabase myDataBase; private static class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = null; DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table " + TABLE + "( " + BaseColumns._ID + " integer primary key autoincrement, " + LETTER + " text not null, " + TYPE + " text not null," + VALUE + " text not null );"; Log.d("EventsData", "onCreate: " + sql); db.execSQL(sql); insertValuesToDB(db); } private void insertValuesToDB(SQLiteDatabase db) { if (db == null){ } else{ db.execSQL("INSERT INTO " + TABLE + " ("+LETTER+","+ TYPE +"," + VALUE +")" + " VALUES ('A', 'country', 'Angola');"); ContentValues initialValues = new ContentValues(); for (int i = 0 ; i < COUNTRIES.length ; i++){ Character tmp = (Character)COUNTRIES[i].charAt(0); initialValues.put(VALUE, COUNTRIES[i]); initialValues.put(TYPE, "country"); initialValues.put(LETTER,tmp.toString(tmp)); db.insert(TABLE, null, initialValues); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public GameSQLHelper(Context ctx) { this.mCtx = ctx; } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion >= newVersion) return; String sql = null; if (oldVersion == 1) sql = "alter table " + TABLE + " add note text;"; if (oldVersion == 2) sql = ""; Log.d("EventsData", "onUpgrade : " + sql); if (sql != null) db.execSQL(sql); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DATABASE_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } public boolean existInDataBase(String serchStr ){ Cursor c = null ; try{ openDataBase(); c = myDataBase.query(true, TABLE, new String[] {TYPE }, VALUE + "=" + serchStr, null, null, null, null, null); } catch(Exception e){ Log.d("sqlExacption", e.getMessage()); } if (c == null) return false; return true; } } whenever i call this class (i hold an instace of him initialized : mDbHelper = new GameSQLHelper(this); where this is an activity ) i always get my mDbHelper as null how can i change it , its my first time working with sql outside of mysql platform so i am kind of having problmes understanding tje concept , and the android notepad example didnt help me .

    Read the article

  • Why "object reference not set to an instance of an object" doesn't tell us which object?

    - by Saeed Neamati
    We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object. However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man. Likewise, if we want to remove the bug, we do need to know which object is null. Now, something has obsessed my mind for several months, and that is: Why .NET doesn't give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source? Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

    Read the article

  • "AND Operator" in PAM

    - by d_inevitable
    I need to prevent users from authenticating through Kerberos when the encrypted /home/users has not yet been mounted. (This is to avoid corrupting the ecryptfs mountpoint) Currently I have these lines in /etc/pam.d/common-auth: auth required pam_group.so use_first_pass auth [success=2 default=ignore] pam_krb5.so minimum_uid=1000 try_first_pass auth [success=1 default=ignore] pam_unix.so nullok_secure try_first_pass I am planning to use pam_exec.so to execute a script that will exit 1 if the ecyptfs mounts are not ready yet. Doing this: auth required pam_exec.so /etc/security/check_ecryptfs will lock me out for good if ecryptfs for some reason fails. In such case I would like to at least be able to login with a local (non-kerberos) user to fix the issue. Is there some sort of AND-Operator in which I can say that login through kerberos+ldap is only sufficient if both kerberos authentication and the ecryptfs mount has succeeded?

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question [closed]

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • Avoid Postfix Increment Operator

    - by muntoo
    I've read that I should avoid the postfix increment operator because of performance reasons (in certain cases). But doesn't this affect code readability? In my opinion: for(int i = 0; i < 42; i++); /* i will never equal 42! */ Looks better than: for(int i = 0; i < 42; ++i); /* i will never equal 42! */ But this is probably just out of habit. Admittedly, I haven't seen many use ++i. Is the performance that bad to sacrifice readability, in this case? Or am I just blind, and ++i is more readable than i++?

    Read the article

  • Why does virtual assignment behave differently than other virtual functions of the same signature?

    - by David Rodríguez - dribeas
    While playing with implementing a virtual assignment operator I have ended with a funny behavior. It is not a compiler glitch, since g++ 4.1, 4.3 and VS 2005 share the same behavior. Basically, the virtual operator= behaves differently than any other virtual function with respect to the code that is actually being executed. struct Base { virtual Base& f( Base const & ) { std::cout << "Base::f(Base const &)" << std::endl; return *this; } virtual Base& operator=( Base const & ) { std::cout << "Base::operator=(Base const &)" << std::endl; return *this; } }; struct Derived : public Base { virtual Base& f( Base const & ) { std::cout << "Derived::f(Base const &)" << std::endl; return *this; } virtual Base& operator=( Base const & ) { std::cout << "Derived::operator=( Base const & )" << std::endl; return *this; } }; int main() { Derived a, b; a.f( b ); // [0] outputs: Derived::f(Base const &) (expected result) a = b; // [1] outputs: Base::operator=(Base const &) Base & ba = a; Base & bb = b; ba = bb; // [2] outputs: Derived::operator=(Base const &) Derived & da = a; Derived & db = b; da = db; // [3] outputs: Base::operator=(Base const &) ba = da; // [4] outputs: Derived::operator=(Base const &) da = ba; // [5] outputs: Derived::operator=(Base const &) } The effect is that the virtual operator= has a different behavior than any other virtual function with the same signature ([0] compared to [1]), by calling the Base version of the operator when called through real Derived objects ([1]) or Derived references ([3]) while it does perform as a regular virtual function when called through Base references ([2]), or when either the lvalue or rvalue are Base references and the other a Derived reference ([4],[5]). Is there any sensible explanation to this odd behavior?

    Read the article

  • operator new for array of class without default constructor......

    - by skydoor
    For a class without default constructor, operator new and placement new can be used to declare an array of such class. When I read the code in More Effective C++, I found the code as below(I modified some part)..... My question is, why [] after the operator new is needed? I test it without it, it still works. Can any body explain that? class A { public: int i; A(int i):i(i) {} }; int main() { void *rawMemory = operator new[] (10 * sizeof(A)); // Why [] needed here? A *p = static_cast<A*>(rawMemory); for(int i = 0 ; i < 10 ; i++ ) { new(&p[i])A(i); } for(int i = 0 ; i < 10 ; i++ ) { cout<<p[i].i<<endl; } for(int i = 0 ; i < 10 ; i++ ) { p[i].~A(); } return 0; }

    Read the article

  • Where to add an overloaded operator for the tr1::array?

    - by phlipsy
    Since I need to add an operator& for the std::tr1::array<bool, N> I wrote the following lines template<std::size_t N> std::tr1::array<bool, N> operator& (const std::tr1::array<bool, N>& a, const std::tr1::array<bool, N>& b) { std::tr1::array<bool, N> result; std::transform(a.begin(), a.end(), b.begin(), result.begin(), std::logical_and<bool>()); return result; } Now I don't know in which namespace I've to put this function. I considered the std namespace as a restricted area. Only total specialization and overloaded function templates are allowed to be added by the user. Putting it into the global namespace isn't "allowed" either in order to prevent pollution of the global namespace and clashes with other declarations. And finally putting this function into the namespace of the project doesn't work since the compiler won't find it there. What had I best do? I don't want to write a new array class putted into the project namespace. Because in this case the compiler would find the right namespace via argument dependent name lookup. Or is this the only possible way because writing a new operator for existing classes means extending their interfaces and this isn't allowed either for standard classes?

    Read the article

  • Operator overloading in generic struct: can I create overloads for specific kinds(?) of generic?

    - by Carson Myers
    I'm defining physical units in C#, using generic structs, and it was going okay until I got the error: One of the parameters of a binary operator must be the containing type when trying to overload the mathematical operators so that they convert between different units. So, I have something like this: public interface ScalarUnit { } public class Duration : ScalarUnit { } public struct Scalar<T> where T : ScalarUnit { public readonly double Value; public Scalar(double Value) { this.Value = Value; } public static implicit operator double(Scalar<T> Value) { return Value.Value; } } public interface VectorUnit { } public class Displacement : VectorUnit { } public class Velocity : VectorUnit { } public struct Vector<T> where T : VectorUnit { #... public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2) { return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction); } } There aren't any errors for the + and - operators, where I'm just working on a Vector<T>, but when I substitute a unit for T, suddenly it doesn't like it. Is there a way to make this work? I figured it would work, since Displacement implements the VectorUnit interface, and I have where T : VectorUnit in the struct header. Am I at least on the right track here? I'm new to C# so I have difficulty understanding what's going on sometimes.

    Read the article

  • Conversion constructor vs. conversion operator: precedence

    - by GRB
    Reading some questions here on SO about conversion operators and constructors got me thinking about the interaction between them, namely when there is an 'ambiguous' call. Consider the following code: class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B's conversion constructor" << endl; } }; class A { public: operator B() //conversion operator { cout << "called A's conversion operator" << endl; return B(); } }; int main() { B b = A(); //what should be called here? apparently, A::operator B() return 0; } The above code displays "called A's conversion operator", meaning that the conversion operator is called as opposed to the constructor. If you remove/comment out the operator B() code from A, the compiler will happily switch over to using the constructor instead (with no other changes to the code). My questions are: Since the compiler doesn't consider B b = A(); to be an ambiguous call, there must be some type of precedence at work here. Where exactly is this precedence established? (a reference/quote from the C++ standard would be appreciated) From an object-oriented philosophical standpoint, is this the way the code should behave? Who knows more about how an A object should become a B object, A or B? According to C++, the answer is A -- is there anything in object-oriented practice that suggests this should be the case? To me personally, it would make sense either way, so I'm interested to know how the choice was made. Thanks in advance

    Read the article

  • Dilemma with two types and operator +

    - by user35443
    I have small problem with operators. I have this code: public class A { public string Name { get; set; } public A() { } public A(string Name) { this.Name = Name; } public static implicit operator B(A a) { return new B(a.Name); } public static A operator+(A a, A b) { return new A(a.Name + " " + b.Name); } } public class B { public string Name { get; set; } public B() { } public B(string Name) { this.Name = Name; } public static implicit operator A(B b) { return new A(b.Name); } public static B operator +(B b, B a) { return new B(b.Name + " " + a.Name); } } Now I want to know, which's conversion operator will be called and which's addition operator will be called in this operation: new A("a") + new B("b"); Will it be operator of A, or of B? (Or both?) Thanks....

    Read the article

  • How to modify a given class to use const operators

    - by zsero
    I am trying to solve my question regarding using push_back in more than one level. From the comments/answers it is clear that I have to: Create a copy operator which takes a const argument Modify all my operators to const But because this header file is given to me there is an operator what I cannot make into const. It is a simple: float & operator [] (int i) { return _item[i]; } In the given program, this operator is used to get and set data. My problem is that because I need to have this operator in the header file, I cannot turn all the other operators to const, what means I cannot insert a copy operator. How can I make all my operators into const, while preserving the functionality of the already written program? Here is the full declaration of the class: class Vector3f { float _item[3]; public: float & operator [] (int i) { return _item[i]; } Vector3f(float x, float y, float z) { _item[0] = x ; _item[1] = y ; _item[2] = z; }; Vector3f() {}; Vector3f & operator = ( const Vector3f& obj) { _item[0] = obj[0]; _item[1] = obj[1]; _item[2] = obj[2]; return *this; }; Vector3f & operator += ( const Vector3f & obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return *this; }; bool operator ==( const Vector3f & obj) { bool x = (_item[0] == obj[0]) && (_item[1] == obj[1]) && (_item[2] == obj[2]); return x; } // my copy operator Vector3f(const Vector3f& obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return this; } };

    Read the article

  • Random pauses with "Key dispatching timed out sending to <null>" when closing Android SurfaceView

    - by kenyee
    When I close an Android SurfaceView Activity, the app sometimes pauses and almost gets an ANR (Application Not Responding) message. Looking at LogCat, it appears to be timing out trying to send keys to it. I tried modifying the code to setFocusable(false) when in the onKeyDown handler for the SurfaceView, but that doesn't seem to affect this. Any other ideas on what might be causing this? Or what these messages in Logcat even mean? ============================= 05-31 19:35:35.285: INFO/WindowManager(586): focus null mToken is null at event dispatch! 05-31 19:35:35.295: WARN/WindowManager(586): Current state: {{KeyEvent{action=1 code=4 repeat=0 meta=0 scancode=158 mFlags=8} to null @ 1275334535292 lw=null lb=null fin=true gfw=true ed=true tts=0 wf=false fp=false mcf=null}} 05-31 19:35:35.305: WARN/WindowManager(586): Continuing to wait for key to be dispatched 05-31 19:35:40.306: WARN/WindowManager(586): Key dispatching timed out sending to 05-31 19:35:40.316: WARN/WindowManager(586): Dispatch state: {{KeyEvent{action=0 code=4 repeat=0 meta=0 scancode=158 mFlags=8} to Window{43763540 com.myapp/com.myapp.DiagramEdit paused=false} @ 1275334499512 lw=Window{43763540 com.myapp/com.myapp.DiagramEdit paused=false} lb=android.os.BinderProxy@43702190 fin=false gfw=true ed=true tts=0 wf=false fp=false mcf=null}} 05-31 19:35:40.326: INFO/WindowManager(586): focus null mToken is null at event dispatch! 05-31 19:35:40.326: WARN/WindowManager(586): Current state: {{KeyEvent{action=1 code=4 repeat=0 meta=0 scancode=158 mFlags=8} to null @ 1275334540327 lw=null lb=null fin=true gfw=true ed=true tts=0 wf=false fp=false mcf=null}} 05-31 19:35:40.326: WARN/WindowManager(586): Continuing to wait for key to be dispatched

    Read the article

  • Concise C# code for gathering several properties with a non-null value into a collection?

    - by stakx
    A fairly basic problem for a change. Given a class such as this: public class X { public T A; public T B; public T C; ... // (other fields, properties, and methods are not of interest here) } I am looking for a concise way to code a method that will return all A, B, C, ... that are not null in an enumerable collection. (Assume that declaring these fields as an array is not an option.) public IEnumerable<T> GetAllNonNullAs(this X x) { // ? } The obvious implementation of this method would be: public IEnumerable<T> GetAllNonNullAs(this X x) { var resultSet = new List<T>(); if (x.A != null) resultSet.Add(x.A); if (x.B != null) resultSet.Add(x.B); if (x.C != null) resultSet.Add(x.C); ... return resultSet; } What's bothering me here in particular is that the code looks verbose and repetitive, and that I don't know the initial List capacity in advance. It's my hope that there is a more clever way, probably something involving the ?? operator? Any ideas?

    Read the article

  • How to create C++ istringstream from a char array with null(0) characters?

    - by Morpheus
    I have a char array which contains null characters at random locations. I tried to create an iStringStream using this array (encodedData_arr) as below, I use this iStringStream to insert binary data(imagedata of Iplimage) to a MySQL database blob field(using MySQL Connector/C++'s setBlob(istream *is) ) it only stores the characters upto the first null character. Is there a way to create an iStringStream using a char array with null characters? unsigned char *encodedData_arr = new unsigned char[data_vector_uchar->size()]; // Assign the data of vector<unsigned char> to the encodedData_arr for (int i = 0; i < vec_size; ++i) { cout<< data_vector_uchar->at(i)<< " : "<< encodedData_arr[i]<<endl; } // Here the content of the encodedData_arr is same as the data_vector_uchar // So char array is initializing fine. istream *is = new istringstream((char*)encodedData_arr, istringstream::in || istringstream::binary); prepStmt_insertImage->setBlob(1, is); // Here only part of the data is stored in the database blob field (Upto the first null character)

    Read the article

  • DIVIDE vs division operator in #dax

    - by Marco Russo (SQLBI)
    Alberto Ferrari wrote an interesting article about DIVIDE performance in DAX. This new function has been introduced in SQL Server Analysis Services 2012 SP1, so it is available also in Excel 2013 (which still doesn’t have other features/fixes introduced by following Cumulative Updates…). The idea that instead of writing: IF ( Sales[Quantity] <> 0, Sales[Amount] / Sales[Quantity], BLANK () ) you can write: DIVIDE ( Sales[Amount], Sales[Quantity] ) There is a third optional argument in DIVIDE that defines the result in case the denominator (second argument) is zero, and by default its value is BLANK, so I omitted the third argument in my example. Using DIVIDE is very important, especially when you use a measure in MDX (for example in an Excel PivotTable) because it raise the chance that the non empty evaluation for the result is evaluated in bulk mode instead of cell-by-cell. However, from a DAX point of view, you might find it’s better to use the standard division operator removing the IF statement. I suggest you to read Alberto’s article, because you will find that an expression applying a filter using FILTER is faster than using CALCULATE, which is against any rule of thumb you might have read until now! Again, this is not always true, and depends on many conditions – trying to simplify, we might say that for a simple calculation, the query plan generated by FILTER could be more efficient – but, as usual, it depends, and 90% of the times using FILTER instead of CALCULATE produces slower performance. Do not take anything for granted, and always check the query plan when performance are your first issue!

    Read the article

  • SQL SERVER – Fix: Error: 8117: Operand data type bit is invalid for sum operator

    - by pinaldave
    Here is the very interesting error I received from a reader. He has very interesting question. He attempted to use BIT filed in the SUM aggregation function and he got following error. He went ahead with various different datatype (i.e. INT, TINYINT etc) and he was able to do the SUM but with BIT he faced the problem. Error Received: Msg 8117, Level 16, State 1, Line 1 Operand data type bit is invalid for sum operator. Reproduction of the error: Set up the environment USE tempdb GO -- Preparing Sample Data CREATE TABLE TestTable (ID INT, Flag BIT) GO INSERT INTO TestTable (ID, Flag) SELECT 1, 0 UNION ALL SELECT 2, 1 UNION ALL SELECT 3, 0 UNION ALL SELECT 4, 1 GO SELECT * FROM TestTable GO Following script will work fine: -- This will work fine SELECT SUM(ID) FROM TestTable GO However following generate error: -- This will generate error SELECT SUM(Flag) FROM TestTable GO The workaround is to convert or cast the BIT to INT: -- Workaround of error SELECT SUM(CONVERT(INT, Flag)) FROM TestTable GO Clean up the setup -- Clean up DROP TABLE TestTable GO Workaround: As mentioned in above script the workaround is to covert the bit datatype to another friendly data types like INT, TINYINT etc. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >