qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
31,932,346
Im trying to add a value to a dynamic array but keep getting a run-time error with this. I've found a few different sources saying that this should be the answer, so I cant figure out what I have done wrong... ``` Sub addtoarray() Dim catSheets() As String ReDim Preserve catSheets(UBound(catSheets) + 1) catSheets(UBound(catSheets)) = "Chemicals" End Sub ```
2015/08/11
[ "https://Stackoverflow.com/questions/31932346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823913/" ]
When you create the `catSheets()` array, it's dimensionless. Therefore, you cannot use `UBound()` to determine the array's upper boundary. You can certainly follow up a `Dim ()` with a `ReDim` if you want to specify an array size, but you won't be able to query the array dimensions until after you've given it some. So you have a few options. First, you could follow up your `Dim ()` with an immediate `ReDim` to give your array an initial size: ``` Dim catSheets() As String ReDim catSheets(0) As String ... ReDim Preserve catSheets(...) As String ``` Or, you could just use `ReDim` from the start to assign an initial size and still have the ability to `ReDim` later: ``` ReDim catSheets(0) As String ... ReDim Preserve catSheets(...) As String ``` Alternatively, you could use the `Array()` function and store it as a `Variant`. Done this way, you *can* query the `UBound()`. For example: ``` Dim catSheets As Variant catSheets = Array() Debug.Print UBound(catSheets) ' => -1 ReDim Preserve catSheets(UBound(catSheets) + 1) catSheets(UBound(catSheets)) = "Chemicals" ' Works fine ```
What you can do is to use `Variant` if you want to preserve the way to use the code. ``` Sub addtoarray() Dim catSheets As Variant catSheets = Array() ' Initially Empty (0 to -1) Redim Preserve catSheets(Ubound(catSheets) + 1) ' Now it's 0 to 0 catSheets(Ubound(catSheets)) = "Chemicals" ' index here is 0 End Sub ```
1,284,055
I use RDP-based Windows' Remote Client Desktop utility to connect to my desktop from my laptop. It's much faster and looks better than remote control applications like TeamViewer etc. Out of curiosity, why is RDP better? Thank you.
2009/08/16
[ "https://Stackoverflow.com/questions/1284055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196889/" ]
RDP is a specific protocol which allows to transmit low-level screen drawing operations. It is also aware of pixmap entities on the screen. For example it understands when an icon is drawn and caches it (typically in a lossy compressed format) on the client side. Other software does not have this low-level access: It waits for the screen to change and then re-transmit a capture of the screen or the changed regions. Whenever the screen changes, a pixmap representation has to be transmitted. Because this is lossy compressed in general, it also looks worse.
There are two major factors at work which determine the performance of a remote control product: **How does it detect when changes occur on the screen?** Some RC products divide the screen into tiles and scan the screen frame buffer periodically to determine if any changes have occurred. Others will hook directly into the OS. In the past this was done by intercepting the video driver. Now you can create a mirror driver into which the OS "mirrors" all drawing operations. This is, obviously, much faster. **How does it send those changes across the wire?** Some products (like VNC) will always send bitmaps of any area that changed. Others will send the actual operation that caused the change. e.g. render text string s using font f at coordinates (x,y) or draw bezier curve using a given set of parameters and, of course, render bitmap. This is, again, much faster. RDP uses the faster (and more difficult to implement) technique in both cases. I believe the actual protocol it uses is T.128. Bitmaps are usually compressed. Some products (like Carbon Copy) also maintain synchronized bitmap caches on both sides of the connection in order to squeeze out even more performance.
5,230,321
Hi there i want to create two distinct tables in a database. These tables are **User\_details** and **Creditcard\_details** I have created the following DBAdapter class to implement the database operations, however when i call the ***insertCreditcard() method*** the values are not inserted. I wonder if the second table is even being created. Im going wrong somewhere, but cant figure out where and what should i do in order to rectify the issue. What i was precisely trying to do was, check the **id field** from the **User\_details** table against the username and password supplied at the login activity and then assign the value of this **id variable** to another variable called **ccid** which is used to search rows in the **Creditcard\_details** table or insert values into it. Can someone please guide me. ``` package com.androidbook.LoginForm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBAdapter { /*------------------------User Details ---------------------------------*/ public static Cursor d; public static final String KEY_ROWID = "_id"; public static final String KEY_Name = "name"; public static final String KEY_Username = "username"; public static final String KEY_Password = "password"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "Wallet"; private static final String DATABASE_TABLE = "User_Details"; /*------------------------Credit Cards Table----------------------*/ private static final String KEY_CCID = "_ccid"; private static final String KEY_CCUNAME= "cuname"; private static final String KEY_CCNO = "ccno"; private static final String KEY_CVV = "cvvno"; private static final String EXP_DATE = "expdate"; private static final String CREDITCARDS_TABLE = "Creditcard_Details"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table User_Details (_id integer primary key autoincrement, " + "name text not null, username text not null, " + "password text not null);"; /*---------------------Create Credit Card Table -------------------------------*/ private static final String CCTABLE_CREATE = "create table Creditcard_Details ( _ccid integer primary key , " + "cuname text not null, ccno text not null, " + "cvvno text not null" + "expdate text not null )";//+ "FOREIGN KEY(_ccid) REFERENCES User_Details(_id))"; private final Context context; public DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(CCTABLE_CREATE); } @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 titles"); onCreate(db); } } public int Login(String username,String password) { try { Cursor c = null; c = db.rawQuery("select * from User_Details where username =" + "\""+ username + "\""+" and password="+ "\""+ password + "\"", null); c.moveToFirst(); String tempid = c.getString(0); //Toast.makeText(DBAdapter.this, "correct"+" "+c,Toast.LENGTH_LONG).show(); d= c;//CCview(tempid); return c.getCount(); } catch(Exception e) { e.printStackTrace(); } return 0; } //-----------------------Display Credit Card ----------------------------- /* public int Getid(String tempid) { Cursor c; c = db.rawQuery("select id from User_Details where username =" + "\""+ username + "\"", null); return Integer.parseInt(c.getString(0)); }*/ public Cursor cursordisplay() { return d; } public Cursor CCview(long menuid)throws SQLException { Cursor mCursor = db.query(true, CREDITCARDS_TABLE, new String[] { KEY_CCID, KEY_CCUNAME, KEY_CCNO, KEY_CVV, EXP_DATE, }, KEY_CCID + "=" + menuid, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //--------------------Entries into Credit Card Table------------------------------------ //---insert a title into the database--- public long insertCreditcard(int i, String j, String k, String l, String date) { ContentValues creditValues = new ContentValues(); creditValues.put(KEY_CCID, i); creditValues.put(KEY_CCUNAME, j); creditValues.put(KEY_CCNO, k); creditValues.put(KEY_CVV, l); creditValues.put(EXP_DATE, date); return db.insert(CREDITCARDS_TABLE, null, creditValues); } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertTitle(String name, String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_Name, name); initialValues.put(KEY_Username, username); initialValues.put(KEY_Password, password); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- public boolean updateTitle(long rowId, String name, String username, String password) { ContentValues args = new ContentValues(); args.put(KEY_Name, name); args.put(KEY_Username, username); args.put(KEY_Password, password); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } ```
2011/03/08
[ "https://Stackoverflow.com/questions/5230321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/642623/" ]
`element.style` in Firebug is the style applied to the element, for exemple ``` <span style="padding: 10px;">My text</span> ``` `element.style` will have ``` element.style { padding: 10px; } ``` to override, the best way is to cleat the `style` attribute, append a `class` name and write the CSS you need. --- Regarding your modal problem, if you are using [jQuery UI Dialog](http://docs.jquery.com/UI/Dialog) component, why don't you set the width programmatically, like: ``` $( ".selector" ).dialog({ width: 460, maxWidth: 460, minWidth: 460 }); ```
You will need to clear the width from the `<div>` element itself. It is flagged as important so you can't override it.
5,230,321
Hi there i want to create two distinct tables in a database. These tables are **User\_details** and **Creditcard\_details** I have created the following DBAdapter class to implement the database operations, however when i call the ***insertCreditcard() method*** the values are not inserted. I wonder if the second table is even being created. Im going wrong somewhere, but cant figure out where and what should i do in order to rectify the issue. What i was precisely trying to do was, check the **id field** from the **User\_details** table against the username and password supplied at the login activity and then assign the value of this **id variable** to another variable called **ccid** which is used to search rows in the **Creditcard\_details** table or insert values into it. Can someone please guide me. ``` package com.androidbook.LoginForm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBAdapter { /*------------------------User Details ---------------------------------*/ public static Cursor d; public static final String KEY_ROWID = "_id"; public static final String KEY_Name = "name"; public static final String KEY_Username = "username"; public static final String KEY_Password = "password"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "Wallet"; private static final String DATABASE_TABLE = "User_Details"; /*------------------------Credit Cards Table----------------------*/ private static final String KEY_CCID = "_ccid"; private static final String KEY_CCUNAME= "cuname"; private static final String KEY_CCNO = "ccno"; private static final String KEY_CVV = "cvvno"; private static final String EXP_DATE = "expdate"; private static final String CREDITCARDS_TABLE = "Creditcard_Details"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table User_Details (_id integer primary key autoincrement, " + "name text not null, username text not null, " + "password text not null);"; /*---------------------Create Credit Card Table -------------------------------*/ private static final String CCTABLE_CREATE = "create table Creditcard_Details ( _ccid integer primary key , " + "cuname text not null, ccno text not null, " + "cvvno text not null" + "expdate text not null )";//+ "FOREIGN KEY(_ccid) REFERENCES User_Details(_id))"; private final Context context; public DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(CCTABLE_CREATE); } @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 titles"); onCreate(db); } } public int Login(String username,String password) { try { Cursor c = null; c = db.rawQuery("select * from User_Details where username =" + "\""+ username + "\""+" and password="+ "\""+ password + "\"", null); c.moveToFirst(); String tempid = c.getString(0); //Toast.makeText(DBAdapter.this, "correct"+" "+c,Toast.LENGTH_LONG).show(); d= c;//CCview(tempid); return c.getCount(); } catch(Exception e) { e.printStackTrace(); } return 0; } //-----------------------Display Credit Card ----------------------------- /* public int Getid(String tempid) { Cursor c; c = db.rawQuery("select id from User_Details where username =" + "\""+ username + "\"", null); return Integer.parseInt(c.getString(0)); }*/ public Cursor cursordisplay() { return d; } public Cursor CCview(long menuid)throws SQLException { Cursor mCursor = db.query(true, CREDITCARDS_TABLE, new String[] { KEY_CCID, KEY_CCUNAME, KEY_CCNO, KEY_CVV, EXP_DATE, }, KEY_CCID + "=" + menuid, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //--------------------Entries into Credit Card Table------------------------------------ //---insert a title into the database--- public long insertCreditcard(int i, String j, String k, String l, String date) { ContentValues creditValues = new ContentValues(); creditValues.put(KEY_CCID, i); creditValues.put(KEY_CCUNAME, j); creditValues.put(KEY_CCNO, k); creditValues.put(KEY_CVV, l); creditValues.put(EXP_DATE, date); return db.insert(CREDITCARDS_TABLE, null, creditValues); } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertTitle(String name, String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_Name, name); initialValues.put(KEY_Username, username); initialValues.put(KEY_Password, password); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- public boolean updateTitle(long rowId, String name, String username, String password) { ContentValues args = new ContentValues(); args.put(KEY_Name, name); args.put(KEY_Username, username); args.put(KEY_Password, password); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } ```
2011/03/08
[ "https://Stackoverflow.com/questions/5230321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/642623/" ]
You will need to clear the width from the `<div>` element itself. It is flagged as important so you can't override it.
element.style is not a valid CSS selector. You would have to target the element using it's class or id, if it has one, otherwise you'd need to use traversal to target the element in either CSS, or with jQuery.
5,230,321
Hi there i want to create two distinct tables in a database. These tables are **User\_details** and **Creditcard\_details** I have created the following DBAdapter class to implement the database operations, however when i call the ***insertCreditcard() method*** the values are not inserted. I wonder if the second table is even being created. Im going wrong somewhere, but cant figure out where and what should i do in order to rectify the issue. What i was precisely trying to do was, check the **id field** from the **User\_details** table against the username and password supplied at the login activity and then assign the value of this **id variable** to another variable called **ccid** which is used to search rows in the **Creditcard\_details** table or insert values into it. Can someone please guide me. ``` package com.androidbook.LoginForm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBAdapter { /*------------------------User Details ---------------------------------*/ public static Cursor d; public static final String KEY_ROWID = "_id"; public static final String KEY_Name = "name"; public static final String KEY_Username = "username"; public static final String KEY_Password = "password"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "Wallet"; private static final String DATABASE_TABLE = "User_Details"; /*------------------------Credit Cards Table----------------------*/ private static final String KEY_CCID = "_ccid"; private static final String KEY_CCUNAME= "cuname"; private static final String KEY_CCNO = "ccno"; private static final String KEY_CVV = "cvvno"; private static final String EXP_DATE = "expdate"; private static final String CREDITCARDS_TABLE = "Creditcard_Details"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table User_Details (_id integer primary key autoincrement, " + "name text not null, username text not null, " + "password text not null);"; /*---------------------Create Credit Card Table -------------------------------*/ private static final String CCTABLE_CREATE = "create table Creditcard_Details ( _ccid integer primary key , " + "cuname text not null, ccno text not null, " + "cvvno text not null" + "expdate text not null )";//+ "FOREIGN KEY(_ccid) REFERENCES User_Details(_id))"; private final Context context; public DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(CCTABLE_CREATE); } @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 titles"); onCreate(db); } } public int Login(String username,String password) { try { Cursor c = null; c = db.rawQuery("select * from User_Details where username =" + "\""+ username + "\""+" and password="+ "\""+ password + "\"", null); c.moveToFirst(); String tempid = c.getString(0); //Toast.makeText(DBAdapter.this, "correct"+" "+c,Toast.LENGTH_LONG).show(); d= c;//CCview(tempid); return c.getCount(); } catch(Exception e) { e.printStackTrace(); } return 0; } //-----------------------Display Credit Card ----------------------------- /* public int Getid(String tempid) { Cursor c; c = db.rawQuery("select id from User_Details where username =" + "\""+ username + "\"", null); return Integer.parseInt(c.getString(0)); }*/ public Cursor cursordisplay() { return d; } public Cursor CCview(long menuid)throws SQLException { Cursor mCursor = db.query(true, CREDITCARDS_TABLE, new String[] { KEY_CCID, KEY_CCUNAME, KEY_CCNO, KEY_CVV, EXP_DATE, }, KEY_CCID + "=" + menuid, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //--------------------Entries into Credit Card Table------------------------------------ //---insert a title into the database--- public long insertCreditcard(int i, String j, String k, String l, String date) { ContentValues creditValues = new ContentValues(); creditValues.put(KEY_CCID, i); creditValues.put(KEY_CCUNAME, j); creditValues.put(KEY_CCNO, k); creditValues.put(KEY_CVV, l); creditValues.put(EXP_DATE, date); return db.insert(CREDITCARDS_TABLE, null, creditValues); } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertTitle(String name, String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_Name, name); initialValues.put(KEY_Username, username); initialValues.put(KEY_Password, password); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- public boolean updateTitle(long rowId, String name, String username, String password) { ContentValues args = new ContentValues(); args.put(KEY_Name, name); args.put(KEY_Username, username); args.put(KEY_Password, password); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } ```
2011/03/08
[ "https://Stackoverflow.com/questions/5230321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/642623/" ]
You will need to clear the width from the `<div>` element itself. It is flagged as important so you can't override it.
This should work. The div [style^= is the Div 'Element Style' where you are able to modify any CSS Element. For Example: If the actual 'Element Style' width is 300px. ``` div [style^="width: 300px"]{ width:700px !important;} ``` This forces to overwrite the Element Style to width 700px.
5,230,321
Hi there i want to create two distinct tables in a database. These tables are **User\_details** and **Creditcard\_details** I have created the following DBAdapter class to implement the database operations, however when i call the ***insertCreditcard() method*** the values are not inserted. I wonder if the second table is even being created. Im going wrong somewhere, but cant figure out where and what should i do in order to rectify the issue. What i was precisely trying to do was, check the **id field** from the **User\_details** table against the username and password supplied at the login activity and then assign the value of this **id variable** to another variable called **ccid** which is used to search rows in the **Creditcard\_details** table or insert values into it. Can someone please guide me. ``` package com.androidbook.LoginForm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBAdapter { /*------------------------User Details ---------------------------------*/ public static Cursor d; public static final String KEY_ROWID = "_id"; public static final String KEY_Name = "name"; public static final String KEY_Username = "username"; public static final String KEY_Password = "password"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "Wallet"; private static final String DATABASE_TABLE = "User_Details"; /*------------------------Credit Cards Table----------------------*/ private static final String KEY_CCID = "_ccid"; private static final String KEY_CCUNAME= "cuname"; private static final String KEY_CCNO = "ccno"; private static final String KEY_CVV = "cvvno"; private static final String EXP_DATE = "expdate"; private static final String CREDITCARDS_TABLE = "Creditcard_Details"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table User_Details (_id integer primary key autoincrement, " + "name text not null, username text not null, " + "password text not null);"; /*---------------------Create Credit Card Table -------------------------------*/ private static final String CCTABLE_CREATE = "create table Creditcard_Details ( _ccid integer primary key , " + "cuname text not null, ccno text not null, " + "cvvno text not null" + "expdate text not null )";//+ "FOREIGN KEY(_ccid) REFERENCES User_Details(_id))"; private final Context context; public DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(CCTABLE_CREATE); } @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 titles"); onCreate(db); } } public int Login(String username,String password) { try { Cursor c = null; c = db.rawQuery("select * from User_Details where username =" + "\""+ username + "\""+" and password="+ "\""+ password + "\"", null); c.moveToFirst(); String tempid = c.getString(0); //Toast.makeText(DBAdapter.this, "correct"+" "+c,Toast.LENGTH_LONG).show(); d= c;//CCview(tempid); return c.getCount(); } catch(Exception e) { e.printStackTrace(); } return 0; } //-----------------------Display Credit Card ----------------------------- /* public int Getid(String tempid) { Cursor c; c = db.rawQuery("select id from User_Details where username =" + "\""+ username + "\"", null); return Integer.parseInt(c.getString(0)); }*/ public Cursor cursordisplay() { return d; } public Cursor CCview(long menuid)throws SQLException { Cursor mCursor = db.query(true, CREDITCARDS_TABLE, new String[] { KEY_CCID, KEY_CCUNAME, KEY_CCNO, KEY_CVV, EXP_DATE, }, KEY_CCID + "=" + menuid, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //--------------------Entries into Credit Card Table------------------------------------ //---insert a title into the database--- public long insertCreditcard(int i, String j, String k, String l, String date) { ContentValues creditValues = new ContentValues(); creditValues.put(KEY_CCID, i); creditValues.put(KEY_CCUNAME, j); creditValues.put(KEY_CCNO, k); creditValues.put(KEY_CVV, l); creditValues.put(EXP_DATE, date); return db.insert(CREDITCARDS_TABLE, null, creditValues); } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertTitle(String name, String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_Name, name); initialValues.put(KEY_Username, username); initialValues.put(KEY_Password, password); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- public boolean updateTitle(long rowId, String name, String username, String password) { ContentValues args = new ContentValues(); args.put(KEY_Name, name); args.put(KEY_Username, username); args.put(KEY_Password, password); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } ```
2011/03/08
[ "https://Stackoverflow.com/questions/5230321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/642623/" ]
`element.style` in Firebug is the style applied to the element, for exemple ``` <span style="padding: 10px;">My text</span> ``` `element.style` will have ``` element.style { padding: 10px; } ``` to override, the best way is to cleat the `style` attribute, append a `class` name and write the CSS you need. --- Regarding your modal problem, if you are using [jQuery UI Dialog](http://docs.jquery.com/UI/Dialog) component, why don't you set the width programmatically, like: ``` $( ".selector" ).dialog({ width: 460, maxWidth: 460, minWidth: 460 }); ```
element.style is not a valid CSS selector. You would have to target the element using it's class or id, if it has one, otherwise you'd need to use traversal to target the element in either CSS, or with jQuery.
5,230,321
Hi there i want to create two distinct tables in a database. These tables are **User\_details** and **Creditcard\_details** I have created the following DBAdapter class to implement the database operations, however when i call the ***insertCreditcard() method*** the values are not inserted. I wonder if the second table is even being created. Im going wrong somewhere, but cant figure out where and what should i do in order to rectify the issue. What i was precisely trying to do was, check the **id field** from the **User\_details** table against the username and password supplied at the login activity and then assign the value of this **id variable** to another variable called **ccid** which is used to search rows in the **Creditcard\_details** table or insert values into it. Can someone please guide me. ``` package com.androidbook.LoginForm; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DBAdapter { /*------------------------User Details ---------------------------------*/ public static Cursor d; public static final String KEY_ROWID = "_id"; public static final String KEY_Name = "name"; public static final String KEY_Username = "username"; public static final String KEY_Password = "password"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "Wallet"; private static final String DATABASE_TABLE = "User_Details"; /*------------------------Credit Cards Table----------------------*/ private static final String KEY_CCID = "_ccid"; private static final String KEY_CCUNAME= "cuname"; private static final String KEY_CCNO = "ccno"; private static final String KEY_CVV = "cvvno"; private static final String EXP_DATE = "expdate"; private static final String CREDITCARDS_TABLE = "Creditcard_Details"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table User_Details (_id integer primary key autoincrement, " + "name text not null, username text not null, " + "password text not null);"; /*---------------------Create Credit Card Table -------------------------------*/ private static final String CCTABLE_CREATE = "create table Creditcard_Details ( _ccid integer primary key , " + "cuname text not null, ccno text not null, " + "cvvno text not null" + "expdate text not null )";//+ "FOREIGN KEY(_ccid) REFERENCES User_Details(_id))"; private final Context context; public DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(CCTABLE_CREATE); } @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 titles"); onCreate(db); } } public int Login(String username,String password) { try { Cursor c = null; c = db.rawQuery("select * from User_Details where username =" + "\""+ username + "\""+" and password="+ "\""+ password + "\"", null); c.moveToFirst(); String tempid = c.getString(0); //Toast.makeText(DBAdapter.this, "correct"+" "+c,Toast.LENGTH_LONG).show(); d= c;//CCview(tempid); return c.getCount(); } catch(Exception e) { e.printStackTrace(); } return 0; } //-----------------------Display Credit Card ----------------------------- /* public int Getid(String tempid) { Cursor c; c = db.rawQuery("select id from User_Details where username =" + "\""+ username + "\"", null); return Integer.parseInt(c.getString(0)); }*/ public Cursor cursordisplay() { return d; } public Cursor CCview(long menuid)throws SQLException { Cursor mCursor = db.query(true, CREDITCARDS_TABLE, new String[] { KEY_CCID, KEY_CCUNAME, KEY_CCNO, KEY_CVV, EXP_DATE, }, KEY_CCID + "=" + menuid, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //--------------------Entries into Credit Card Table------------------------------------ //---insert a title into the database--- public long insertCreditcard(int i, String j, String k, String l, String date) { ContentValues creditValues = new ContentValues(); creditValues.put(KEY_CCID, i); creditValues.put(KEY_CCUNAME, j); creditValues.put(KEY_CCNO, k); creditValues.put(KEY_CVV, l); creditValues.put(EXP_DATE, date); return db.insert(CREDITCARDS_TABLE, null, creditValues); } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertTitle(String name, String username, String password) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_Name, name); initialValues.put(KEY_Username, username); initialValues.put(KEY_Password, password); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_Name, KEY_Username, KEY_Password }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- public boolean updateTitle(long rowId, String name, String username, String password) { ContentValues args = new ContentValues(); args.put(KEY_Name, name); args.put(KEY_Username, username); args.put(KEY_Password, password); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } } ```
2011/03/08
[ "https://Stackoverflow.com/questions/5230321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/642623/" ]
`element.style` in Firebug is the style applied to the element, for exemple ``` <span style="padding: 10px;">My text</span> ``` `element.style` will have ``` element.style { padding: 10px; } ``` to override, the best way is to cleat the `style` attribute, append a `class` name and write the CSS you need. --- Regarding your modal problem, if you are using [jQuery UI Dialog](http://docs.jquery.com/UI/Dialog) component, why don't you set the width programmatically, like: ``` $( ".selector" ).dialog({ width: 460, maxWidth: 460, minWidth: 460 }); ```
This should work. The div [style^= is the Div 'Element Style' where you are able to modify any CSS Element. For Example: If the actual 'Element Style' width is 300px. ``` div [style^="width: 300px"]{ width:700px !important;} ``` This forces to overwrite the Element Style to width 700px.
11,705,243
I'm using next code to support sharing in my application: ``` //create the send intent Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); //set the type shareIntent.setType("text/plain"); //add a subject shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"subject"); String msg = https://play.google.com/store/apps/detailsid=com.rovio.amazingalex.premium //add the message shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg); //start the chooser for sharing startActivity(Intent.createChooser(shareIntent, "Sharing...")); ``` Even without any extra for image from my side, facebook takes a random image, that is not part of my application, but kind of associate with it. For example, when trying to share "Amazing Alex", this is the attached image: ![enter image description here](https://i.stack.imgur.com/n00vA.png) How can I change this image?
2012/07/28
[ "https://Stackoverflow.com/questions/11705243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1038702/" ]
I dont know how to change the image, Facebook is using, but another solution could be to post a Link to your own webpage, where there is only a picture of your App, which Facebook will use in the post, and where you can define a redirect in the HTML Meta tags to your Google Play site. ``` <head> <meta http-equiv="refresh" content="0; URL=https://play.google.com/store/apps/details?id=com.rovio.amazingalex.premium&feature=banner#?t=W251bGwsMSwyLDIwMSwiY29tLnJvdmlvLmFtYXppbmdhbGV4LnByZW1pdW0iXQ../"> </head> ``` So the tag above will redirect your visitor immediately to the page of google play. I justed tested it with a homepage of mine and Facebook is using the picture on it but the link redirects to google play. Be carefully: the page you are providing is shown shortly before the browser redirects.
You can use the [Facebook URL linter](https://developers.facebook.com/tools/debug/og/object?q=https://play.google.com/store/apps/details?id=net.jessechen.instawifi) to see what Facebook sees when they scrape the URL. As you can see, my Android app also has the same issue where the picture is an app under the "Users who viewed this also viewed" section. Unfortunately if you have to link directly to the Android Market, you can't change the image and as a consequence, there is no real solution to your problem unless Google decides to implement [OG tags](http://davidwalsh.name/facebook-meta-tags). You can put in your own url (yours was not working when I tried it) into the URL linter to see how Facebook scrapes your link.
11,705,243
I'm using next code to support sharing in my application: ``` //create the send intent Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); //set the type shareIntent.setType("text/plain"); //add a subject shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"subject"); String msg = https://play.google.com/store/apps/detailsid=com.rovio.amazingalex.premium //add the message shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg); //start the chooser for sharing startActivity(Intent.createChooser(shareIntent, "Sharing...")); ``` Even without any extra for image from my side, facebook takes a random image, that is not part of my application, but kind of associate with it. For example, when trying to share "Amazing Alex", this is the attached image: ![enter image description here](https://i.stack.imgur.com/n00vA.png) How can I change this image?
2012/07/28
[ "https://Stackoverflow.com/questions/11705243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1038702/" ]
Instead of String msg = <https://play.google.com/store/apps/detailsid=com.rovio.amazingalex.premium> You should use the following String msg = <https://market.android.com/search?q=pname:com.rovio.amazingalex.premium>
I dont know how to change the image, Facebook is using, but another solution could be to post a Link to your own webpage, where there is only a picture of your App, which Facebook will use in the post, and where you can define a redirect in the HTML Meta tags to your Google Play site. ``` <head> <meta http-equiv="refresh" content="0; URL=https://play.google.com/store/apps/details?id=com.rovio.amazingalex.premium&feature=banner#?t=W251bGwsMSwyLDIwMSwiY29tLnJvdmlvLmFtYXppbmdhbGV4LnByZW1pdW0iXQ../"> </head> ``` So the tag above will redirect your visitor immediately to the page of google play. I justed tested it with a homepage of mine and Facebook is using the picture on it but the link redirects to google play. Be carefully: the page you are providing is shown shortly before the browser redirects.
11,705,243
I'm using next code to support sharing in my application: ``` //create the send intent Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); //set the type shareIntent.setType("text/plain"); //add a subject shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"subject"); String msg = https://play.google.com/store/apps/detailsid=com.rovio.amazingalex.premium //add the message shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg); //start the chooser for sharing startActivity(Intent.createChooser(shareIntent, "Sharing...")); ``` Even without any extra for image from my side, facebook takes a random image, that is not part of my application, but kind of associate with it. For example, when trying to share "Amazing Alex", this is the attached image: ![enter image description here](https://i.stack.imgur.com/n00vA.png) How can I change this image?
2012/07/28
[ "https://Stackoverflow.com/questions/11705243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1038702/" ]
Instead of String msg = <https://play.google.com/store/apps/detailsid=com.rovio.amazingalex.premium> You should use the following String msg = <https://market.android.com/search?q=pname:com.rovio.amazingalex.premium>
You can use the [Facebook URL linter](https://developers.facebook.com/tools/debug/og/object?q=https://play.google.com/store/apps/details?id=net.jessechen.instawifi) to see what Facebook sees when they scrape the URL. As you can see, my Android app also has the same issue where the picture is an app under the "Users who viewed this also viewed" section. Unfortunately if you have to link directly to the Android Market, you can't change the image and as a consequence, there is no real solution to your problem unless Google decides to implement [OG tags](http://davidwalsh.name/facebook-meta-tags). You can put in your own url (yours was not working when I tried it) into the URL linter to see how Facebook scrapes your link.
12,824,633
We did some maintenance today, and moved our web forums from /forums into the root folder of the domain. We put in a redirect 301 in a .htaccess file: ``` Redirect 301 /forums/ http://www.ourforums.com/ ``` However, we used to have some links that contained duplicate /forums folders. I.e. www.ourforums.com/forums/forums/forum.1 Obviously the redirect from above now leads to /forum.1, which odes not exist. I would like the old link to actually point to www.ourforums.com/boards/forum.1. I attempted to use something like: ``` RewriteRule ^/forums/forums http://www.ourforums.com/boards/ [NC,R=301,L] ``` Regardless of what I tried though, the Redirect seems to supersede any RewriteRules I put in the same file, regardless of whether I place them before the Redirect. Is there any way I can somehow ensure the RewriteRule is handled before the Redirect?
2012/10/10
[ "https://Stackoverflow.com/questions/12824633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569711/" ]
This is because mod\_alias (the `Redirect` directive) and mod\_rewrite (the `RewriteRule` directive) is conflicting with each other in your case. Both of them play their part in the URL-file-mapping processing pipeline, where URI's get processed, rewritten, flagged, and eventually mapped to a resource and a response. You have a `Redirect` rule which is getting applied and the response is being flagged as a redirect. The thing about the `Redirect` directive is that it connects 2 path nodes together, meaning: ``` /forums/ ``` is connected to ``` http://www.ourforums.com/ ``` So anything below the `/forums` folder ends up getting redirected as well. This is why it's catching `^/forums/forums`. You can either stick to just mod\_rewrite or use a `RedirectMatch` that excludes `/forums/forums`: ``` RewriteRule ^/forums/forums(.*)$ http://www.ourforums.com/boards$1 [NC,R=301,L] RewriteRule ^/forums/(.*)$ http://www.ourforums.com/$1 [NC,R=301,L] ``` or ``` RedirectMatch 301 ^/forums/(?!forums)(.*)$ http://www.ourforums.com/$1 ```
Manually adding redirect statements like so seems to do the trick for me: ``` Redirect /forums/forums/forum.1 http://www.ourforums.com/boards/forum.1 ```
12,824,633
We did some maintenance today, and moved our web forums from /forums into the root folder of the domain. We put in a redirect 301 in a .htaccess file: ``` Redirect 301 /forums/ http://www.ourforums.com/ ``` However, we used to have some links that contained duplicate /forums folders. I.e. www.ourforums.com/forums/forums/forum.1 Obviously the redirect from above now leads to /forum.1, which odes not exist. I would like the old link to actually point to www.ourforums.com/boards/forum.1. I attempted to use something like: ``` RewriteRule ^/forums/forums http://www.ourforums.com/boards/ [NC,R=301,L] ``` Regardless of what I tried though, the Redirect seems to supersede any RewriteRules I put in the same file, regardless of whether I place them before the Redirect. Is there any way I can somehow ensure the RewriteRule is handled before the Redirect?
2012/10/10
[ "https://Stackoverflow.com/questions/12824633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569711/" ]
This is because mod\_alias (the `Redirect` directive) and mod\_rewrite (the `RewriteRule` directive) is conflicting with each other in your case. Both of them play their part in the URL-file-mapping processing pipeline, where URI's get processed, rewritten, flagged, and eventually mapped to a resource and a response. You have a `Redirect` rule which is getting applied and the response is being flagged as a redirect. The thing about the `Redirect` directive is that it connects 2 path nodes together, meaning: ``` /forums/ ``` is connected to ``` http://www.ourforums.com/ ``` So anything below the `/forums` folder ends up getting redirected as well. This is why it's catching `^/forums/forums`. You can either stick to just mod\_rewrite or use a `RedirectMatch` that excludes `/forums/forums`: ``` RewriteRule ^/forums/forums(.*)$ http://www.ourforums.com/boards$1 [NC,R=301,L] RewriteRule ^/forums/(.*)$ http://www.ourforums.com/$1 [NC,R=301,L] ``` or ``` RedirectMatch 301 ^/forums/(?!forums)(.*)$ http://www.ourforums.com/$1 ```
I had a somewhat similar problem. I was trying to add redirects from cpanel while I already had some rewrite rules written in my .htaccess file. The error I got was "No maching tag for " What I ultimately did was that kept a copy of my existing rules and cleaned the .htaccess. Then went and added all the redirects that I needed from cpanel, and then at the end put back my own rewrite rules in the end of the file. That worked for me
12,824,633
We did some maintenance today, and moved our web forums from /forums into the root folder of the domain. We put in a redirect 301 in a .htaccess file: ``` Redirect 301 /forums/ http://www.ourforums.com/ ``` However, we used to have some links that contained duplicate /forums folders. I.e. www.ourforums.com/forums/forums/forum.1 Obviously the redirect from above now leads to /forum.1, which odes not exist. I would like the old link to actually point to www.ourforums.com/boards/forum.1. I attempted to use something like: ``` RewriteRule ^/forums/forums http://www.ourforums.com/boards/ [NC,R=301,L] ``` Regardless of what I tried though, the Redirect seems to supersede any RewriteRules I put in the same file, regardless of whether I place them before the Redirect. Is there any way I can somehow ensure the RewriteRule is handled before the Redirect?
2012/10/10
[ "https://Stackoverflow.com/questions/12824633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569711/" ]
Manually adding redirect statements like so seems to do the trick for me: ``` Redirect /forums/forums/forum.1 http://www.ourforums.com/boards/forum.1 ```
I had a somewhat similar problem. I was trying to add redirects from cpanel while I already had some rewrite rules written in my .htaccess file. The error I got was "No maching tag for " What I ultimately did was that kept a copy of my existing rules and cleaned the .htaccess. Then went and added all the redirects that I needed from cpanel, and then at the end put back my own rewrite rules in the end of the file. That worked for me
28,558,421
I have a web service which returns a Unique ID when I provide a valid request. This web service is username/password protected and I have the credentials for the same. The Service request returns a expected response in SOAP UI where I added the username password fields in the resource properties. Now I want to access the same web service in OSB. I get the error: ``` 'The invocation resulted in an error: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received..' ``` How do I access this web service? I added the following code in the request part of the operation I am trying to invoke in the wsdl. ``` <wsp:Policy wsu:Id="WS-Policy-UNT" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss- wssecurity-utility-1.0.xsd"> <wssp:Identity xmlns:wssp="http://www.bea.com/wls90/security/policy"> <wssp:SupportedTokens> <wssp:SecurityToken TokenType="http://docs.oasis-open.org/wss/2004/01/oasis- 200401-wss-username-token-profile-1.0#UsernameToken"> <wssp:UsePassword Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/> </wssp:SecurityToken> </wssp:SupportedTokens> </wssp:Identity> </wsp:Policy> ``` I also added a Service account with the username password in the security tab of the same. I am still getting the same error. Please guide me...
2015/02/17
[ "https://Stackoverflow.com/questions/28558421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528200/" ]
My issue resolved by updating xcode to beta 6.2 version 5 and adding [WKInterfaceController openParentApplication:@{@"msgStatus": @"unread"} reply:nil]; at watchkit side which was mentioned in previous answer which is deleted now dnt knw why :-( ,but I want to thank him(I dnt remember that persons name). plz post dat answer again.
Make sure that you are using the correct and the up to dated provisioning.
28,558,421
I have a web service which returns a Unique ID when I provide a valid request. This web service is username/password protected and I have the credentials for the same. The Service request returns a expected response in SOAP UI where I added the username password fields in the resource properties. Now I want to access the same web service in OSB. I get the error: ``` 'The invocation resulted in an error: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received..' ``` How do I access this web service? I added the following code in the request part of the operation I am trying to invoke in the wsdl. ``` <wsp:Policy wsu:Id="WS-Policy-UNT" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss- wssecurity-utility-1.0.xsd"> <wssp:Identity xmlns:wssp="http://www.bea.com/wls90/security/policy"> <wssp:SupportedTokens> <wssp:SecurityToken TokenType="http://docs.oasis-open.org/wss/2004/01/oasis- 200401-wss-username-token-profile-1.0#UsernameToken"> <wssp:UsePassword Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/> </wssp:SecurityToken> </wssp:SupportedTokens> </wssp:Identity> </wsp:Policy> ``` I also added a Service account with the username password in the security tab of the same. I am still getting the same error. Please guide me...
2015/02/17
[ "https://Stackoverflow.com/questions/28558421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528200/" ]
I got it worked by following this video ``` https://www.youtube.com/watch?v=0ts196U4xS4 ``` Are you sure that you have turned on 'App Groups' for both iPhone part & iwatchkit extension ? Also the app groups selected must be the same.
Make sure that you are using the correct and the up to dated provisioning.
28,558,421
I have a web service which returns a Unique ID when I provide a valid request. This web service is username/password protected and I have the credentials for the same. The Service request returns a expected response in SOAP UI where I added the username password fields in the resource properties. Now I want to access the same web service in OSB. I get the error: ``` 'The invocation resulted in an error: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received..' ``` How do I access this web service? I added the following code in the request part of the operation I am trying to invoke in the wsdl. ``` <wsp:Policy wsu:Id="WS-Policy-UNT" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss- wssecurity-utility-1.0.xsd"> <wssp:Identity xmlns:wssp="http://www.bea.com/wls90/security/policy"> <wssp:SupportedTokens> <wssp:SecurityToken TokenType="http://docs.oasis-open.org/wss/2004/01/oasis- 200401-wss-username-token-profile-1.0#UsernameToken"> <wssp:UsePassword Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/> </wssp:SecurityToken> </wssp:SupportedTokens> </wssp:Identity> </wsp:Policy> ``` I also added a Service account with the username password in the security tab of the same. I am still getting the same error. Please guide me...
2015/02/17
[ "https://Stackoverflow.com/questions/28558421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528200/" ]
I got it worked by following this video ``` https://www.youtube.com/watch?v=0ts196U4xS4 ``` Are you sure that you have turned on 'App Groups' for both iPhone part & iwatchkit extension ? Also the app groups selected must be the same.
My issue resolved by updating xcode to beta 6.2 version 5 and adding [WKInterfaceController openParentApplication:@{@"msgStatus": @"unread"} reply:nil]; at watchkit side which was mentioned in previous answer which is deleted now dnt knw why :-( ,but I want to thank him(I dnt remember that persons name). plz post dat answer again.
63,217
Depending on the interval, yahoo finance seems to show different prices on the chart for SWRD.L: [Interval=1d](https://ca.finance.yahoo.com/quote/SWRD.L/chart?p=SWRD.L#eyJpbnRlcnZhbCI6ImRheSIsInBlcmlvZGljaXR5IjoxLCJ0aW1lVW5pdCI6bnVsbCwiY2FuZGxlV2lkdGgiOjUuMTEyNjEyNjEyNjEyNjEzLCJmbGlwcGVkIjpmYWxzZSwidm9sdW1lVW5kZXJsYXkiOnRydWUsImFkaiI6dHJ1ZSwiY3Jvc3NoYWlyIjp0cnVlLCJjaGFydFR5cGUiOiJsaW5lIiwiZXh0ZW5kZWQiOmZhbHNlLCJtYXJrZXRTZXNzaW9ucyI6e30sImFnZ3JlZ2F0aW9uVHlwZSI6Im9obGMiLCJjaGFydFNjYWxlIjoibGluZWFyIiwic3R1ZGllcyI6eyLigIx2b2wgdW5kcuKAjCI6eyJ0eXBlIjoidm9sIHVuZHIiLCJpbnB1dHMiOnsiaWQiOiLigIx2b2wgdW5kcuKAjCIsImRpc3BsYXkiOiLigIx2b2wgdW5kcuKAjCJ9LCJvdXRwdXRzIjp7IlVwIFZvbHVtZSI6IiMwMGIwNjEiLCJEb3duIFZvbHVtZSI6IiNmZjMzM2EifSwicGFuZWwiOiJjaGFydCIsInBhcmFtZXRlcnMiOnsid2lkdGhGYWN0b3IiOjAuNDUsImNoYXJ0TmFtZSI6ImNoYXJ0In19fSwicGFuZWxzIjp7ImNoYXJ0Ijp7InBlcmNlbnQiOjEsImRpc3BsYXkiOiJTV1JELkwiLCJjaGFydE5hbWUiOiJjaGFydCIsImluZGV4IjowLCJ5QXhpcyI6eyJuYW1lIjoiY2hhcnQiLCJwb3NpdGlvbiI6bnVsbH0sInlheGlzTEhTIjpbXSwieWF4aXNSSFMiOlsiY2hhcnQiLCLigIx2b2wgdW5kcuKAjCJdfX0sInNldFNwYW4iOm51bGwsImxpbmVXaWR0aCI6Miwic3RyaXBlZEJhY2tncm91bmQiOnRydWUsImV2ZW50cyI6dHJ1ZSwiY29sb3IiOiIjMDA4MWYyIiwic3RyaXBlZEJhY2tncm91ZCI6dHJ1ZSwicmFuZ2UiOm51bGwsImV2ZW50TWFwIjp7ImNvcnBvcmF0ZSI6eyJkaXZzIjp0cnVlLCJzcGxpdHMiOnRydWV9LCJzaWdEZXYiOnt9fSwic3ltYm9scyI6W3sic3ltYm9sIjoiU1dSRC5MIiwic3ltYm9sT2JqZWN0Ijp7InN5bWJvbCI6IlNXUkQuTCIsInF1b3RlVHlwZSI6IkVURiIsImV4Y2hhbmdlVGltZVpvbmUiOiJFdXJvcGUvTG9uZG9uIn0sInBlcmlvZGljaXR5IjoxLCJpbnRlcnZhbCI6ImRheSIsInRpbWVVbml0IjpudWxsLCJzZXRTcGFuIjpudWxsfV19) => Final price is ~20 [![enter image description here](https://i.stack.imgur.com/xMxjw.png)](https://i.stack.imgur.com/xMxjw.png) [Interval=1h](https://ca.finance.yahoo.com/quote/SWRD.L/chart?p=SWRD.L#eyJpbnRlcnZhbCI6NjAsInBlcmlvZGljaXR5IjoxLCJ0aW1lVW5pdCI6Im1pbnV0ZSIsImNhbmRsZVdpZHRoIjoxLjE3NDk0ODI0MDE2NTYzMTUsImZsaXBwZWQiOmZhbHNlLCJ2b2x1bWVVbmRlcmxheSI6dHJ1ZSwiYWRqIjp0cnVlLCJjcm9zc2hhaXIiOnRydWUsImNoYXJ0VHlwZSI6ImxpbmUiLCJleHRlbmRlZCI6ZmFsc2UsIm1hcmtldFNlc3Npb25zIjp7fSwiYWdncmVnYXRpb25UeXBlIjoib2hsYyIsImNoYXJ0U2NhbGUiOiJsaW5lYXIiLCJwYW5lbHMiOnsiY2hhcnQiOnsicGVyY2VudCI6MSwiZGlzcGxheSI6IlNXUkQuTCIsImNoYXJ0TmFtZSI6ImNoYXJ0IiwiaW5kZXgiOjAsInlBeGlzIjp7Im5hbWUiOiJjaGFydCIsInBvc2l0aW9uIjpudWxsfSwieWF4aXNMSFMiOltdLCJ5YXhpc1JIUyI6WyJjaGFydCIsIuKAjHZvbCB1bmRy4oCMIl19fSwic2V0U3BhbiI6bnVsbCwibGluZVdpZHRoIjoyLCJzdHJpcGVkQmFja2dyb3VuZCI6dHJ1ZSwiZXZlbnRzIjp0cnVlLCJjb2xvciI6IiMwMDgxZjIiLCJzdHJpcGVkQmFja2dyb3VkIjp0cnVlLCJyYW5nZSI6bnVsbCwiZXZlbnRNYXAiOnsiY29ycG9yYXRlIjp7ImRpdnMiOnRydWUsInNwbGl0cyI6dHJ1ZX0sInNpZ0RldiI6e319LCJzeW1ib2xzIjpbeyJzeW1ib2wiOiJTV1JELkwiLCJzeW1ib2xPYmplY3QiOnsic3ltYm9sIjoiU1dSRC5MIiwicXVvdGVUeXBlIjoiRVRGIiwiZXhjaGFuZ2VUaW1lWm9uZSI6IkV1cm9wZS9Mb25kb24ifSwicGVyaW9kaWNpdHkiOjEsImludGVydmFsIjo2MCwidGltZVVuaXQiOiJtaW51dGUiLCJzZXRTcGFuIjpudWxsfV0sInN0dWRpZXMiOnsi4oCMdm9sIHVuZHLigIwiOnsidHlwZSI6InZvbCB1bmRyIiwiaW5wdXRzIjp7ImlkIjoi4oCMdm9sIHVuZHLigIwiLCJkaXNwbGF5Ijoi4oCMdm9sIHVuZHLigIwifSwib3V0cHV0cyI6eyJVcCBWb2x1bWUiOiIjMDBiMDYxIiwiRG93biBWb2x1bWUiOiIjZmYzMzNhIn0sInBhbmVsIjoiY2hhcnQiLCJwYXJhbWV0ZXJzIjp7IndpZHRoRmFjdG9yIjowLjQ1LCJjaGFydE5hbWUiOiJjaGFydCIsInBhbmVsTmFtZSI6ImNoYXJ0In19fSwiY3VzdG9tUmFuZ2UiOm51bGx9) => Final price is ~28 [![enter image description here](https://i.stack.imgur.com/PNI9y.png)](https://i.stack.imgur.com/PNI9y.png) I use the API for some analysis and realized this discrepancy. Is this a feature or a bug? It might be I just use yahoo finance wrongly. Thanks
2021/04/05
[ "https://quant.stackexchange.com/questions/63217", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/51176/" ]
### It seems to be a bug on Yahoo Finance: If we take a look at alternative sites such as [Bloomberg](https://www.bloomberg.com/quote/SWRD:LN) and [State Street](https://www.ssga.com/uk/en_gb/institutional/etfs/funds/spdr-msci-world-ucits-etf-sppw-gy) they both report a NAV of 28.22 USD as of 1st of April, for the ETF with ticker SWRD.L (as seen on your second picture). **However, as seen on the State Street website, the same asset exist on the London Stock Exchange in GBP (ticker symbol [SWLD.L](https://finance.yahoo.com/quote/SWLD.L/)) and the last price is 20.41 GBP (which is depicted in your first picture).** The daily graph as-well as the historical data for SWRD.L (in USD) on Yahoo Finance, is the exact same as the SWLD.L (in GBP). Therefore, it looks like a bug.
This is not an answer. I'm posting it to show a variation where the chart contains prices in both currencies: [1d chart with USD and GBP](https://ca.finance.yahoo.com/quote/SWRD.L/chart?p=SWRD.L#eyJpbnRlcnZhbCI6ImRheSIsInBlcmlvZGljaXR5IjoxLCJ0aW1lVW5pdCI6bnVsbCwiY2FuZGxlV2lkdGgiOjgsImZsaXBwZWQiOmZhbHNlLCJ2b2x1bWVVbmRlcmxheSI6dHJ1ZSwiYWRqIjp0cnVlLCJjcm9zc2hhaXIiOnRydWUsImNoYXJ0VHlwZSI6ImxpbmUiLCJleHRlbmRlZCI6ZmFsc2UsIm1hcmtldFNlc3Npb25zIjp7fSwiYWdncmVnYXRpb25UeXBlIjoib2hsYyIsImNoYXJ0U2NhbGUiOiJsaW5lYXIiLCJzdHVkaWVzIjp7IuKAjHZvbCB1bmRy4oCMIjp7InR5cGUiOiJ2b2wgdW5kciIsImlucHV0cyI6eyJpZCI6IuKAjHZvbCB1bmRy4oCMIiwiZGlzcGxheSI6IuKAjHZvbCB1bmRy4oCMIn0sIm91dHB1dHMiOnsiVXAgVm9sdW1lIjoiIzAwYjA2MSIsIkRvd24gVm9sdW1lIjoiI2ZmMzMzYSJ9LCJwYW5lbCI6ImNoYXJ0IiwicGFyYW1ldGVycyI6eyJ3aWR0aEZhY3RvciI6MC40NSwiY2hhcnROYW1lIjoiY2hhcnQifX19LCJwYW5lbHMiOnsiY2hhcnQiOnsicGVyY2VudCI6MSwiZGlzcGxheSI6IlNXUkQuTCIsImNoYXJ0TmFtZSI6ImNoYXJ0IiwiaW5kZXgiOjAsInlBeGlzIjp7Im5hbWUiOiJjaGFydCIsInBvc2l0aW9uIjpudWxsfSwieWF4aXNMSFMiOltdLCJ5YXhpc1JIUyI6WyJjaGFydCIsIuKAjHZvbCB1bmRy4oCMIl19fSwic2V0U3BhbiI6e30sImxpbmVXaWR0aCI6Miwic3RyaXBlZEJhY2tncm91bmQiOnRydWUsImV2ZW50cyI6dHJ1ZSwiY29sb3IiOiIjMDA4MWYyIiwic3RyaXBlZEJhY2tncm91ZCI6dHJ1ZSwiZXZlbnRNYXAiOnsiY29ycG9yYXRlIjp7ImRpdnMiOnRydWUsInNwbGl0cyI6dHJ1ZX0sInNpZ0RldiI6e319LCJzeW1ib2xzIjpbeyJzeW1ib2wiOiJTV1JELkwiLCJzeW1ib2xPYmplY3QiOnsic3ltYm9sIjoiU1dSRC5MIiwicXVvdGVUeXBlIjoiRVRGIiwiZXhjaGFuZ2VUaW1lWm9uZSI6IkV1cm9wZS9Mb25kb24ifSwicGVyaW9kaWNpdHkiOjEsImludGVydmFsIjoiZGF5IiwidGltZVVuaXQiOm51bGwsInNldFNwYW4iOnt9fV19) [![enter image description here](https://i.stack.imgur.com/ke1Qh.png)](https://i.stack.imgur.com/ke1Qh.png)
18,008,306
I want to partially view a webpage on webview android and remove some div element from the webpage. I have a webpage like this ``` <!DOCTYPE html> <body> <div id="a"><p>Remove aa</p></div> <div id="b"><p>bb</p></div> </body></html> ``` Now I want to remove the div with id 'a' from the webpage. I tried to code it with Jsoup but I am not well enough to make it out. Please see my full code: ``` import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.webkit.WebView; import android.webkit.WebViewClient; public class CustomWebsite extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_website); Document doc; String htmlcode = ""; try { doc = Jsoup.connect("http://skyasim.info/ab.html").get(); doc.head().getElementsByTag("DIV#a").remove(); htmlcode = doc.html(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } webView = (WebView) findViewById(R.id.webView_test); webView.setWebViewClient(new myWebClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("htmlcode"); } public class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return true; } } } ```
2013/08/02
[ "https://Stackoverflow.com/questions/18008306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862434/" ]
You can do this without using Jsoup you know. Just use plain old javascript. The following code will show how to remove an element from the HTML page and display the rest. ``` final WebView mWebView = (WebView) findViewById(R.id.mWebViewId); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mWebView.loadUrl("javascript:(function() { " + "document.getElementById('a')[0].style.display='none'; " + "})()"); } }); mWebView.loadUrl(youUrl); ```
Remove it from the document by selecting it and then using the `remove`-method. ``` doc.select("div#a").remove(); System.out.println(doc); ``` --- Example: ``` Document doc = Jsoup.parse(html); System.out.println("Before removal of 'div id=\"a\"' = "); System.out.println("-------------------------"); System.out.println(doc); doc.select("div#a").remove(); System.out.println("\n\nAfter removal of 'div id=\"a\"' = "); System.out.println("-------------------------"); System.out.println(doc); ``` will result in ``` Before removal of 'div id="a"' = ------------------------- <!DOCTYPE html> <html> <head></head> <body> <div id="a"> <p>Remove aa</p> </div> <div id="b"> <p>bb</p> </div> </body> </html> After removal of 'div id="a"' = ------------------------- <!DOCTYPE html> <html> <head></head> <body> <div id="b"> <p>bb</p> </div> </body> </html> ```
18,008,306
I want to partially view a webpage on webview android and remove some div element from the webpage. I have a webpage like this ``` <!DOCTYPE html> <body> <div id="a"><p>Remove aa</p></div> <div id="b"><p>bb</p></div> </body></html> ``` Now I want to remove the div with id 'a' from the webpage. I tried to code it with Jsoup but I am not well enough to make it out. Please see my full code: ``` import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.webkit.WebView; import android.webkit.WebViewClient; public class CustomWebsite extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_website); Document doc; String htmlcode = ""; try { doc = Jsoup.connect("http://skyasim.info/ab.html").get(); doc.head().getElementsByTag("DIV#a").remove(); htmlcode = doc.html(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } webView = (WebView) findViewById(R.id.webView_test); webView.setWebViewClient(new myWebClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("htmlcode"); } public class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return true; } } } ```
2013/08/02
[ "https://Stackoverflow.com/questions/18008306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862434/" ]
You can do this without using Jsoup you know. Just use plain old javascript. The following code will show how to remove an element from the HTML page and display the rest. ``` final WebView mWebView = (WebView) findViewById(R.id.mWebViewId); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { mWebView.loadUrl("javascript:(function() { " + "document.getElementById('a')[0].style.display='none'; " + "})()"); } }); mWebView.loadUrl(youUrl); ```
I had tried to use Jsoup to do something similar before, but my app always crash. If you are open to using Javascript only (which helps to make your app size smaller), here is what I did for my app: ``` webview3.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { view.loadUrl("javascript:var con = document.getElementById('a'); " + "con.style.display = 'none'; "); } }); ``` Hope my Javascript is correct. The idea here is to use Javascript to hide the div after the page has finished loading.
43,887,759
I'm trying to read from a file in my project's directory. My problem is, that depending on the caller, the path changes. The caller changes, because I want to unit test this code and the caller is not `Main.go` anymore. This is what my project structure looks like: [![Project Structure](https://i.stack.imgur.com/uO9Kx.png)](https://i.stack.imgur.com/uO9Kx.png) The code where I try to access `specialChars.txt` from looks like this: ``` func RemoveSpecialChars(word string) string { file, err := ioutil.ReadFile("wordlists/specialChars.txt") [...] } ``` This code works for the start from `Main.go` but not for the start from `CleanupUtil_test.go`. To get it working from the test I would need `file, err := ioutil.ReadFile("../wordlists/specialChars.txt")` I found answers like this one: <https://stackoverflow.com/a/32163888/2837489> `_, filename, _, ok := runtime.Caller(0)` which is obviously also dependent on the caller. Is it possible to get the projects root path independent of the calling function? Or is my code design wrong? Should I pass the file path into the function?
2017/05/10
[ "https://Stackoverflow.com/questions/43887759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2837489/" ]
Starting from Go 1.16, you can use the [embed](https://pkg.go.dev/embed) package. This allows you to embed the files in the running go program. It comes with the caveat that the referenced directory needs to exist at or below the embedding file. In your case, the structure would look as follows: ``` -- main.go -- cleanup -- wordlist \- specialChars.txt CleanupUtil.go CleanupUtil_test.go ``` You can reference the file using a go directive ``` // CleanupUtil.go package cleanup import ( "embed" ) //go:embed wordlists/specialChars.txt var content embed.FS func RemoveSpecialChars(word string) string { file, err := content.ReadFile("wordlists/specialChars.txt") [...] } ``` This program will run successfully regardless of where the program is executed. You should be able to reference this code in both your `main.go` file and your `CleanupUtil_test.go` file.
Pass in the filepath as a parameter to the function (as indicated in your last question). **More details:** The relative path `"wordlists/specialChars.txt"` is in fact not dependent on where the source file is located (such as `Main.go` or `CleanupUtil_test.go`), but where you execute it from. So you could run your tests from your root directory and then it would actually work. In short, the current working directory is relevant. Still, I'd recommend specifying the path, because that makes your function more reusable and universal. Maybe you don't even need to put this information into a file, but can simply have a string containing those chars. In this case you could also check if <https://golang.org/pkg/regexp/#Regexp.ReplaceAll> already covers your use case.
46,780,087
I am passing a URL to a block of code in which I need to insert a new element into the regex. Pretty sure the regex is valid and the code seems right but no matter what I can't seem to execute the match for regex! ``` //** Incoming url's //** url e.g. api/223344 //** api/11aa/page/2017 //** Need to match to the following //** dir/api/12ab/page/1999 //** Hence the need to add dir at the front var url = req.url; //** pass in: /^\/api\/([a-zA-Z0-9-_~ %]+)(?:\/page\/([a-zA-Z0-9-_~ %]+))?$/ var re = myregex.toString(); //** Insert dir into regex: /^dir\/api\/([a-zA-Z0-9-_~ %]+)(?:\/page\/([a-zA-Z0-9-_~ %]+))?$/ var regVar = re.substr(0, 2) + 'dir' + re.substr(2); var matchedData = url.match(regVar); matchedData === null ? console.log('NO') : console.log('Yay'); ``` I hope I am just missing the obvious but can anyone see why I can't match and always returns NO? Thanks
2017/10/16
[ "https://Stackoverflow.com/questions/46780087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446190/" ]
Let's break down your regex `^\/api\/` this matches the beginning of a string, and it looks to match exactly the string "/api" `([a-zA-Z0-9-_~ %]+)` this is a capturing group: this one specifically will capture anything inside those brackets, with the `+` indicating to capture 1 or more, so for example, this section will match `abAB25-_ %` `(?:\/page\/([a-zA-Z0-9-_~ %]+))` this groups multiple tokens together as well, but does not create a capturing group like above (the `?:` makes it non-captuing). You are first matching a string exactly like "/page/" followed by a group exactly like mentioned in the paragraph above (that matches a-z, A-Z, 0-9, etc. `?$` is at the end, and the `?` means capture 0 or more of the precending group, and the `$` matches the end of the string This regex will match this string, for example: `/api/abAB25-_ %/page/abAB25-_ %` You may be able to take advantage of capturing groups, however, and use something like this instead to get similar results: `^\/api\/([a-zA-Z0-9-_~ %]+)\/page\/\1?$`. Here, we are using `\1` to reference that first capturing group and match exactly the same tokens it is matching. EDIT: actually, this probably won't work, since the text after /api/ and the text after /page/ will most likely be different, carrying on... Afterwards, you are are adding "dir" to the beginning of your search, so you can now match someting like this: `dir/api/abAB25-_ %/page/abAB25-_ %` You have also now converted the regex to a string, so like Crayon Violent pointed out in their comment, this will break your expected funtionality. You can fix this by using `.source` on your regex: `var matchedData = url.match(regVar.source);` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source> Now you can properly match a string like this: `dir/api/11aa/page/2017` see this example: <https://repl.it/Mj8h>
As mentioned by Crayon Violent in the comments, it seems you're passing a String rather than a regular expression in the .match() function. maybe try the following: ``` url.match(new RegExp(regVar, "i")); ``` to convert the string to a regular expression. The "i" is for ignore case; don't know that's what you want. Learn more here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp>
46,945,026
The ['Volatile Rule'](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html) says that 'A write to a volatile field happens-before every subsequent read of that same field', I DO know that this means if we write to a volatile thread and read another volatile in another thread, then there are NO happens-before relationship between the two actions. My queustion is why we must use 'same field'?
2017/10/26
[ "https://Stackoverflow.com/questions/46945026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351818/" ]
That is how it should work isn't? All we want is the data shared between threads should be consistent, so why should we have happens-before relationship between different variables? It makes sense to have happens before relationship on same field because if we don't then it may lead to data race. isn't?
Because what you are asking for is covered by `synchronized`: writing to any field of an object through a synchronized method *happens before* subsequently reading any other field of the same object through a synchronized method.
15,151,523
The following R code give me only half of a normal distribution; what should I change to the code in order to get the other half? ``` halfnormal <- function(n){ vector <- rep(0,n) for(i in 1:n){ uni_random <- runif(2) y <- -log(uni_random) while(y[2] < (y[1]-1)^2/2){ uni_random <- runif(2) y <- -log(uni_random) } vector[i] <- y[1] } vector } output <- halfnormal(1000) hist(output) ```
2013/03/01
[ "https://Stackoverflow.com/questions/15151523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069764/" ]
If you insist on using that code to generate a standard normal (not recommended, as `rnorm` will be much faster and more accurate), just dot product that entire vector by an equal-length vector consisting of random `(-1, +1)` values. By the way, the half-normal is also known as the [Chi distribution](http://en.wikipedia.org/wiki/Chi_distribution) (with 1 degree of freedom).
This looks bit like Ziggurat algorithm with Marsaglia's modification, but it's bit different? If you don't want to use any guaranteed-to-work random number generators in R, perhaps this works: ``` halfnormal <- function(n){ vector <- rep(0,n) for(i in 1:n){ uni_random <- runif(2) y <- -log(uni_random) while(y[2] < (y[1]-1)^2/2){ uni_random <- runif(2) y <- -log(uni_random) } vector[i] <- sample(c(-1,1),size=1)*y[1] #randomly select the tail } vector } output <- halfnormal(1000) hist(output) ```
2,925,209
I made a mistake while proving the theorem in the title, however, I don't see where. Here's the theorem: > > Let $C$ be closed and limited subsets of $\Bbb{R}$. Then $\bigcap\_{i \in K} (C\_i) = \emptyset \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcap\_{i \in F} (C\_i) = \emptyset$ > > > Proof (proceeds by finding equivalent problems). $$\Bbb{R} - \bigcap\_{i \in K} (C\_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \Bbb{R} - \bigcap\_{i \in F} (C\_i) = \Bbb{R}$$ $$\bigcup\_{i \in K} (\Bbb{R} - C\_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcup\_{i \in F} (\Bbb{R} - C\_i) = \Bbb{R}$$ Let $O\_i = \Bbb{R} - C\_i$. Note that $\forall i \in K. \, O\_i$ is open and unlimited subset of $\Bbb{R}$ $$\bigcup\_{i \in K} (O\_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcup\_{i \in F} (O\_i) = \Bbb{R}$$ And the last is false since if we take $\forall i \in \Bbb{N}. \, O\_i = (-\infty , i), B = \bigcup\_{i \in \Bbb{N}} (O\_i) = \Bbb{R}$ but there are no finite subsets of N which generates R in that way. I cannot.find the flaw in my proof. Can you please help me with that?
2018/09/21
[ "https://math.stackexchange.com/questions/2925209", "https://math.stackexchange.com", "https://math.stackexchange.com/users/419751/" ]
I think there might be a fractal solution, with two shapes bounded by this sequence of horizontal and vertical lines: $$(0,0),(1,0),(1,x),(1+x^2,x),(1+x^2,x+x^3),(1+x^2+x^4,x+x^3),...$$ end at the far corner $$\left(\frac1{1-x^2},\frac x{1-x^2}\right)$$
Other comments have answered the question you asked (namely, is your solution correct?). I'm going to push on and help you see where the really interesting part of this problem lies (a part that I will not solve because I don't know how to do it!). Despite your solution being not quite right, it's *almost* right. It's still possible to split the strip into exactly two rectangles (except for particular values of $k$): you make one of them *almost* $1 \times k$, and the other be $1$ unit tall and about $1/k$ wide. More precisely, you want to get this picture: ``` |----------------------|-| | | | | | | |----------------------|-| ``` where the first rectangle is $1 \times a$, and the other is $1 \times b$, and 1. $a + b = k$ 2. $a/1$ is the same as $1/b$, so that they are similar. Solving gives $ab = 1$, so $a + \frac{1}{a} = k$, hence $$ a^2 -ka + 1 = 0 $$ and $$ a = \frac{k \pm \sqrt{k^2 - 4}}{2} $$ Because only values of $a$ less than $k$ make sense, only one of these two roots is a good choice. There are two clear problems remaining: 1. If $k = 2$, the two rectangles are both $1 \times 2$, and hence are similar *and* congruent, adn you need a different solution (if there is one). 2. For $k < 2$, this approach, as written, doesn't get you an answer. But if you rotate the diagram above by 90 degrees, you can still get something by essentially the same method. The $1 \times k$ rectangle becomes $k \times 1$, which you can scale down to $1 \times 1/k$, for which the previous method works when $1/k > 2$, i.e., when $k < \frac{1}{2}$. (Thanks to @JaapScherphuis for pointing this out). So the whole thing boils down to the $1/2 \le k \le 2$ question (for which I don't see an obvious answer in either direction, personally). As Jaap observes, rotation lets us assume $k > 1$, so really the unanswered range is $1 \le k \le 2$.
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Here is another piece of code which can be used if you have to distinguish between a single- and a double-click and have to take a specific action in either case. ``` import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class DoubleClickDetectionTest extends Application { boolean dragFlag = false; int clickCounter = 0; ScheduledThreadPoolExecutor executor; ScheduledFuture<?> scheduledFuture; public DoubleClickDetectionTest() { executor = new ScheduledThreadPoolExecutor(1); executor.setRemoveOnCancelPolicy(true); } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { StackPane root = new StackPane(); primaryStage.setScene(new Scene(root, 400, 400)); primaryStage.show(); root.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY)) { dragFlag = true; } } }); root.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY)) { if (!dragFlag) { System.out.println(++clickCounter + " " + e.getClickCount()); if (e.getClickCount() == 1) { scheduledFuture = executor.schedule(() -> singleClickAction(), 500, TimeUnit.MILLISECONDS); } else if (e.getClickCount() > 1) { if (scheduledFuture != null && !scheduledFuture.isCancelled() && !scheduledFuture.isDone()) { scheduledFuture.cancel(false); doubleClickAction(); } } } dragFlag = false; } } }); } @Override public void stop() { executor.shutdown(); } private void singleClickAction() { System.out.println("Single-click action executed."); } private void doubleClickAction() { System.out.println("Double-click action executed."); } } ```
An alternative to single click vs. double click that I'm using is single click vs. press-and-hold (for about a quarter to a half second or so), then release the button. The technique can use a threaded abortable timer as in some of the code snippets above to distinguish between the two. Assuming that the actual event handling happens on the button release, this alternative has the advantage that single click works normally (i.e., without any delay), and for press-and-hold you can give the user some visual feedback when the button has been held long enough to be released (so there's never any ambiguity about which action was performed).
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Yes you can detect single, double even multiple clicks: ``` myNode.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ System.out.println("Double clicked"); } } } }); ``` `MouseButton.PRIMARY` is used to determine if the left (commonly) mouse button is triggered the event. Read the api of `getClickCount()` to conclude that there maybe multiple click counts other than single or double. However I find it hard to distinguish between single and double click events. Because the first click count of the double click will rise a single event as well.
Since it is not possible to distinguish between single-click and double-click by default, we use the following approach: On single-click, we wrap the single-click operation in an abortable runnable. This runnable waits a certain amount of time (i.e., `SINGLE_CLICK_DELAY`) before being executed. In the meantime, if a second click, i.e., a double-click, occurs, the single-click operation gets aborted and only the double-click operation is performed. This way, either the single-click *or* the double-click operation is performed, but never both. --- Following is the full code. To use it, only the three `TODO` lines have to be replaced by the wanted handlers. ``` private static final int SINGLE_CLICK_DELAY = 250; private ClickRunner latestClickRunner = null; private class ClickRunner implements Runnable { private final Runnable onSingleClick; private boolean aborted = false; public ClickRunner(Runnable onSingleClick) { this.onSingleClick = onSingleClick; } public void abort() { this.aborted = true; } @Override public void run() { try { Thread.sleep(SINGLE_CLICK_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } if (!aborted) { System.out.println("Execute Single Click"); Platform.runLater(() -> onSingleClick.run()); } } } private void init() { container.setOnMouseClicked(me -> { switch (me.getButton()) { case PRIMARY: if (me.getClickCount() == 1) { System.out.println("Single Click"); latestClickRunner = new ClickRunner(() -> { // TODO: Single-left-click operation }); CompletableFuture.runAsync(latestClickRunner); } if (me.getClickCount() == 2) { System.out.println("Double Click"); if (latestClickRunner != null) { System.out.println("-> Abort Single Click"); latestClickRunner.abort(); } // TODO: Double-left-click operation } break; case SECONDARY: // TODO: Right-click operation break; default: break; } }); } ```
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Adhering to Java SE 8 lambda expressions would look something like this: ``` node.setOnMouseClicked(event -> { if(event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { handleSomeAction(); } }); ``` Once you get used to lambda expressions - they end up being more understandable than the original class instantiation and overriding (x) method. -In my opinion-
If you are testing how many mouse buttons (==2) are pressed, do not code it in sub-method! The next is working: ``` listView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if( mouseEvent.getButton().equals(MouseButton.SECONDARY)) { System.out.println("isSecondaryButtonDown"); mouseEvent.consume(); // .... } else if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ System.out.println("Double clicked"); // mousePressedInListViewDC(mouseEvent); } else if(mouseEvent.getClickCount() == 1){ System.out.println("1 clicked"); mousePressedInListView1C(mouseEvent); } } } }) ``` ;
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Here is another piece of code which can be used if you have to distinguish between a single- and a double-click and have to take a specific action in either case. ``` import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class DoubleClickDetectionTest extends Application { boolean dragFlag = false; int clickCounter = 0; ScheduledThreadPoolExecutor executor; ScheduledFuture<?> scheduledFuture; public DoubleClickDetectionTest() { executor = new ScheduledThreadPoolExecutor(1); executor.setRemoveOnCancelPolicy(true); } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { StackPane root = new StackPane(); primaryStage.setScene(new Scene(root, 400, 400)); primaryStage.show(); root.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY)) { dragFlag = true; } } }); root.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton().equals(MouseButton.PRIMARY)) { if (!dragFlag) { System.out.println(++clickCounter + " " + e.getClickCount()); if (e.getClickCount() == 1) { scheduledFuture = executor.schedule(() -> singleClickAction(), 500, TimeUnit.MILLISECONDS); } else if (e.getClickCount() > 1) { if (scheduledFuture != null && !scheduledFuture.isCancelled() && !scheduledFuture.isDone()) { scheduledFuture.cancel(false); doubleClickAction(); } } } dragFlag = false; } } }); } @Override public void stop() { executor.shutdown(); } private void singleClickAction() { System.out.println("Single-click action executed."); } private void doubleClickAction() { System.out.println("Double-click action executed."); } } ```
Since it is not possible to distinguish between single-click and double-click by default, we use the following approach: On single-click, we wrap the single-click operation in an abortable runnable. This runnable waits a certain amount of time (i.e., `SINGLE_CLICK_DELAY`) before being executed. In the meantime, if a second click, i.e., a double-click, occurs, the single-click operation gets aborted and only the double-click operation is performed. This way, either the single-click *or* the double-click operation is performed, but never both. --- Following is the full code. To use it, only the three `TODO` lines have to be replaced by the wanted handlers. ``` private static final int SINGLE_CLICK_DELAY = 250; private ClickRunner latestClickRunner = null; private class ClickRunner implements Runnable { private final Runnable onSingleClick; private boolean aborted = false; public ClickRunner(Runnable onSingleClick) { this.onSingleClick = onSingleClick; } public void abort() { this.aborted = true; } @Override public void run() { try { Thread.sleep(SINGLE_CLICK_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } if (!aborted) { System.out.println("Execute Single Click"); Platform.runLater(() -> onSingleClick.run()); } } } private void init() { container.setOnMouseClicked(me -> { switch (me.getButton()) { case PRIMARY: if (me.getClickCount() == 1) { System.out.println("Single Click"); latestClickRunner = new ClickRunner(() -> { // TODO: Single-left-click operation }); CompletableFuture.runAsync(latestClickRunner); } if (me.getClickCount() == 2) { System.out.println("Double Click"); if (latestClickRunner != null) { System.out.println("-> Abort Single Click"); latestClickRunner.abort(); } // TODO: Double-left-click operation } break; case SECONDARY: // TODO: Right-click operation break; default: break; } }); } ```
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Adhering to Java SE 8 lambda expressions would look something like this: ``` node.setOnMouseClicked(event -> { if(event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { handleSomeAction(); } }); ``` Once you get used to lambda expressions - they end up being more understandable than the original class instantiation and overriding (x) method. -In my opinion-
An alternative to single click vs. double click that I'm using is single click vs. press-and-hold (for about a quarter to a half second or so), then release the button. The technique can use a threaded abortable timer as in some of the code snippets above to distinguish between the two. Assuming that the actual event handling happens on the button release, this alternative has the advantage that single click works normally (i.e., without any delay), and for press-and-hold you can give the user some visual feedback when the button has been held long enough to be released (so there's never any ambiguity about which action was performed).
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Since it is not possible to distinguish between single-click and double-click by default, we use the following approach: On single-click, we wrap the single-click operation in an abortable runnable. This runnable waits a certain amount of time (i.e., `SINGLE_CLICK_DELAY`) before being executed. In the meantime, if a second click, i.e., a double-click, occurs, the single-click operation gets aborted and only the double-click operation is performed. This way, either the single-click *or* the double-click operation is performed, but never both. --- Following is the full code. To use it, only the three `TODO` lines have to be replaced by the wanted handlers. ``` private static final int SINGLE_CLICK_DELAY = 250; private ClickRunner latestClickRunner = null; private class ClickRunner implements Runnable { private final Runnable onSingleClick; private boolean aborted = false; public ClickRunner(Runnable onSingleClick) { this.onSingleClick = onSingleClick; } public void abort() { this.aborted = true; } @Override public void run() { try { Thread.sleep(SINGLE_CLICK_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } if (!aborted) { System.out.println("Execute Single Click"); Platform.runLater(() -> onSingleClick.run()); } } } private void init() { container.setOnMouseClicked(me -> { switch (me.getButton()) { case PRIMARY: if (me.getClickCount() == 1) { System.out.println("Single Click"); latestClickRunner = new ClickRunner(() -> { // TODO: Single-left-click operation }); CompletableFuture.runAsync(latestClickRunner); } if (me.getClickCount() == 2) { System.out.println("Double Click"); if (latestClickRunner != null) { System.out.println("-> Abort Single Click"); latestClickRunner.abort(); } // TODO: Double-left-click operation } break; case SECONDARY: // TODO: Right-click operation break; default: break; } }); } ```
An alternative to single click vs. double click that I'm using is single click vs. press-and-hold (for about a quarter to a half second or so), then release the button. The technique can use a threaded abortable timer as in some of the code snippets above to distinguish between the two. Assuming that the actual event handling happens on the button release, this alternative has the advantage that single click works normally (i.e., without any delay), and for press-and-hold you can give the user some visual feedback when the button has been held long enough to be released (so there's never any ambiguity about which action was performed).
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Since it is not possible to distinguish between single-click and double-click by default, we use the following approach: On single-click, we wrap the single-click operation in an abortable runnable. This runnable waits a certain amount of time (i.e., `SINGLE_CLICK_DELAY`) before being executed. In the meantime, if a second click, i.e., a double-click, occurs, the single-click operation gets aborted and only the double-click operation is performed. This way, either the single-click *or* the double-click operation is performed, but never both. --- Following is the full code. To use it, only the three `TODO` lines have to be replaced by the wanted handlers. ``` private static final int SINGLE_CLICK_DELAY = 250; private ClickRunner latestClickRunner = null; private class ClickRunner implements Runnable { private final Runnable onSingleClick; private boolean aborted = false; public ClickRunner(Runnable onSingleClick) { this.onSingleClick = onSingleClick; } public void abort() { this.aborted = true; } @Override public void run() { try { Thread.sleep(SINGLE_CLICK_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } if (!aborted) { System.out.println("Execute Single Click"); Platform.runLater(() -> onSingleClick.run()); } } } private void init() { container.setOnMouseClicked(me -> { switch (me.getButton()) { case PRIMARY: if (me.getClickCount() == 1) { System.out.println("Single Click"); latestClickRunner = new ClickRunner(() -> { // TODO: Single-left-click operation }); CompletableFuture.runAsync(latestClickRunner); } if (me.getClickCount() == 2) { System.out.println("Double Click"); if (latestClickRunner != null) { System.out.println("-> Abort Single Click"); latestClickRunner.abort(); } // TODO: Double-left-click operation } break; case SECONDARY: // TODO: Right-click operation break; default: break; } }); } ```
If you are testing how many mouse buttons (==2) are pressed, do not code it in sub-method! The next is working: ``` listView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if( mouseEvent.getButton().equals(MouseButton.SECONDARY)) { System.out.println("isSecondaryButtonDown"); mouseEvent.consume(); // .... } else if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ System.out.println("Double clicked"); // mousePressedInListViewDC(mouseEvent); } else if(mouseEvent.getClickCount() == 1){ System.out.println("1 clicked"); mousePressedInListView1C(mouseEvent); } } } }) ``` ;
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Not sure if someone still follows this OP or refer it, but below is my version of differentiating single click to double click. While most of the answers are quite acceptable, it would be really useful if it can be done in a proper resuable way. One of the challenge I encountered is the need to have the single-double click differentiation on multiple nodes at multiple places. I cannot do the same repetitive cumbersome logic on each and every node. It should be done in a generic way. So I opted to implement a custom EventDispatcher and use this dispatcher on node level or I can apply it directly to Scene to make it applicable for all child nodes. For this I created a new MouseEvent namely 'MOUSE\_DOUBLE\_CLICKED", so tthat I am still sticking with the standard JavaFX practises. Now I can include the double\_clicked event filters/handlers just like other mouse event types. ``` node.addEventFilter(CustomMouseEvent.MOUSE_DOUBLE_CLICKED, e->{..<code to handle double_click>..}); node.addEventHandler(CustomMouseEvent.MOUSE_DOUBLE_CLICKED, e->{..<code to handle double_click>..}); ``` Below is the implementation and complete working demo of this custom event dispatcher. ``` import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.*; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class DoubleClickEventDispatcherDemo extends Application { @Override public void start(Stage stage) throws Exception { Rectangle box1 = new Rectangle(150, 150); box1.setStyle("-fx-fill:red;-fx-stroke-width:2px;-fx-stroke:black;"); addEventHandlers(box1, "Red Box"); Rectangle box2 = new Rectangle(150, 150); box2.setStyle("-fx-fill:yellow;-fx-stroke-width:2px;-fx-stroke:black;"); addEventHandlers(box2, "Yellow Box"); HBox pane = new HBox(box1, box2); pane.setSpacing(10); pane.setAlignment(Pos.CENTER); addEventHandlers(pane, "HBox"); Scene scene = new Scene(new StackPane(pane), 450, 300); stage.setScene(scene); stage.show(); // SETTING CUSTOM EVENT DISPATCHER TO SCENE scene.setEventDispatcher(new DoubleClickEventDispatcher(scene.getEventDispatcher())); } private void addEventHandlers(Node node, String nodeId) { node.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> System.out.println("" + nodeId + " mouse clicked filter")); node.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> System.out.println("" + nodeId + " mouse clicked handler")); node.addEventFilter(CustomMouseEvent.MOUSE_DOUBLE_CLICKED, e -> System.out.println("" + nodeId + " mouse double clicked filter")); node.addEventHandler(CustomMouseEvent.MOUSE_DOUBLE_CLICKED, e -> System.out.println(nodeId + " mouse double clicked handler")); } /** * Custom MouseEvent */ interface CustomMouseEvent { EventType<MouseEvent> MOUSE_DOUBLE_CLICKED = new EventType<>(MouseEvent.ANY, "MOUSE_DBL_CLICKED"); } /** * Custom EventDispatcher to differentiate from single click with double click. */ class DoubleClickEventDispatcher implements EventDispatcher { /** * Default delay to fire a double click event in milliseconds. */ private static final long DEFAULT_DOUBLE_CLICK_DELAY = 215; /** * Default event dispatcher of a node. */ private final EventDispatcher defaultEventDispatcher; /** * Timeline for dispatching mouse clicked event. */ private Timeline clickedTimeline; /** * Constructor. * * @param initial Default event dispatcher of a node */ public DoubleClickEventDispatcher(final EventDispatcher initial) { defaultEventDispatcher = initial; } @Override public Event dispatchEvent(final Event event, final EventDispatchChain tail) { final EventType<? extends Event> type = event.getEventType(); if (type == MouseEvent.MOUSE_CLICKED) { final MouseEvent mouseEvent = (MouseEvent) event; final EventTarget eventTarget = event.getTarget(); if (mouseEvent.getClickCount() > 1) { if (clickedTimeline != null) { clickedTimeline.stop(); clickedTimeline = null; final MouseEvent dblClickedEvent = copy(mouseEvent, CustomMouseEvent.MOUSE_DOUBLE_CLICKED); Event.fireEvent(eventTarget, dblClickedEvent); } return mouseEvent; } if (clickedTimeline == null) { final MouseEvent clickedEvent = copy(mouseEvent, mouseEvent.getEventType()); clickedTimeline = new Timeline(new KeyFrame(Duration.millis(DEFAULT_DOUBLE_CLICK_DELAY), e -> { Event.fireEvent(eventTarget, clickedEvent); clickedTimeline = null; })); clickedTimeline.play(); return mouseEvent; } } return defaultEventDispatcher.dispatchEvent(event, tail); } /** * Creates a copy of the provided mouse event type with the mouse event. * * @param e MouseEvent * @param eventType Event type that need to be created * @return New mouse event instance */ private MouseEvent copy(final MouseEvent e, final EventType<? extends MouseEvent> eventType) { return new MouseEvent(eventType, e.getSceneX(), e.getSceneY(), e.getScreenX(), e.getScreenY(), e.getButton(), e.getClickCount(), e.isShiftDown(), e.isControlDown(), e.isAltDown(), e.isMetaDown(), e.isPrimaryButtonDown(), e.isMiddleButtonDown(), e.isSecondaryButtonDown(), e.isSynthesized(), e.isPopupTrigger(), e.isStillSincePress(), e.getPickResult()); } } } ```
If you are testing how many mouse buttons (==2) are pressed, do not code it in sub-method! The next is working: ``` listView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if( mouseEvent.getButton().equals(MouseButton.SECONDARY)) { System.out.println("isSecondaryButtonDown"); mouseEvent.consume(); // .... } else if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ System.out.println("Double clicked"); // mousePressedInListViewDC(mouseEvent); } else if(mouseEvent.getClickCount() == 1){ System.out.println("1 clicked"); mousePressedInListView1C(mouseEvent); } } } }) ``` ;
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Yes you can detect single, double even multiple clicks: ``` myNode.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ if(mouseEvent.getClickCount() == 2){ System.out.println("Double clicked"); } } } }); ``` `MouseButton.PRIMARY` is used to determine if the left (commonly) mouse button is triggered the event. Read the api of `getClickCount()` to conclude that there maybe multiple click counts other than single or double. However I find it hard to distinguish between single and double click events. Because the first click count of the double click will rise a single event as well.
Adhering to Java SE 8 lambda expressions would look something like this: ``` node.setOnMouseClicked(event -> { if(event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { handleSomeAction(); } }); ``` Once you get used to lambda expressions - they end up being more understandable than the original class instantiation and overriding (x) method. -In my opinion-
10,949,465
I have the below sql, which if i take out the inner join to the table and hard code the values, i get 2 records. But when i use the inner join statement, i just get 1 record. I am aware that with MYSQL, the like clause, is not case sensitive. Here is the sql below. I dont know why it is only returning row. ``` SELECT a.project_code as projectCode, a.project_name as projectName, a.project_creation_date as projectCreationDate, a.project_end_date as projectEndDate, a.project_status as projectStatus from projects a inner join tmp_rec_naren8 b on a.project_name like concat("%",b.expertise_desc,"%") OR a.project_description like concat("%",b.expertise_desc,"%") ; ``` If I change the above to: ``` select * from projects where project_name like '%java%' OR project_description like '%java%'; ``` I get 2 rows and not 1. Table `tmp_rec_naren8` has just one column `expertise_desc` and contains this data: ``` expertise_desc -------------- XML Python DWH Java ``` Table `projects` has many columns :.. But these below are the relevant ones ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 2 naren7 INV Networking 3 naren9 CCV Java, Unix ``` The first query returns 1 row: ``` project_code sr_user_name project_name project_descriiption .. --------------------------------------------------------------- 1 naren5 POS C++,XML,Java ``` The second query returns 2 rows ``` project_code sr_user_name project_name project_descriiption .. ----------------------------------------------------------- 1 naren5 POS C++, XML,Java 3 naren9 CCV Java, Unix ```
2012/06/08
[ "https://Stackoverflow.com/questions/10949465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278124/" ]
Since it is not possible to distinguish between single-click and double-click by default, we use the following approach: On single-click, we wrap the single-click operation in an abortable runnable. This runnable waits a certain amount of time (i.e., `SINGLE_CLICK_DELAY`) before being executed. In the meantime, if a second click, i.e., a double-click, occurs, the single-click operation gets aborted and only the double-click operation is performed. This way, either the single-click *or* the double-click operation is performed, but never both. --- Following is the full code. To use it, only the three `TODO` lines have to be replaced by the wanted handlers. ``` private static final int SINGLE_CLICK_DELAY = 250; private ClickRunner latestClickRunner = null; private class ClickRunner implements Runnable { private final Runnable onSingleClick; private boolean aborted = false; public ClickRunner(Runnable onSingleClick) { this.onSingleClick = onSingleClick; } public void abort() { this.aborted = true; } @Override public void run() { try { Thread.sleep(SINGLE_CLICK_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } if (!aborted) { System.out.println("Execute Single Click"); Platform.runLater(() -> onSingleClick.run()); } } } private void init() { container.setOnMouseClicked(me -> { switch (me.getButton()) { case PRIMARY: if (me.getClickCount() == 1) { System.out.println("Single Click"); latestClickRunner = new ClickRunner(() -> { // TODO: Single-left-click operation }); CompletableFuture.runAsync(latestClickRunner); } if (me.getClickCount() == 2) { System.out.println("Double Click"); if (latestClickRunner != null) { System.out.println("-> Abort Single Click"); latestClickRunner.abort(); } // TODO: Double-left-click operation } break; case SECONDARY: // TODO: Right-click operation break; default: break; } }); } ```
A solution using PauseTransition: ```java PauseTransition singlePressPause = new PauseTransition(Duration.millis(500)); singlePressPause.setOnFinished(e -> { // single press }); node.setOnMousePressed(e -> { if (e.isPrimaryButtonDown() && e.getClickCount() == 1) { singlePressPause.play(); } if (e.isPrimaryButtonDown() && e.getClickCount() == 2) { singlePressPause.stop(); // double press } }); ```
14,202,825
I have Google Map created with version of Google Maps api v3. It's "standard" Google Map, filled with markers and clusters. Every marker and cluster have it's own InfoWindow, showed when end user click on it. What I need is that when map is loaded, to open all of InfoWindows of all markers and clusters showed on map. Right now, they are showed only when I click on them: ``` google.maps.event.addListener(markerGreenCluster, 'clusterclick', function(markerGreenCluster) { var content = ''; var info = new google.maps.MVCObject; info.set('position', markerGreenCluster.center_); var infowindow = new google.maps.InfoWindow(); aIWgreen.push(infowindow); var center = markerGreenCluster.getCenter(); var size = markerGreenCluster.getSize(); var markers = markerGreenCluster.getMarkers(); // more code goes here... }) ``` I noticed that problem is in cluster definition, and method **`markerGreenCluster.getSize();`** It returns number of grupped markers, and it can return it after whole map is loaded, or something like that. Can you help me how can I achieve that all of InfoWindows are open (showed) when map is loaded?
2013/01/07
[ "https://Stackoverflow.com/questions/14202825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198003/" ]
I'm guessing the reason you're doing this is because you're unaware that you can send multidimensional arrays in HTML forms. I suggest an approach such as. ``` <input name="users[1][userid]" /> <input name="users[1][status]" /> <input name="users[1][howlate]" /> <input name="users[1][passfail]" /> <input name="users[2][userid]" /> <input name="users[2][status]" /> <input name="users[2][howlate]" /> <input name="users[2][passfail]" /> ``` Then in php you can access them in the following manner. ``` foreach( $_POST['users'] as $key => $user ) { $userID = $user['userid']; // same for the other fields. } ```
Assign your variables (if you are not using PDO, which you should to avoid SQL injection) for example: ``` $userId = $_POST['userId']; // assuming that is what your field id is from the html form $status = $_POST['status']; ``` etc. Then insert into the database table: ``` insert into attendance (UserID, Status, HowLate, PassFail) values ($userId, '$status' etc. ```
30,641,827
I have ran into very strange behavior of my code, the basic flow of code is `main ()` parses a file and sets global variables accordingly.. such as ``` int frame_size, version; typedef struct//file parsing variables { int frame, int version; } configuration; ***//the function init_parse calls*** static int handler(void* user, const char* section, const char* name, const char* value) { configuration* pconfig = (configuration*)user; #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 if (MATCH("protocol", "version")) { pconfig->version = atoi(value); } else if (MATCH("basic", "frames")) { pconfig->frames= atoi(value); frame_size=pconfig->frames; } else { return 0; /* unknown section/name, error */ } return 1; } main (){ configuration config; if (ini_parse("test.ini", handler, &config) < 0) { printf("Can't load 'test.ini'\n"); getchar(); iret = pthread_create(&hThread,NULL, pcapreader, NULL); if(iret) { fprintf(stderr,"Error - pthread_create() return code: %d\n",iret); exit(EXIT_FAILURE); } } ``` Now, the line followed by `main()`'s parsing line, everything seems set, but as soon as thread is started , the value frame\_size changes to something 6345720:/ I have double checked code for possible replicated variable. thread only uses `frame_size` in for loop to check the limit.
2015/06/04
[ "https://Stackoverflow.com/questions/30641827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4247061/" ]
the only problem was with initialization, once initialized, everything worked like a charm :)
I think it might never initialize the frame\_size variable and never reached MATCH("basic", "frames") statement too.
61,737
Regarding the following verbs/phrases, which ones mean "this is my strong believe" and which ones mean "this is my understanding of the situations"? * I feel * I can see * I am convinced
2015/07/13
[ "https://ell.stackexchange.com/questions/61737", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/628/" ]
Generally speaking, "I feel and "I can see" are roughly equivalent to "this is my understanding of the situation", whereas "I am convinced" is equivalent to "this is my strong belie**f**". This is because "I feel", "I can see", and "this is my understanding of the situation" express less force and certainty than "I am convinced" or "this is my strong belief".
The correct phrase is actually *This is my belie**f***. From your examples, the first one would be the best fit because a belief can be considered a feeling.
61,737
Regarding the following verbs/phrases, which ones mean "this is my strong believe" and which ones mean "this is my understanding of the situations"? * I feel * I can see * I am convinced
2015/07/13
[ "https://ell.stackexchange.com/questions/61737", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/628/" ]
There are many ways in English to express shades of certainty. Phrases that indicate a low level of certainty include "I feel", "I think", "I assume", and "I suppose". Phrases that indicate a high level of certainty include "I know", "I am certain that", and "I am convinced that". All of these have fuzzy boundaries so you can't necessarily arrange them in strict order. Like you can't say that "I feel" indicates, say, 20% certainty while I think is 25% or any such. "I can see" would, I think, be somewhere in the middle.
The correct phrase is actually *This is my belie**f***. From your examples, the first one would be the best fit because a belief can be considered a feeling.
61,737
Regarding the following verbs/phrases, which ones mean "this is my strong believe" and which ones mean "this is my understanding of the situations"? * I feel * I can see * I am convinced
2015/07/13
[ "https://ell.stackexchange.com/questions/61737", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/628/" ]
Generally speaking, "I feel and "I can see" are roughly equivalent to "this is my understanding of the situation", whereas "I am convinced" is equivalent to "this is my strong belie**f**". This is because "I feel", "I can see", and "this is my understanding of the situation" express less force and certainty than "I am convinced" or "this is my strong belief".
There are many ways in English to express shades of certainty. Phrases that indicate a low level of certainty include "I feel", "I think", "I assume", and "I suppose". Phrases that indicate a high level of certainty include "I know", "I am certain that", and "I am convinced that". All of these have fuzzy boundaries so you can't necessarily arrange them in strict order. Like you can't say that "I feel" indicates, say, 20% certainty while I think is 25% or any such. "I can see" would, I think, be somewhere in the middle.
750,090
Managing computers for UNIFI routers "have to be in the same level 2 network" as the managed routers. Is a computer behind the same internet modem router, but in a different IP-network, in the same level 2 network? EG: Modem-Router, LAN-IP 192.168.1.0, serves 2 "sub"-routers, one with LAN-IP 10.10.10.0, the other with LAN-IP 10.200.200.0. Is a computer in the 10.200.200.0 network in the same level 2 network as one in the 10.10.10.0 network??? I know, it is in a different level 3 (IP) network, but is it in the same level 2 network?? Chris EDIT: This is what it is about: I have a modem-router, to which I have attached several WiFi-APs, PLUS another LAN-Router for a local office network (cable based). The LAN-router is some sort of encapsulation of the office LAN from the WiFi-NW. Now I like to replace the WiFi-APs by UNIFI WiFi-APs to build up a managed wireless NW. These APs need a managing computer. As in the office-LAN there is already a server running 7x24 hours (just for local purposes, not accessible from the internet), it would be the easiest to use this one as controller instead of installing another 7x24 server just as WiFi manager. According to the UNIFI documentation, the controller has to be within the same layer 2 network.
2014/05/05
[ "https://superuser.com/questions/750090", "https://superuser.com", "https://superuser.com/users/320653/" ]
That '+' *is* wrong. You *concatenate strings* with `&` and *add numbers* with `+`. Pretend TopRow = 1, and NewLastRow = 5: You're trying to ADD "D1" to ":D5", and since you can't perform math additions on strings, you get the type mismatch error when you try. Beyond that - output value problems without syntax errors are logic problems, to help with those, we'll need other specific information. So those are probably best handled as new questions (with appropriate information given) so that we can deal with the problems you are encountering one at a time, after you've done your share of investigating them. :)
``` 1. I noticed a mixture of &'s and +'s. 1a. I fixed them. 2. I think you need to **cast your integers** to strings (TopRow, NewLastRow, others). 2a. I cast them for you. ``` > > I cut your code exactly. > > I added some comments that you will > see in green once you cut this and paste it. > > I added casting > to your integers in Range fields. > > If your code is correct it > will now work. If it still Err's then you have to look at some logic. > Use some debugging to message yourself e.g. MsgBox "trying out code > var:" & myvar > > > > > > > ``` Function Material_Rollup() MyfirstValue = 0 MyLastValue = 0 Cnt = 0 TopRow = 0 BottomRow = 0 CntDelRows = 0 NewLastRow = 0 Quantity = 0 loopCnt = 0 Dim MyBom As String Dim MyRollup As String Dim NextRow As String MyBom = ActiveSheet.Name If Val(Range("A2")) > 0 Or Val(Range("I1")) > 0 Then MsgBox MyBom & " is not a BOM72 Work sheet or Material Rollup Sheet, Rollup Canceled." Call GotoSheet GoTo Cancel End If ReturnRows (Selection.Address) MyfirstValue = My_First_Row MyLastValue = My_Last_Row If MyfirstValue = MyLastValue Then Call BOM72ERR(3, "") GoTo Cancel End If RetrySheet: If Pick_Sheet = "Pick_Sheet_Cancel" Then Sheets(MyBom).Select GoTo Cancel Else MyRollup = Pick_Sheet End If 'See if Rollup sheet name exist or is new For Each sh In ActiveWorkbook.Sheets If UCase(sh.Name) = UCase(MyRollup) Then DoesSheetExist = 1 Exit For Else DoesSheetExist = 0 End If Next 'If Sheet exist make sure its a Material Rollup Sheet If DoesSheetExist = 1 Then If Worksheets(MyRollup).Range("E1").Value <= 0 Then MsgBox MyRollup & " is not a Material Rollup Sheet." GoTo RetrySheet End If End If 'If sheet doesn't exist, build and format If DoesSheetExist = 0 Then Sheets.Add ActiveSheet.Name = MyRollup ActiveWindow.DisplayGridlines = False With Application .Calculation = xlManual .MaxChange = 0.001 End With ActiveWorkbook.PrecisionAsDisplayed = False Worksheets("Data").Range("A4:W6").Copy (Worksheets(MyRollup).Range("A1")) Range("a4").Select ActiveWindow.FreezePanes = True Range("A5").Select TopRow = 4 'Does Range("E1") return an address or integer? Dim myMessage = "Range("E1") return an address or integer? TopRow = " Range("E1") = TopRow MsgBox myMessage & TopRow End If Worksheets(MyRollup).Select ' 'TopRow = Address + 1? Does Range("E1") return an integer? TopRow = (Range("E1") + 1) MsgBox myMessage & TopRow 'Is Val(MyFirstValue), Val necessary, or help, or hinder? BottomRow = ((Val(MyLastValue) - Val(MyfirstValue)) + 1) + Range("E1").Value Cnt = TopRow 'Casting Worksheets(MyBom).Range("B" + CStr(MyfirstValue) & ":H" & CStr(MyLastValue)).Copy (Worksheets(MyRollup).Range("B" & CStr(TopRow))) 'Delete Rows that are not Material Items (Look for Text in Mfg Column) For Each C In Worksheets(MyRollup).Range("C" & CStr(TopRow) & ":C" & CStr(BottomRow)) If C.Value = "" Then 'Added Cast to summation Rows(CStr((Cnt - CntDelRows))).Select Selection.Delete Shift:=xlUp CntDelRows = CntDelRows + 1 End If Cnt = Cnt + 1 Next C 'Delete Rows with the Unit Price column colored Gray (Don't Rollup) NewLastRow = (Cnt - (CntDelRows + 1)) Cnt = TopRow CntDelRows = 0 'Casting For Each C2 In Worksheets(MyRollup).Range("G" & CStr(TopRow) & ":G" & CStr(NewLastRow)) If C2.Interior.ColorIndex = 40 Then Rows((Cnt - CntDelRows)).Select Selection.Delete Shift:=xlUp CntDelRows = CntDelRows + 1 End If Cnt = Cnt + 1 Next C2 NewLastRow = (Cnt - (CntDelRows + 1)) 'Sort Rollup by Part Number 'Casting Range("A" & CStr(TopRow) & ":S" & CStr(NewLastRow)).Select Selection.Sort Key1:=Range("D" & TopRow), Order1:=xlAscending, Header:=xlGuess, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom Range("B" & TopRow).Select Cells.Select With Selection.Font .Name = "Arial" .FontStyle = "Regular" .Size = 10 End With Range("A1").Select Cnt = TopRow cnt2 = (Cnt + 1) CntDelRows = 0 loopCnt = 0 'Casting 'Rollup, Like Part Numbers, Combine Quantities and Delete Rows For Each c1 In Worksheets(MyRollup).Range("D" & CStr(TopRow) + ":D" & CStr(NewLastRow)) NextRow = Range("D" & cnt2) 'Casting If UCase(c1.Value) = UCase(NextRow) Then Quantity = Range("E" & CStr(Cnt)) & Range("E" & CStr(cnt2)) Range("E" & CStr(cnt2)) = Quantity '?Cast here? CStr(Cnt)? Rows(Cnt).Select Selection.Delete Shift:=xlUp CntDelRows = CntDelRows + 1 Cnt = Cnt - 1 cnt2 = cnt2 - 1 Quantity = 0 End If Cnt = (Cnt + 1) cnt2 = (cnt2 + 1) Next c1 NewLastRow = NewLastRow - CntDelRows 'Casting 'Sort Rollup by Manufacturer then Part Number Range("A" & CStr(TopRow) & ":S" & CStr(NewLastRow)).Select Selection.Sort Key1:=Range("C" & CStr(TopRow)), Order1:=xlAscending, Key2:=Range _ ("D" & CStr(TopRow)), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, _ MatchCase:=False, Orientation:=xlTopToBottom 'Casting Range("B" + CStr(TopRow)).Select Worksheets("Data").Range("G8:W8").Copy Worksheets(MyRollup).Range("G" & CStr(TopRow) & ":G" & CStr(NewLastRow)) Sheets(MyRollup).Select Columns("K:S").Select Selection.ColumnWidth = 6 Columns("A").Select Selection.ColumnWidth = 3 Columns("B").Select Selection.ColumnWidth = 20 Columns("C:D").Select Selection.ColumnWidth = 12 Columns("E:F").Select Selection.ColumnWidth = 6 Columns("H").Select Selection.ColumnWidth = 3 Range("K5").Select With Application .Calculation = xlAutomatic .MaxChange = 0.001 End With ActiveWorkbook.PrecisionAsDisplayed = False 'Casting Range("E1") = NewLastRow '? CStr(NewLastRow) ? Might need here! Range("A" & TopRow) = "WorkSheet: " & MyBom & " Rows: " & CStr(MyfirstValue) & " to " & CStr(MyLastValue) Range("A" & CStr(TopRow)).Font.ColorIndex = 22 If TopRow > 5 Then Range("B1") = "Multi-Rollup Sheet" Else Range("B1") = "Single-Rollup Sheet" End If Range("B" + CStr(TopRow)).Select 'Don't forget to value quantity column Cancel: End Function ```
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids. ``` DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10) ```
Maybe find the ID of the 10th element and then delete all rows which are older?
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
You can use this:- ``` DELETE FROM `people` WHERE id NOT IN ( SELECT id FROM ( SELECT id FROM `people` ORDER BY id DESC LIMIT 10 ) ); ``` Also your query is logically incorrect and you are fetching the records in descending order. i.e. `Latest to older` and you are deleting the most recent records. Use `ASC` instead.
Maybe find the ID of the 10th element and then delete all rows which are older?
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
Your logic is all over the place, [you should `ORDER BY ASC`, not `DESC`] and your query will take ages if there are [for example] 10,000 entries because you'll have an `IN` clause with 9,990 entries to compare all 10,000 to. Select the 10 most recent, and delete where NOT in. ``` DELETE FROM people WHERE id NOT IN( SELECT id FROM people ORDER BY id DESC LIMIT 10 ) ```
Maybe find the ID of the 10th element and then delete all rows which are older?
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
You can use this:- ``` DELETE FROM `people` WHERE id NOT IN ( SELECT id FROM ( SELECT id FROM `people` ORDER BY id DESC LIMIT 10 ) ); ``` Also your query is logically incorrect and you are fetching the records in descending order. i.e. `Latest to older` and you are deleting the most recent records. Use `ASC` instead.
Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids. ``` DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10) ```
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids. ``` DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10) ```
Your logic is all over the place, [you should `ORDER BY ASC`, not `DESC`] and your query will take ages if there are [for example] 10,000 entries because you'll have an `IN` clause with 9,990 entries to compare all 10,000 to. Select the 10 most recent, and delete where NOT in. ``` DELETE FROM people WHERE id NOT IN( SELECT id FROM people ORDER BY id DESC LIMIT 10 ) ```
17,326,740
I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried `DELETE FROM people ORDER BY id DESC LIMIT $excess`, but it just deleted the top 10 entries. ``` $query = "SELECT * FROM people"; $result = mysqli_query($conn, $query); $count = mysqli_num_rows($result); if ($count > 10) { $excess = $count - 10; $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')"; mysqli_query($conn, $query); } ```
2013/06/26
[ "https://Stackoverflow.com/questions/17326740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229571/" ]
You can use this:- ``` DELETE FROM `people` WHERE id NOT IN ( SELECT id FROM ( SELECT id FROM `people` ORDER BY id DESC LIMIT 10 ) ); ``` Also your query is logically incorrect and you are fetching the records in descending order. i.e. `Latest to older` and you are deleting the most recent records. Use `ASC` instead.
Your logic is all over the place, [you should `ORDER BY ASC`, not `DESC`] and your query will take ages if there are [for example] 10,000 entries because you'll have an `IN` clause with 9,990 entries to compare all 10,000 to. Select the 10 most recent, and delete where NOT in. ``` DELETE FROM people WHERE id NOT IN( SELECT id FROM people ORDER BY id DESC LIMIT 10 ) ```
39,228,784
I need to update one table with values from another table (msdb.dbo.sysjobhistory). Since I need to get the max values of the run\_time and run\_date, I kept getting 'aggregate function not allowed in set statement' error. As a workaround, I tried the following but something isn't right because ALL the values in every row are the same, indicating either an error in the join or something I can't figure out.This is what I have (which is not correct): ``` UPDATE inventory.dbo.books SET auth_time = t1.at, auth_date = t1.ad FROM (SELECT MAX(run_time) AS at, MAX(run_date) AS ad FROM msdb.dbo.sysjobhistory h INNER JOIN inventory.dbo.books t ON h.job_id = t.jobid) t1 ``` ALSO, I need to be able to convert the run\_time into decimal(10,2) format (as the auth\_time field is that) and run\_date into datetime (as auth\_time is datetime format).
2016/08/30
[ "https://Stackoverflow.com/questions/39228784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526303/" ]
Using an example with `find` you will get similar results. ``` find /c "this|that|andtheotherthing" C:\temp\EventCombMT.txt ``` ``` find : FIND: Parameter format not correct At line:1 char:1 + find /c "this|that|andtheotherthing" C:\temp\EventCombMT.txt + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (FIND: Parameter format not correct:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError ``` Pretty sure this is because the quotes are consumed by the PowerShell interpreter and that leave your `mocha` command with an unquoted string. Doubling up the quotes is another was to prevent this. ``` find /c '"this|that|andtheotherthing"' C:\temp\EventCombMT.txt ``` It seems this is not the case with mocha? In comments it was determined that we need to reverse the quote set from that seen in the `find` examples. There are better ways to call external commands as you have seen in [your linked post](http://edgylogic.com/blog/powershell-and-external-commands-done-right/). Like using the call operator and a hashtable. You would still have to address the quotes though. You could escape a set of double quotes as well to get a similar effect. ``` find /c "`"this|that|andtheotherthing`"" C:\temp\EventCombMT.txt ``` For this to be correct though it does not really match the error you are getting. While I am correct about a solution I might be wrong about my interpretation of the issue. PowerShell should not care about the pipe character regardless of how it is quoted. That is what the quotes are for.
Thanks to [PowerShell and external commands done right](http://edgylogic.com/blog/powershell-and-external-commands-done-right/). You can quote the pipe character to stop powershell treating it as a pipe. In this case: ``` mocha -g 'network"|"database"|"skip' ``` Works perfectly. As @matt has since mentioned, you can also run the (much neater): ``` mocha -i -g '"database|network|skip"' ```
67,460,934
I am new at C and want to find out how memory allocation and pointers work. But I am struggled with some strange behaviour of my code. See the code and output below. I am using mingw, gcc version 4.9.2 (tdm-1), not sure is it a bug or I missing something? Is it correct way of sending structures to/from a function? And is it ok to simply assign staticly allocated array to a pointer? No warnings from gcc btw. ``` #include <stdlib.h> #include <stdio.h> typedef struct S { int *a; } s_t; s_t create_s () { s_t s; s.a = malloc ( sizeof ( int ) * 5 ); for ( int i = 0; i < 5; ++i ) { s.a [ i ] = i << 1; } return s; } void fill_s ( s_t s ) { for ( int i = 0; i < 5; ++i ) { s.a [ i ] = i; } } void kill_s ( s_t s ) { free ( s.a ); } void fill1_s_from_const ( s_t s ) { int array [ 5 ] = { 11, 21, 31, 41, 51 }; s.a = array; } s_t fill2_s_from_const () { int array [ 5 ] = { 12, 22, 32, 42, 52 }; s_t s; s.a = array; return s; } void copy_s_from_const ( s_t s ) { int array [ 5 ] = { 111, 222, 333, 444, 555 }; for ( int i = 0; i < 5; ++i ) { s.a [ i ] = array [ i ]; } } int main () { s_t s = create_s (); printf ( "\ncreate_s\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } fill_s ( s ); printf ( "\nfill_s\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } copy_s_from_const ( s ); printf ( "\ncopy_s_from_const\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } kill_s ( s ); // not working at all (array filled with garbage) fill1_s_from_const ( s ); printf ( "\nfill1_s_from_const\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } // works partly (array filled correctly but some fields are still full of garbage) s = fill2_s_from_const (); printf ( "\nfill2_s_from_const\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } // same as fill1_s_from_const or fill2_s_from_const (imo) but works perfectly fine int b [ 5 ] = { 11, 22, 33, 44, 55 }; s.a = b; printf ( "\ninline\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } } ``` [Output](https://i.stack.imgur.com/VR10n.png)
2021/05/09
[ "https://Stackoverflow.com/questions/67460934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10562922/" ]
``` void fill1_s_from_const ( s_t s ) { int array [ 5 ] = { 11, 21, 31, 41, 51 }; s.a = array; } ``` Structs are passed by value, so this function doesn't do anything. After you call it, the caller's `s.a` is still what it was before, in your case a pointer to memory you just freed. ``` s_t fill2_s_from_const () { int array [ 5 ] = { 12, 22, 32, 42, 52 }; s_t s; s.a = array; return s; } ``` Assigning an array to a pointer is by reference, so calling this function results in giving the caller a dangling pointer in `s.a`. ``` // same as fill1_s_from_const or fill2_s_from_const (imo) but works perfectly fine int b [ 5 ] = { 11, 22, 33, 44, 55 }; s.a = b; printf ( "\ninline\n" ); for ( int i = 0; i < 5; ++i ) { printf ( "%d\n", s.a [ i ] ); } ``` This works because unlike `fill2_s_from_const`, the pointer doesn't become dangling before you use it here.
Ok, I got it. fill\_s works because I am sending s by value so s.a in fill\_s has the same value (pointing to the same memory block) as s.a in main, while both s'es are separate structure instances. fill1\_s\_from\_const does not work the same way because I am assigning value to the local s.a created on function call, it is not the same as s.a in main (values are). Function will work as fill2\_s\_from\_const if s will be passed as a pointer. fill2\_s\_from\_const simply sets to s.a the pointer to the local memory block. When program returns back to the main, the data stored in there is already destroyed (in my case -- partially, wich confuses me). Sorry for the dumb question (cannot delete it).
57,501,951
I am new to Unity, and many of these principals I am just blanking on. I build a dialogue system and its working great, but I want to make a confirmation box. I have managed to get the confirmation box to pull up, but I cant seem to figure out how to wait for one of the Yes / No buttons are pushed before the code is returned to the Dialogue manager with the proper bool. Right now the code pushes on behind the dialogue box. Which is expected. I tried an enumerator but I must have been doing it wrong because it did not matter. I just cleaned up the code to try to start from scratch. ``` public bool AskForTakingMoney(){ takingMoneyBox.SetActive(true); goldText.text = "Current Gold: " + GameManager.instance.currentGold.ToString() + "G"; questionText.text = "Pay the " + DialogManager.instance.goldAmount + "G?"; //Wait here until yes or no button pushed return saysYes; } public void SaysYes(){ saysYes = true; selectedAnswer = true; takingMoneyBox.SetActive(false); } public void SaysNo(){ saysYes = false; selectedAnswer = true; takingMoneyBox.SetActive(false); } ``` I really just need the return function to not go back until the yes or no button is pushed. I am at a complete loss.
2019/08/14
[ "https://Stackoverflow.com/questions/57501951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8569903/" ]
If you want to show a popup, then the popup should be responsible for what happens next. So your `AskForTakingMoney` should never return a value. Instead you need to assign the `onclick` events for the Yes and No button. Your code should simply be: ``` public void AskForTakingMoney(){ takingMoneyBox.SetActive(true); goldText.text = "Current Gold: " + GameManager.instance.currentGold.ToString() + "G"; questionText.text = "Pay the " + DialogManager.instance.goldAmount + "G?"; } public void SaysYes(){ takingMoneyBox.SetActive(false); // Your withdraw money code here. } public void SaysNo(){ takingMoneyBox.SetActive(false); } ``` Then from within the Editor, click on your Yes Button. You should see an onclick field like the one in the picture. Click on the plus sign, then drag in your MonoBehaviour object which is holding the code with above functions. After dragging it in, You should be able to select `SaysYes` from the dropdown that appears under 'YourScriptName' -> 'SaysYes()' Do the same for your No Button and you should be all set. [![OnClick](https://i.stack.imgur.com/RYkeJ.png)](https://i.stack.imgur.com/RYkeJ.png)
Make Two Buttons, Set them to active at the end of AskForTakingMoney(), Make those buttons lead to SaysYes(); and SaysNo(); Edit: Comment if you need clarification. I may not be understanding you clear enough. Do you even have buttons set up?
57,501,951
I am new to Unity, and many of these principals I am just blanking on. I build a dialogue system and its working great, but I want to make a confirmation box. I have managed to get the confirmation box to pull up, but I cant seem to figure out how to wait for one of the Yes / No buttons are pushed before the code is returned to the Dialogue manager with the proper bool. Right now the code pushes on behind the dialogue box. Which is expected. I tried an enumerator but I must have been doing it wrong because it did not matter. I just cleaned up the code to try to start from scratch. ``` public bool AskForTakingMoney(){ takingMoneyBox.SetActive(true); goldText.text = "Current Gold: " + GameManager.instance.currentGold.ToString() + "G"; questionText.text = "Pay the " + DialogManager.instance.goldAmount + "G?"; //Wait here until yes or no button pushed return saysYes; } public void SaysYes(){ saysYes = true; selectedAnswer = true; takingMoneyBox.SetActive(false); } public void SaysNo(){ saysYes = false; selectedAnswer = true; takingMoneyBox.SetActive(false); } ``` I really just need the return function to not go back until the yes or no button is pushed. I am at a complete loss.
2019/08/14
[ "https://Stackoverflow.com/questions/57501951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8569903/" ]
If you want to show a popup, then the popup should be responsible for what happens next. So your `AskForTakingMoney` should never return a value. Instead you need to assign the `onclick` events for the Yes and No button. Your code should simply be: ``` public void AskForTakingMoney(){ takingMoneyBox.SetActive(true); goldText.text = "Current Gold: " + GameManager.instance.currentGold.ToString() + "G"; questionText.text = "Pay the " + DialogManager.instance.goldAmount + "G?"; } public void SaysYes(){ takingMoneyBox.SetActive(false); // Your withdraw money code here. } public void SaysNo(){ takingMoneyBox.SetActive(false); } ``` Then from within the Editor, click on your Yes Button. You should see an onclick field like the one in the picture. Click on the plus sign, then drag in your MonoBehaviour object which is holding the code with above functions. After dragging it in, You should be able to select `SaysYes` from the dropdown that appears under 'YourScriptName' -> 'SaysYes()' Do the same for your No Button and you should be all set. [![OnClick](https://i.stack.imgur.com/RYkeJ.png)](https://i.stack.imgur.com/RYkeJ.png)
You would either need the function to not care about returning what they clicked, and each frame check (in the update method, or in a coroutine) if the button has been pressed by checking your selectedAnswer variable. Or you could run some code in a separate thread, and use WaitHandle's, to cause the thread to pause until the button has been pressed. Example using your code: ``` using System.Threading; using UnityEngine; public class Manager : MonoBehaviour { EventWaitHandle handle = new EventWaitHandle(false,EventResetMode.AutoReset); Thread _thread; public void StartThread() { _thread = new Thread(BackgroundThreadFunction); _thread.Start(); } public void BackgroundThreadFunction() { if (AskForTakingMoney()) { //Yes } else { //No } } public bool AskForTakingMoney() { takingMoneyBox.SetActive(true); goldText.text = "Current Gold: " + GameManager.instance.currentGold.ToString() + "G"; questionText.text = "Pay the " + DialogManager.instance.goldAmount + "G?"; //Wait here until yes or no button pushed handle.WaitOne(); return saysYes; } public void SaysYes() { saysYes = true; selectedAnswer = true; takingMoneyBox.SetActive(false); handle.Set(); } public void SaysNo() { saysYes = false; selectedAnswer = true; takingMoneyBox.SetActive(false); handle.Set(); } } ```
34,112,551
I am trying to send multiple strings using the socket.send() and socket.recv() function. I am building a client/server, and "in a perfect world" would like my server to call the socket.send() function a maximum of 3 times (for a certain server command) while having my client call the socket.recv() call 3 times. This doesn't seem to work the client gets hung up waiting for another response. server: ``` clientsocket.send(dir) clientsocket.send(dirS) clientsocket.send(fileS) ``` client ``` response1 = s.recv(1024) if response1: print "\nRecieved response: \n" , response1 response2 = s.recv(1024) if response2: print "\nRecieved response: \n" , response2 response3 = s.recv(1024) if response3: print "\nRecieved response: \n" , response3 ``` I was going through the tedious task of joining all my strings together then reparsing them in the client, and was wondering if there was a more efficient way of doing it? edit: My output of response1 gives me unusual results. The first time I print response1, it prints all 3 of the responses in 1 string (all mashed together). The second time I call it, it gives me the first string by itself. The following calls to recv are now glitched/bugged and display the 2nd string, then the third string. It then starts to display the other commands but as if it was behind and in a queue. Very unusual, but I will likely stick to joining the strings together in the server then parsing them in the client
2015/12/06
[ "https://Stackoverflow.com/questions/34112551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5140127/" ]
You wouldn't send bytes/strings over a socket like that in a real-world app. You would create a messaging protocol on-top of the socket, then you would put your bytes/strings in messages and send messages over the socket. You probably wouldn't create the messaging protocol from scratch either. You'd use a library like [nanomsg](https://github.com/tonysimpson/nanomsg-python) or [zeromq](http://zeromq.org/bindings:python). **server** ``` from nanomsg import Socket, PAIR sock = Socket(PAIR) sock.bind('inproc://bob') sock.send(dir) sock.send(dirS) sock.send(fileS) ``` **client** ``` from nanomsg import Socket, PAIR sock = Socket(PAIR) sock.bind('inproc://bob') response1 = sock.recv() response2 = sock.recv() response3 = sock.recv() ``` In nanomsg, recv() will return exactly what was sent by send() so there is a one-to-one mapping between send() and recv(). This is not the case when using lower-level Python sockets where you may need to call recv() multiple times to get everything that was sent with send().
TCP is a streaming protocol and there are no message boundaries. Whether a blob of data was sent with one or a hundred `send` calls is unknown to the receiver. You certainly can't assume that 3 `sends` can be matched with 3 `recv`s. So, you are left with the tedious job of reassembling fragments at the receiver. One option is to layer a messaging protocol on top of the pure TCP stream. This is what [zeromq](http://zeromq.org/) does, and it may be an option for reducing the tedium.
34,112,551
I am trying to send multiple strings using the socket.send() and socket.recv() function. I am building a client/server, and "in a perfect world" would like my server to call the socket.send() function a maximum of 3 times (for a certain server command) while having my client call the socket.recv() call 3 times. This doesn't seem to work the client gets hung up waiting for another response. server: ``` clientsocket.send(dir) clientsocket.send(dirS) clientsocket.send(fileS) ``` client ``` response1 = s.recv(1024) if response1: print "\nRecieved response: \n" , response1 response2 = s.recv(1024) if response2: print "\nRecieved response: \n" , response2 response3 = s.recv(1024) if response3: print "\nRecieved response: \n" , response3 ``` I was going through the tedious task of joining all my strings together then reparsing them in the client, and was wondering if there was a more efficient way of doing it? edit: My output of response1 gives me unusual results. The first time I print response1, it prints all 3 of the responses in 1 string (all mashed together). The second time I call it, it gives me the first string by itself. The following calls to recv are now glitched/bugged and display the 2nd string, then the third string. It then starts to display the other commands but as if it was behind and in a queue. Very unusual, but I will likely stick to joining the strings together in the server then parsing them in the client
2015/12/06
[ "https://Stackoverflow.com/questions/34112551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5140127/" ]
You wouldn't send bytes/strings over a socket like that in a real-world app. You would create a messaging protocol on-top of the socket, then you would put your bytes/strings in messages and send messages over the socket. You probably wouldn't create the messaging protocol from scratch either. You'd use a library like [nanomsg](https://github.com/tonysimpson/nanomsg-python) or [zeromq](http://zeromq.org/bindings:python). **server** ``` from nanomsg import Socket, PAIR sock = Socket(PAIR) sock.bind('inproc://bob') sock.send(dir) sock.send(dirS) sock.send(fileS) ``` **client** ``` from nanomsg import Socket, PAIR sock = Socket(PAIR) sock.bind('inproc://bob') response1 = sock.recv() response2 = sock.recv() response3 = sock.recv() ``` In nanomsg, recv() will return exactly what was sent by send() so there is a one-to-one mapping between send() and recv(). This is not the case when using lower-level Python sockets where you may need to call recv() multiple times to get everything that was sent with send().
The answer to this has been covered [elsewhere](https://stackoverflow.com/a/14762550/336892). There are two solutions to your problem. **Solution 1**: Mark the end of your strings. `send(escape(dir) + MARKER)` Your client then keeps calling `recv()` until it gets the end-of-message marker. If `recv()` returns multiple strings, you can use the marker to know where they start and end. You need to escape the marker if your strings contain it. Remember to escape on the client too. **Solution 2**: Send the length of your strings before you send the actual string. Your client then keeps calling recv() until its read all the bytes. If recv() returns multiple strings. You know where they start and end since you know how long they are. When sending the length of your string, make you you use a fixed number of bytes so you can distinguish the string lenght from the string in the byte stream. You will find [struct module](https://docs.python.org/2/library/struct.html) useful.
12,692,736
I am creating a view and I was asked to do a 'replace' and a 'cast', so as an example: ``` SELECT CAST(qtyshipped AS INT) AS 'QTYShipped', REPLACE(itemval,'.','') FROM Database ``` Within the view, should not actually change the information in the database but just in the query correct? (It works perfectly in my sandbox server but i just want to confirm)
2012/10/02
[ "https://Stackoverflow.com/questions/12692736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700703/" ]
Not a dumb question at all. And the answer is yes, it only changes the result of the query, the underlying data will remain the same.
That is already a good query. But I need to tell some points with you. * REPLACE function is case-sensitive. Although I've seen in your code that you are only replacing period. * Why is your column `qtyshipped` is not in numeric type? You should have change that into numeric. So you won't need casting which may *lower* the performance. It will not affect your database since your are only executing `SELECT` not `UPDATE`.
28,496,690
I'm having a Wordpress headache. I'm building a Wordpress frontend that hooks up to a CRM I use to pull details on stock, which I then display in Wordpress. It's all working ok except for 1 thing - pagination. I do Wordpress pagination all the time passing the paged var and using various plugins, but my queries are hand coded PHP PDO requests that don't utilise Wordpress' functions. Does anyone know how to force pagination within Wordpress, even if the results are provided by an external resource? If it helps, my query is as follows (in functions.php): ``` $dbh = new PDO("mysql:host=$hostname;dbname=cl15-l3ase2015", $username, $password); $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0,$limit"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->execute(); $total = $stmt->rowCount(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $data['total_results'] = $total; return $data; ``` ...and the template is controlled by the following: ``` <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 mask-left mask-right"> <div class="body-copy-alt"> <?php $posts_per_page = 2; $post_count = $total; $vehicle_group = get_latest_vehicles(10000); $total = $vehicle_group['total_results']; ?> <div class="col-xs-12 col-sm-7 col-md-8 col-lg-8 no-padding-left"> <h4 class="top"><strong><span id="total-holder"><?php echo $total;?></span> vehicles found</strong>, drive away in five days</h4> </div> <div class="col-xs-12 col-sm-5 col-md-4 col-lg-4 no-padding-right mask-left"> <select name="refine" id="refine"> <option value="null" disabled>Select Lowest Deposit</option> <option value="100">100</option> </select> </div> <div class="clearfix"></div> <?php foreach($vehicle_group as $current_vehicle) { $current_id = $current_vehicle['id']; $vehicle_manufacturer = $current_vehicle['carMake']; $vehicle_model = $current_vehicle['carModel']; $vehicle_registration = $current_vehicle['carReg']; $vehicle_fuel = get_specific('FUEL', $current_vehicle['fuel']); $vehicle_transmission = get_specific('TRANSMISSION', $current_vehicle['transmission']); $vehicle_mileage = $current_vehicle['mileage']; $vehicle_mpg = $current_vehicle['economy']; $vehicle_year = $current_vehicle['year']; $finance_data = get_finance_data($current_id); $vehicle_deposit_min = $finance_data['minDeposit']; $vehicle_weekly_payments = $finance_data['weeklyPayments']; $gallery_data = get_gallery_images($current_id); if(isset($current_id)) { ?> <!-- Vehicle result sample --> <div class="search-result"> <img src="<?php bloginfo('template_directory');?>/assets/img/new-stock-ribbon.png" class="ribbon" /> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-6 no-padding-left no-padding-right"> <form id="vehicle-<?php echo $current_id;?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <a href="#" onclick="$('#vehicle-<?php echo $current_id; ?>').submit();"> <img src="http://79.170.40.161/lease2buy.co.uk/uploads/<?php echo $current_id;?>/<?php echo $gallery_data[0]['photo']; ?>" class="vehicle-thumb" /> </a> </form> </div> <div class="col-xs-12 col-sm-8 col-md-8 col-lg-6"> <h4><?php echo $vehicle_manufacturer; ?></h4> <i><?php echo $vehicle_model; ?></i> <div class="clearfix"></div> <table class="table-responsive" summary="Vehicle specifications"> <tbody> <tr> <td class="legend">Reg No</td> <td><?php echo strtoupper($vehicle_registration); ?></td> <td class="spacer"></td> <td class="legend">Year</td> <td><?php echo $vehicle_year; ?></td> </tr> <tr> <td class="legend">Mileage</td> <td><?php echo $vehicle_mileage; ?></td> <td class="spacer"></td> <td class="legend">Fuel Type</td> <td><?php echo $vehicle_fuel; ?></td> </tr> <tr> <td class="legend">Transmission</td> <td><?php echo $vehicle_transmission; ?></td> <td class="spacer"></td> <td class="legend">MPG</td> <td><?php echo $vehicle_mpg; ?></td> </tr> </tbody> </table> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-left"> <form name="vehicle_interest" method="post" action="<?php bloginfo('url');?>/vehicle/"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-lightblue" value="View Details" /> </form> </div> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-right"> <form name="vehicle-<?php echo $current_id; ?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-green" value="More Info" /> </form> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> <!-- /.search-result --> <div class="clearfix"></div> <div class="result-bottom"> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 gallery-link"> <a href="#"><img src="<?php bloginfo('template_directory');?>/assets/img/icon-camera.png" /> <?php echo $gallery_data['total_results']; ?></a> </div> <div class="hidden-xs col-sm-8 col-md-8 col-lg-8"> <h5 class="text-white"><strong>Min Deposit</strong> &pound;<?php echo $vehicle_deposit_min; ?> | <strong>From</strong> &pound;<?php echo $vehicle_weekly_payments; ?> per week</h5> </div> </div> <!-- END Search result sample --> <?php } } ?> <?php global $wp_query; $wp_query->max_num_pages = ceil( $post_count / $posts_per_page ); // pagination functions next_posts_link( 'Older Entries' ); previous_posts_link( 'Newer Entries' ); ?> .... ```
2015/02/13
[ "https://Stackoverflow.com/questions/28496690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4320125/" ]
All that the WordPress next\_posts\_link and previous\_posts\_link do are create links in the correct format to get the next page and previous page. Since you are not using posts or pages, these links will not be the right format. You can accomplish the same using your custom CRM if you introduce an additional parameter for DB starting position. The details will depend a bit on exactly how your application works, but the basics are: You modify your code to introduce some way of knowing where to start in the database. For example: ``` $dbh = new PDO("mysql:host=$hostname;dbname=cl15-l3ase2015", $username, $password); $start = isset($_GET['start']) ? $_GET['start'] : 0; $stmt = $dbh->prepare("SELECT * FROM cars LIMIT $start,$limit"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->execute(); $total = $stmt->rowCount(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $data['total_results'] = $total; return $data; ``` You can create your own functions that accomplish the same thing. For example, if $start is the starting position of the current page: ``` function my_next_link($start, $limit) { $new_start = $start + $limit; if ($new_start <= number of records in the CRM) { echo "<a href=\"http://example.com/mypage?start=$start\">Next</a>"; } } function my_previous_link($start, $limit) { if ($start > 0) { $new_start = max(0, $start - $limit); echo "<a href=\"http://example.com/mypage?start=$start\">Previous</a>"; } ```
I don't exactly understand what's not working, but you are preparing the statement in the wrong way. instead of ``` $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0,$limit"); ``` it should be ``` $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0, ?"); ``` and then you can limit to 1 ``` $stmt->bindParam(1, $id, PDO::PARAM_INT); ``` EDIT - if you want to do pagination the query must keep count of the page. So let's start with the query ``` $stmt = $dbh->prepare('SELECT * FROM cars LIMIT :lower, :upper '); $per_page = 5; $page = 1; if ( isset( $_GET['page'] ) ) { $page = $_GET['page']; } $upper = $per_page * $page; $lower = $upper - $per_page; $stmt->bindParam(':lower', $lower); $stmt->bindParam(':upper ', $upper ); $stmt->execute(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); return $data; ``` And then you must create Next/Prev links using a parameter which is 'page'
28,496,690
I'm having a Wordpress headache. I'm building a Wordpress frontend that hooks up to a CRM I use to pull details on stock, which I then display in Wordpress. It's all working ok except for 1 thing - pagination. I do Wordpress pagination all the time passing the paged var and using various plugins, but my queries are hand coded PHP PDO requests that don't utilise Wordpress' functions. Does anyone know how to force pagination within Wordpress, even if the results are provided by an external resource? If it helps, my query is as follows (in functions.php): ``` $dbh = new PDO("mysql:host=$hostname;dbname=cl15-l3ase2015", $username, $password); $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0,$limit"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->execute(); $total = $stmt->rowCount(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $data['total_results'] = $total; return $data; ``` ...and the template is controlled by the following: ``` <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 mask-left mask-right"> <div class="body-copy-alt"> <?php $posts_per_page = 2; $post_count = $total; $vehicle_group = get_latest_vehicles(10000); $total = $vehicle_group['total_results']; ?> <div class="col-xs-12 col-sm-7 col-md-8 col-lg-8 no-padding-left"> <h4 class="top"><strong><span id="total-holder"><?php echo $total;?></span> vehicles found</strong>, drive away in five days</h4> </div> <div class="col-xs-12 col-sm-5 col-md-4 col-lg-4 no-padding-right mask-left"> <select name="refine" id="refine"> <option value="null" disabled>Select Lowest Deposit</option> <option value="100">100</option> </select> </div> <div class="clearfix"></div> <?php foreach($vehicle_group as $current_vehicle) { $current_id = $current_vehicle['id']; $vehicle_manufacturer = $current_vehicle['carMake']; $vehicle_model = $current_vehicle['carModel']; $vehicle_registration = $current_vehicle['carReg']; $vehicle_fuel = get_specific('FUEL', $current_vehicle['fuel']); $vehicle_transmission = get_specific('TRANSMISSION', $current_vehicle['transmission']); $vehicle_mileage = $current_vehicle['mileage']; $vehicle_mpg = $current_vehicle['economy']; $vehicle_year = $current_vehicle['year']; $finance_data = get_finance_data($current_id); $vehicle_deposit_min = $finance_data['minDeposit']; $vehicle_weekly_payments = $finance_data['weeklyPayments']; $gallery_data = get_gallery_images($current_id); if(isset($current_id)) { ?> <!-- Vehicle result sample --> <div class="search-result"> <img src="<?php bloginfo('template_directory');?>/assets/img/new-stock-ribbon.png" class="ribbon" /> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-6 no-padding-left no-padding-right"> <form id="vehicle-<?php echo $current_id;?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <a href="#" onclick="$('#vehicle-<?php echo $current_id; ?>').submit();"> <img src="http://79.170.40.161/lease2buy.co.uk/uploads/<?php echo $current_id;?>/<?php echo $gallery_data[0]['photo']; ?>" class="vehicle-thumb" /> </a> </form> </div> <div class="col-xs-12 col-sm-8 col-md-8 col-lg-6"> <h4><?php echo $vehicle_manufacturer; ?></h4> <i><?php echo $vehicle_model; ?></i> <div class="clearfix"></div> <table class="table-responsive" summary="Vehicle specifications"> <tbody> <tr> <td class="legend">Reg No</td> <td><?php echo strtoupper($vehicle_registration); ?></td> <td class="spacer"></td> <td class="legend">Year</td> <td><?php echo $vehicle_year; ?></td> </tr> <tr> <td class="legend">Mileage</td> <td><?php echo $vehicle_mileage; ?></td> <td class="spacer"></td> <td class="legend">Fuel Type</td> <td><?php echo $vehicle_fuel; ?></td> </tr> <tr> <td class="legend">Transmission</td> <td><?php echo $vehicle_transmission; ?></td> <td class="spacer"></td> <td class="legend">MPG</td> <td><?php echo $vehicle_mpg; ?></td> </tr> </tbody> </table> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-left"> <form name="vehicle_interest" method="post" action="<?php bloginfo('url');?>/vehicle/"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-lightblue" value="View Details" /> </form> </div> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-right"> <form name="vehicle-<?php echo $current_id; ?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-green" value="More Info" /> </form> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> <!-- /.search-result --> <div class="clearfix"></div> <div class="result-bottom"> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 gallery-link"> <a href="#"><img src="<?php bloginfo('template_directory');?>/assets/img/icon-camera.png" /> <?php echo $gallery_data['total_results']; ?></a> </div> <div class="hidden-xs col-sm-8 col-md-8 col-lg-8"> <h5 class="text-white"><strong>Min Deposit</strong> &pound;<?php echo $vehicle_deposit_min; ?> | <strong>From</strong> &pound;<?php echo $vehicle_weekly_payments; ?> per week</h5> </div> </div> <!-- END Search result sample --> <?php } } ?> <?php global $wp_query; $wp_query->max_num_pages = ceil( $post_count / $posts_per_page ); // pagination functions next_posts_link( 'Older Entries' ); previous_posts_link( 'Newer Entries' ); ?> .... ```
2015/02/13
[ "https://Stackoverflow.com/questions/28496690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4320125/" ]
I don't exactly understand what's not working, but you are preparing the statement in the wrong way. instead of ``` $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0,$limit"); ``` it should be ``` $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0, ?"); ``` and then you can limit to 1 ``` $stmt->bindParam(1, $id, PDO::PARAM_INT); ``` EDIT - if you want to do pagination the query must keep count of the page. So let's start with the query ``` $stmt = $dbh->prepare('SELECT * FROM cars LIMIT :lower, :upper '); $per_page = 5; $page = 1; if ( isset( $_GET['page'] ) ) { $page = $_GET['page']; } $upper = $per_page * $page; $lower = $upper - $per_page; $stmt->bindParam(':lower', $lower); $stmt->bindParam(':upper ', $upper ); $stmt->execute(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); return $data; ``` And then you must create Next/Prev links using a parameter which is 'page'
At first, think, how pagination works whatever worpdress or any other cms. The page list belongs the number i.e. 2,3,4...7,8. When someone click on any page link it provides the `$_GET` value. Then we use this value in query limit. There is another way that is retrieve all the data from the database, split into page. However, you should try the first way. There are many pagination classes and tutorials, pick one of them and check how that works and implement as you require. I think this link will help you [link](http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928).
28,496,690
I'm having a Wordpress headache. I'm building a Wordpress frontend that hooks up to a CRM I use to pull details on stock, which I then display in Wordpress. It's all working ok except for 1 thing - pagination. I do Wordpress pagination all the time passing the paged var and using various plugins, but my queries are hand coded PHP PDO requests that don't utilise Wordpress' functions. Does anyone know how to force pagination within Wordpress, even if the results are provided by an external resource? If it helps, my query is as follows (in functions.php): ``` $dbh = new PDO("mysql:host=$hostname;dbname=cl15-l3ase2015", $username, $password); $stmt = $dbh->prepare("SELECT * FROM cars LIMIT 0,$limit"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->execute(); $total = $stmt->rowCount(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $data['total_results'] = $total; return $data; ``` ...and the template is controlled by the following: ``` <div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 mask-left mask-right"> <div class="body-copy-alt"> <?php $posts_per_page = 2; $post_count = $total; $vehicle_group = get_latest_vehicles(10000); $total = $vehicle_group['total_results']; ?> <div class="col-xs-12 col-sm-7 col-md-8 col-lg-8 no-padding-left"> <h4 class="top"><strong><span id="total-holder"><?php echo $total;?></span> vehicles found</strong>, drive away in five days</h4> </div> <div class="col-xs-12 col-sm-5 col-md-4 col-lg-4 no-padding-right mask-left"> <select name="refine" id="refine"> <option value="null" disabled>Select Lowest Deposit</option> <option value="100">100</option> </select> </div> <div class="clearfix"></div> <?php foreach($vehicle_group as $current_vehicle) { $current_id = $current_vehicle['id']; $vehicle_manufacturer = $current_vehicle['carMake']; $vehicle_model = $current_vehicle['carModel']; $vehicle_registration = $current_vehicle['carReg']; $vehicle_fuel = get_specific('FUEL', $current_vehicle['fuel']); $vehicle_transmission = get_specific('TRANSMISSION', $current_vehicle['transmission']); $vehicle_mileage = $current_vehicle['mileage']; $vehicle_mpg = $current_vehicle['economy']; $vehicle_year = $current_vehicle['year']; $finance_data = get_finance_data($current_id); $vehicle_deposit_min = $finance_data['minDeposit']; $vehicle_weekly_payments = $finance_data['weeklyPayments']; $gallery_data = get_gallery_images($current_id); if(isset($current_id)) { ?> <!-- Vehicle result sample --> <div class="search-result"> <img src="<?php bloginfo('template_directory');?>/assets/img/new-stock-ribbon.png" class="ribbon" /> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-6 no-padding-left no-padding-right"> <form id="vehicle-<?php echo $current_id;?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <a href="#" onclick="$('#vehicle-<?php echo $current_id; ?>').submit();"> <img src="http://79.170.40.161/lease2buy.co.uk/uploads/<?php echo $current_id;?>/<?php echo $gallery_data[0]['photo']; ?>" class="vehicle-thumb" /> </a> </form> </div> <div class="col-xs-12 col-sm-8 col-md-8 col-lg-6"> <h4><?php echo $vehicle_manufacturer; ?></h4> <i><?php echo $vehicle_model; ?></i> <div class="clearfix"></div> <table class="table-responsive" summary="Vehicle specifications"> <tbody> <tr> <td class="legend">Reg No</td> <td><?php echo strtoupper($vehicle_registration); ?></td> <td class="spacer"></td> <td class="legend">Year</td> <td><?php echo $vehicle_year; ?></td> </tr> <tr> <td class="legend">Mileage</td> <td><?php echo $vehicle_mileage; ?></td> <td class="spacer"></td> <td class="legend">Fuel Type</td> <td><?php echo $vehicle_fuel; ?></td> </tr> <tr> <td class="legend">Transmission</td> <td><?php echo $vehicle_transmission; ?></td> <td class="spacer"></td> <td class="legend">MPG</td> <td><?php echo $vehicle_mpg; ?></td> </tr> </tbody> </table> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-left"> <form name="vehicle_interest" method="post" action="<?php bloginfo('url');?>/vehicle/"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-lightblue" value="View Details" /> </form> </div> <div class="col-xs-6 col-sm-6 col-md-5 col-lg-5 no-padding-right"> <form name="vehicle-<?php echo $current_id; ?>" method="post" action="<?php bloginfo('url');?>/vehicle"> <input type="hidden" name="vehicle" value="<?php echo $current_id; ?>" /> <input type="submit" class="button bg-green" value="More Info" /> </form> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> <!-- /.search-result --> <div class="clearfix"></div> <div class="result-bottom"> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 gallery-link"> <a href="#"><img src="<?php bloginfo('template_directory');?>/assets/img/icon-camera.png" /> <?php echo $gallery_data['total_results']; ?></a> </div> <div class="hidden-xs col-sm-8 col-md-8 col-lg-8"> <h5 class="text-white"><strong>Min Deposit</strong> &pound;<?php echo $vehicle_deposit_min; ?> | <strong>From</strong> &pound;<?php echo $vehicle_weekly_payments; ?> per week</h5> </div> </div> <!-- END Search result sample --> <?php } } ?> <?php global $wp_query; $wp_query->max_num_pages = ceil( $post_count / $posts_per_page ); // pagination functions next_posts_link( 'Older Entries' ); previous_posts_link( 'Newer Entries' ); ?> .... ```
2015/02/13
[ "https://Stackoverflow.com/questions/28496690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4320125/" ]
All that the WordPress next\_posts\_link and previous\_posts\_link do are create links in the correct format to get the next page and previous page. Since you are not using posts or pages, these links will not be the right format. You can accomplish the same using your custom CRM if you introduce an additional parameter for DB starting position. The details will depend a bit on exactly how your application works, but the basics are: You modify your code to introduce some way of knowing where to start in the database. For example: ``` $dbh = new PDO("mysql:host=$hostname;dbname=cl15-l3ase2015", $username, $password); $start = isset($_GET['start']) ? $_GET['start'] : 0; $stmt = $dbh->prepare("SELECT * FROM cars LIMIT $start,$limit"); $stmt->bindParam(1, $id, PDO::PARAM_INT); $stmt->execute(); $total = $stmt->rowCount(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $data['total_results'] = $total; return $data; ``` You can create your own functions that accomplish the same thing. For example, if $start is the starting position of the current page: ``` function my_next_link($start, $limit) { $new_start = $start + $limit; if ($new_start <= number of records in the CRM) { echo "<a href=\"http://example.com/mypage?start=$start\">Next</a>"; } } function my_previous_link($start, $limit) { if ($start > 0) { $new_start = max(0, $start - $limit); echo "<a href=\"http://example.com/mypage?start=$start\">Previous</a>"; } ```
At first, think, how pagination works whatever worpdress or any other cms. The page list belongs the number i.e. 2,3,4...7,8. When someone click on any page link it provides the `$_GET` value. Then we use this value in query limit. There is another way that is retrieve all the data from the database, split into page. However, you should try the first way. There are many pagination classes and tutorials, pick one of them and check how that works and implement as you require. I think this link will help you [link](http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928).
96,903
I'm new in CentOS and I'm trying to create a little script in Python, something like: ``` $ python -m SimpleHTTPServer ``` If I try to access port 8000 in my web browser, I don't get access, however if I turn off the firewall with: ``` $ system-config-firewall-tui ``` I'm able to access the service. I just need to access port 3343 and 8880 but I don't want to disable the firewall.
2013/10/21
[ "https://unix.stackexchange.com/questions/96903", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/47372/" ]
Try something like this: ``` $ iptables -A INPUT -p tcp --dport 3343 -j ACCEPT $ iptables -A INPUT -p tcp --dport 8880 -j ACCEPT ```
Just for anybody who needs, after make the change in iptables i reload the services with: ``` /etc/init.d/iptables restart ``` And ``` /etc/init.d/networking restart ```
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
There are a number of environment variables that control how history works in Bash. Relevant excerpt from bash manpage follows: ```none HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the begin- ning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks speci- fied by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTSIZE The number of commands to remember in the command history (see HISTORY below). The default value is 500. ``` To answer your questions directly: No, there isn't a guarantee, since history can be disabled, some commands may not be stored (e.g. starting with a white space) and there may be a limit imposed on the history size. As for the history size limitation: if you unset `HISTSIZE` and `HISTFILESIZE`: ```none unset HISTSIZE unset HISTFILESIZE ``` you'll prevent the shell from truncating your history file. However, if you have an instance of a shell running that has these two variables set, it will truncate your history while exiting, so the solution is quite brittle. In case you absolutely must maintain long term shell history, you should not rely on shell and copy the files regularly (e.g., using a [cron](https://en.wikipedia.org/wiki/Cron) job) to a safe location. History truncation always removes the oldest entries first as stated in the [man page](https://en.wikipedia.org/wiki/Man_page) excerpt above.
`man bash` is your friend: The `HISTFILESIZE` variable: > > The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the > oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an > interactive shell exits. > > >
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
There are a number of environment variables that control how history works in Bash. Relevant excerpt from bash manpage follows: ```none HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the begin- ning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks speci- fied by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTSIZE The number of commands to remember in the command history (see HISTORY below). The default value is 500. ``` To answer your questions directly: No, there isn't a guarantee, since history can be disabled, some commands may not be stored (e.g. starting with a white space) and there may be a limit imposed on the history size. As for the history size limitation: if you unset `HISTSIZE` and `HISTFILESIZE`: ```none unset HISTSIZE unset HISTFILESIZE ``` you'll prevent the shell from truncating your history file. However, if you have an instance of a shell running that has these two variables set, it will truncate your history while exiting, so the solution is quite brittle. In case you absolutely must maintain long term shell history, you should not rely on shell and copy the files regularly (e.g., using a [cron](https://en.wikipedia.org/wiki/Cron) job) to a safe location. History truncation always removes the oldest entries first as stated in the [man page](https://en.wikipedia.org/wiki/Man_page) excerpt above.
Also note: By default, if you work with multiple login sessions (I usually have two or three [PuTTY](https://en.wikipedia.org/wiki/PuTTY) windows logged into the same server), they do *not* see each other's history. Also, it appears that when I exit all the shells, the last one to exit is the one which is saved back the file (i.e., is visible when I start work the next day). So I assume Bash is keeping the history in memory and then flushes to the file on exit. At least that’s my guess based on what I see.
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
There are a number of environment variables that control how history works in Bash. Relevant excerpt from bash manpage follows: ```none HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the begin- ning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks speci- fied by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTSIZE The number of commands to remember in the command history (see HISTORY below). The default value is 500. ``` To answer your questions directly: No, there isn't a guarantee, since history can be disabled, some commands may not be stored (e.g. starting with a white space) and there may be a limit imposed on the history size. As for the history size limitation: if you unset `HISTSIZE` and `HISTFILESIZE`: ```none unset HISTSIZE unset HISTFILESIZE ``` you'll prevent the shell from truncating your history file. However, if you have an instance of a shell running that has these two variables set, it will truncate your history while exiting, so the solution is quite brittle. In case you absolutely must maintain long term shell history, you should not rely on shell and copy the files regularly (e.g., using a [cron](https://en.wikipedia.org/wiki/Cron) job) to a safe location. History truncation always removes the oldest entries first as stated in the [man page](https://en.wikipedia.org/wiki/Man_page) excerpt above.
Adam suggested that unsetting size limits doesn't cut it, but you can avoid other instances of the shell to change HISTSIZE, HISTFILESIZE, etc. by setting the "readonly" flag on them in file */etc/profile*. ``` unset HISTSIZE unset HISTFILESIZE readonly HISTFILE HISTFILESIZE HISTSIZE HISTCONTROL HISTIGNORE HISTTIMEFORMAT ```
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
There are a number of environment variables that control how history works in Bash. Relevant excerpt from bash manpage follows: ```none HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the begin- ning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks speci- fied by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTSIZE The number of commands to remember in the command history (see HISTORY below). The default value is 500. ``` To answer your questions directly: No, there isn't a guarantee, since history can be disabled, some commands may not be stored (e.g. starting with a white space) and there may be a limit imposed on the history size. As for the history size limitation: if you unset `HISTSIZE` and `HISTFILESIZE`: ```none unset HISTSIZE unset HISTFILESIZE ``` you'll prevent the shell from truncating your history file. However, if you have an instance of a shell running that has these two variables set, it will truncate your history while exiting, so the solution is quite brittle. In case you absolutely must maintain long term shell history, you should not rely on shell and copy the files regularly (e.g., using a [cron](https://en.wikipedia.org/wiki/Cron) job) to a safe location. History truncation always removes the oldest entries first as stated in the [man page](https://en.wikipedia.org/wiki/Man_page) excerpt above.
If you want all commands from all sessions appended to the history instantly (so that you can use commands from one session immediately in another), you can put the following lines into your *[.bashrc](https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example)* file: ``` unset HISTSIZE unset HISTFILESIZE HISTCONTROL=erasedups # Append to the history file. Don't overwrite it shopt -s histappend # Multi-line commands should be stored as a single command shopt -s cmdhist # Sharing of history between multiple terminals # The history file has to be read and saved after each command execution PROMPT_COMMAND="history -n; history -w; history -c; history -r; $PROMPT_COMMAND" ``` More information about these commands can be found in *[Preserve Bash history in multiple terminal windows](https://unix.stackexchange.com/questions/1288/preserve-bash-history-in-multiple-terminal-windows#3055135 "Preserve bash history in multiple terminal windows")*
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
`man bash` is your friend: The `HISTFILESIZE` variable: > > The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the > oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an > interactive shell exits. > > >
Also note: By default, if you work with multiple login sessions (I usually have two or three [PuTTY](https://en.wikipedia.org/wiki/PuTTY) windows logged into the same server), they do *not* see each other's history. Also, it appears that when I exit all the shells, the last one to exit is the one which is saved back the file (i.e., is visible when I start work the next day). So I assume Bash is keeping the history in memory and then flushes to the file on exit. At least that’s my guess based on what I see.
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
`man bash` is your friend: The `HISTFILESIZE` variable: > > The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the > oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an > interactive shell exits. > > >
Adam suggested that unsetting size limits doesn't cut it, but you can avoid other instances of the shell to change HISTSIZE, HISTFILESIZE, etc. by setting the "readonly" flag on them in file */etc/profile*. ``` unset HISTSIZE unset HISTFILESIZE readonly HISTFILE HISTFILESIZE HISTSIZE HISTCONTROL HISTIGNORE HISTTIMEFORMAT ```
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
If you want all commands from all sessions appended to the history instantly (so that you can use commands from one session immediately in another), you can put the following lines into your *[.bashrc](https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example)* file: ``` unset HISTSIZE unset HISTFILESIZE HISTCONTROL=erasedups # Append to the history file. Don't overwrite it shopt -s histappend # Multi-line commands should be stored as a single command shopt -s cmdhist # Sharing of history between multiple terminals # The history file has to be read and saved after each command execution PROMPT_COMMAND="history -n; history -w; history -c; history -r; $PROMPT_COMMAND" ``` More information about these commands can be found in *[Preserve Bash history in multiple terminal windows](https://unix.stackexchange.com/questions/1288/preserve-bash-history-in-multiple-terminal-windows#3055135 "Preserve bash history in multiple terminal windows")*
Also note: By default, if you work with multiple login sessions (I usually have two or three [PuTTY](https://en.wikipedia.org/wiki/PuTTY) windows logged into the same server), they do *not* see each other's history. Also, it appears that when I exit all the shells, the last one to exit is the one which is saved back the file (i.e., is visible when I start work the next day). So I assume Bash is keeping the history in memory and then flushes to the file on exit. At least that’s my guess based on what I see.
8,168,680
I am using struts framework in my project. Have Used one check box, one button and one text box on my JSP. Below is the code for all of them. ``` <html:text name="FormBean" styleId = "codeERText" property="codeER" onFocus="change_classe_byId(this,'on');" onBlur="change_classe_byId(this,'off');" styleClass="off" maxlength="5"/> <input type="button" styleId = "deduireButton" name = "deduireButton" id = "deduireButton" value="<bean:message key="Property.deduire"/>" onClick="javascript:validate('DEDUIRE');"> <html:checkbox styleId="idBrodcastCheckbox" property="sentToAll" name="FormBean" onChange="javascript:broadcastValidate();" /> ``` Requirement is when check box is checked, it should disable the button and textbox and vice-verse. Below is the function which is being called at onChange Event of Checkbox.. While running this on Application, it just gives first alert ("Inside Broadcast Validate").. No other alerts are raised.. Nor the button or text box is being disabled. I believe, it is not entering in any of the If/Else pairs. App Server used is Weblogic 8.1. ``` function broadcastValidate(){ alert("Inside Broadcast Validate"); if(document.forms[0].idBrodcastCheckbox.checked == true) { alert("checked true"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("First If over"); if(this.document.FormBean.getElementById("idBrodcastCheckbox").checked == true) { alert("checked true 2"); this.document.getElementById("codeERText").disabled = true; this.document.getElementById("deduireButton").disabled = true; } else { alert("checked false 2"); this.document.getElementById("codeERText").disabled = false; this.document.getElementById("deduireButton").disabled = false; } alert("Second If over "); if(document.forms[0].sentToAll.value == true) { alert("checked true - Sent to All"); document.forms[0].codeERText.disabled = true; document.forms[0].deduireButton.disabled = true; } else { alert("checked false - Sent to All"); document.forms[0].codeERText.disabled = false; document.forms[0].deduireButton.disabled = false; } alert("Third If over - Exiting Broadcast Validate"); } ``` Please suggest some solution to this.
2011/11/17
[ "https://Stackoverflow.com/questions/8168680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722536/" ]
If you want all commands from all sessions appended to the history instantly (so that you can use commands from one session immediately in another), you can put the following lines into your *[.bashrc](https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example)* file: ``` unset HISTSIZE unset HISTFILESIZE HISTCONTROL=erasedups # Append to the history file. Don't overwrite it shopt -s histappend # Multi-line commands should be stored as a single command shopt -s cmdhist # Sharing of history between multiple terminals # The history file has to be read and saved after each command execution PROMPT_COMMAND="history -n; history -w; history -c; history -r; $PROMPT_COMMAND" ``` More information about these commands can be found in *[Preserve Bash history in multiple terminal windows](https://unix.stackexchange.com/questions/1288/preserve-bash-history-in-multiple-terminal-windows#3055135 "Preserve bash history in multiple terminal windows")*
Adam suggested that unsetting size limits doesn't cut it, but you can avoid other instances of the shell to change HISTSIZE, HISTFILESIZE, etc. by setting the "readonly" flag on them in file */etc/profile*. ``` unset HISTSIZE unset HISTFILESIZE readonly HISTFILE HISTFILESIZE HISTSIZE HISTCONTROL HISTIGNORE HISTTIMEFORMAT ```
939,829
I'd like to know if it's possible to change disk partitioning standard from MBR to GPT for a disk with OS on which I do that, without loosing the OS. I have windows 7 and want to install side by side Fedora 22. So, I need a GPT disk. But I have only my HD which contains windows 7 and is already MBR. What should I do?
2015/07/13
[ "https://superuser.com/questions/939829", "https://superuser.com", "https://superuser.com/users/468685/" ]
A conversion without losing your partitions is possible, but your system won't be bootable after you make such a change. My own [GPT fdisk (`gdisk` and related programs)](http://www.rodsbooks.com/gdisk/) can do this, and I believe some commercial third-party Windows tools can do so, too. Windows ties its boot mode tightly to the boot disk's partition table type; Windows can boot MBR disks *only* in BIOS mode and GPT disks *only* in EFI mode. Thus, making this conversion will require installing an EFI-mode boot loader for Windows. Also, your computer must have EFI firmware, which was absent on most computers from before mid-2011. There are sites describing how to do the conversion and install a suitable boot loader, but I don't happen to have any URLs handy at the moment. It's almost certain to be easier to install Fedora on your MBR disk. If you have fewer than four primary partitions right now, you can do this pretty easily by resizing your existing partition(s) to make room and install Fedora entirely in logical partitions. (*DO NOT* create partition(s) for Fedora using the Windows tools, though; that's likely to create new problems.) Fedora copes fine with being installed entirely to logical partitions. If you've already got four primary partitions, you must delete one or convert it from primary to logical form. The latter can be accomplished with my [FixParts program](http://www.rodsbooks.com/fixparts/) or with some third-party Windows tools. *Do not* convert any bootable partition from primary to logical form; do such conversions only on data partitions.
I think you mean convert MBR to GPT. **1. Convert MBR to GPT using Diskpart command** This method you have to backup all your data and delete all partitions and volumes. Then use the DISKPART command Open command prompt and type in DISKPART and press Enter Then type in list disk (Note down the number of disk you want to convert to GPT) Then type in select disk number of disk Finally type in convert gpt. **2.Convert MBR disk to GPT disk with Windows Disk Management** Right click "My Computer" and choose "Manage" -> "Storage" -> "Disk Management". Delete all volumes on the MBR hard disk which you want to convert to GPT disk. Right click on the hard disk 1 and choose "Convert to GPT disk". After you convert MBR disk to GPT disk, you can create partitions on the GPT disk if you like. **3.Third-party disk manage tool** [EaseUS Partition Master](http://www.partition-tool.com/resource/GPT-disk-partition-manager/convert-mbr-disk-to-gpt-disk.htm) and [Paragon Partition Manager](http://www.paragon-software.com/home/) Strongly recommended.
939,829
I'd like to know if it's possible to change disk partitioning standard from MBR to GPT for a disk with OS on which I do that, without loosing the OS. I have windows 7 and want to install side by side Fedora 22. So, I need a GPT disk. But I have only my HD which contains windows 7 and is already MBR. What should I do?
2015/07/13
[ "https://superuser.com/questions/939829", "https://superuser.com", "https://superuser.com/users/468685/" ]
You can conveniently use `MBR2GPT.EXE` by Microsoft: > > MBR2GPT.EXE converts a disk from the Master Boot Record (MBR) to the > GUID Partition Table (GPT) partition style without modifying or > deleting data on the disk. The tool is designed to be run from a > Windows Preinstallation Environment (Windows PE) command prompt, but > can also be run from the full Windows 10 operating system (OS) by > using the /allowFullOS option. > > > Find more information over [at Microsoft](https://docs.microsoft.com/en-us/windows/deployment/mbr-to-gpt).
I think you mean convert MBR to GPT. **1. Convert MBR to GPT using Diskpart command** This method you have to backup all your data and delete all partitions and volumes. Then use the DISKPART command Open command prompt and type in DISKPART and press Enter Then type in list disk (Note down the number of disk you want to convert to GPT) Then type in select disk number of disk Finally type in convert gpt. **2.Convert MBR disk to GPT disk with Windows Disk Management** Right click "My Computer" and choose "Manage" -> "Storage" -> "Disk Management". Delete all volumes on the MBR hard disk which you want to convert to GPT disk. Right click on the hard disk 1 and choose "Convert to GPT disk". After you convert MBR disk to GPT disk, you can create partitions on the GPT disk if you like. **3.Third-party disk manage tool** [EaseUS Partition Master](http://www.partition-tool.com/resource/GPT-disk-partition-manager/convert-mbr-disk-to-gpt-disk.htm) and [Paragon Partition Manager](http://www.paragon-software.com/home/) Strongly recommended.
37,954,432
**This is my connection string** ``` { "Data": { "PhotoGalleryConnection": { "ConnectionString": "Server=WINDOWS-B7MJR5T\\SQLEXPRESS;User Id=sa;password=allah;Database=PhotoGallery;Trusted_Connection=True;MultipleActiveResultSets=true" } } } ``` **And I am facing this exception** > > An exception of type 'System.Data.SqlClient.SqlException' occurred in > Microsoft.EntityFrameworkCore.dll but was not handled in user code > Additional information: Cannot open database "PhotoGallery" requested > by the login. The login failed. > > >
2016/06/21
[ "https://Stackoverflow.com/questions/37954432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176700/" ]
It should work after You delete Trusted\_Connection=True; from connection string. > > If you specify either Trusted\_Connection=True; or Integrated > Security=SSPI; or Integrated Security=true; in your connection string > THEN (and only then) you have Windows Authentication happening. Any > user id= setting in the connection string will be ignored. Found in here: [When using Trusted\_Connection=true and SQL Server authentication, will this effect performance?](https://stackoverflow.com/questions/1642483/when-using-trusted-connection-true-and-sql-server-authentication-will-this-effe) > > >
[![Please search service in window menu](https://i.stack.imgur.com/sSmro.png)](https://i.stack.imgur.com/sSmro.png) Please search services in the window menu, it will show you the local services then go to SQL server services and refresh all, then go to the SQL server management studio and by using SQL authentication please provide username and password, you will be able to use the SQL server. for appsetting.json update, trusted\_connection is used for window authentication not for SQL server authentication by using username and password
21,017,925
My Manifest activity code ``` <activity android:name="FileReceiver" > <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> ``` My Activity code : ``` Intent i = getIntent(); String action = i.getAction(); if (action.equals(Intent.ACTION_SEND)) { Uri imageUri = (Uri) i.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { Log.i("1234567", "URI : " + imageUri); Log.i("123456", "path :" + imageUri.getPath()); File source = null; source = new File(imageUri.getPath()); String fileNme = "/" + source.getName(); File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path); Log.i("123456", "destination path :" + destination); try { FileUtils.copyFile(source, destination); } catch (IOException e) { Log.i("123456", "IO Exception"); e.printStackTrace(); } } ``` im getting exception ``` 01-09 16:10:09.756: W/System.err(30225): java.io.FileNotFoundException: Source 'content:/media/external/images/media/127' does not exist ``` how do i get the path of the image when i receive an image from DCIM folder ?
2014/01/09
[ "https://Stackoverflow.com/questions/21017925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1140321/" ]
``` /** * helper to retrieve the path of an image URI */ public String getPath(Uri uri) { // just some safety built in if( uri == null ) { // TODO perform some logging or show user feedback return null; } // try to retrieve the image from the media store first // this will only work for images selected from gallery String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if( cursor != null ){ int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } // this is our fallback here return uri.getPath(); } ``` source: [Get/pick an image from Android's built-in Gallery app programmatically](https://stackoverflow.com/questions/2169649/get-pick-an-image-from-androids-built-in-gallery-app-programmatically)
I've got the same problem. Solved it using the following code: ``` public static String getPathFromURI(Context context, Uri contentUri) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, contentUri)) { return getPathForV19AndUp(context, contentUri); } else { return getPathForPreV19(context, contentUri); } } private static String getPathForPreV19(Context context, Uri contentUri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null); if (cursor != null && cursor.moveToFirst()) { try { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); return cursor.getString(columnIndex); } finally { cursor.close(); } } return null; } @TargetApi(Build.VERSION_CODES.KITKAT) private static String getPathForV19AndUp(Context context, Uri contentUri) { String documentId = DocumentsContract.getDocumentId(contentUri); String id = documentId.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = context.getContentResolver(). query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null); if (cursor != null) { try { int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { return cursor.getString(columnIndex); } } finally { cursor.close(); } } return null; } ```
6,101,273
I require a very simple mechanism in my application, where my project is built as a shared library '.so' or '.dll', but what I want is: ``` ExampleAppOne.so ``` I get: ``` libExampleAppOne.so -> libExampleAppOne.so.1.0.0 libExampleAppOne.so.1 -> libExampleAppOne.so.1.0.0 libExampleAppOne.so.1.0 -> libExampleAppOne.so.1.0.0 ``` I don't even want the 'lib' prefix. In the .pro file, all I can do is change the INSTALLS variable (that is because my third requirement IS that the library be built in a specific directory). Also, I have a fourth, related requirement: When I ask QLibrary to load the library, I want it to specifically search for a library in a very specific path and a library that matches the EXACT name given to it. No 'lib' prefix matching, no 'version string' searching, no looking into LD\_LIBRARY\_PATH... Any help is appreciated. Regards, rohan
2011/05/23
[ "https://Stackoverflow.com/questions/6101273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183133/" ]
add the following to you .pro file ``` # disables the lib prefix CONFIG += no_plugin_name_prefix # disable symlinks & versioning CONFIG += plugin ```
Adding `plugin` to the `CONFIG` variable should disable versioning and the generation of symbolic links to the library. I don't know of a simple way to disable the `lib` prefix though. You way want to dig into the provided QMake spec files to see how the default processing is implemented.
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
As we know the `count()` function always returns the count of the array. So it goes to the else case in every match of the condition. You should try something like this: ``` class Demo{ const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; function calculateResultOfSearch(array $imagesResultArray) { if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return current($imagesResultArray); } elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } } $demo = new Demo(); print_r($demo->calculateResultOfSearch(["positive","positive"])); ``` `array_count_values()` returns an array using the values of the array as keys and their frequency in the array as values. Here is a simple way to check the values of an array containing the same value using `array_count_values` function and count if all keys are the same this should equal. [Reference](https://daveismyname.blog/checking-all-array-keys-are-the-same-with-php)
You're comparing `(count(array_unique($imagesResultArray))` which return an `int` with `self::RESULT_OF_SEARCH_POSITIVE` or `self::RESULT_OF_SEARCH_NEGATIVE` which return a `string` equals to either `"positive"` or `"negative"` so it's always false. You need to change your conditions. **EDIT after OP's edit** PHP: array\_unique > > Takes an input array and returns a new array without duplicate values. > > > In your case you might want to check if the resulting array only has one element equals to `"positive"` or `"negative"`. ``` $newArray = array_unique($imagesResultArray); if (count($newArray) == 1 && $newArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(count($newArray) == 1 && $newArray[0] === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } ```
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
A much simplified version of the code which if `array_unique` just has 1 value, then return it (also I only call it once rather than repeatedly calling it which is very inefficient)... ``` private function calculateResultOfSearch(array $imagesResultArray) { $unique = array_unique($imagesResultArray); return (count($unique) == 1 ) ? $unique[0] : self::RESULT_OF_SEARCH_PARTLY; } ``` **Edit:** I am unfortuantly back after realising I've wasted 20% of the lines I wrote :( If all the items are the same, I can just return the first item of the array passed in so I don't need to store the result of `array_unique()` at all :-/ ``` private function calculateResultOfSearch(array $imagesResultArray) { return ( count(array_unique($imagesResultArray)) == 1 ) ? $imagesResultArray[0]: RESULT_OF_SEARCH_PARTLY; } ```
You're comparing `(count(array_unique($imagesResultArray))` which return an `int` with `self::RESULT_OF_SEARCH_POSITIVE` or `self::RESULT_OF_SEARCH_NEGATIVE` which return a `string` equals to either `"positive"` or `"negative"` so it's always false. You need to change your conditions. **EDIT after OP's edit** PHP: array\_unique > > Takes an input array and returns a new array without duplicate values. > > > In your case you might want to check if the resulting array only has one element equals to `"positive"` or `"negative"`. ``` $newArray = array_unique($imagesResultArray); if (count($newArray) == 1 && $newArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(count($newArray) == 1 && $newArray[0] === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } ```
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
As we know the `count()` function always returns the count of the array. So it goes to the else case in every match of the condition. You should try something like this: ``` class Demo{ const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; function calculateResultOfSearch(array $imagesResultArray) { if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return current($imagesResultArray); } elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } } $demo = new Demo(); print_r($demo->calculateResultOfSearch(["positive","positive"])); ``` `array_count_values()` returns an array using the values of the array as keys and their frequency in the array as values. Here is a simple way to check the values of an array containing the same value using `array_count_values` function and count if all keys are the same this should equal. [Reference](https://daveismyname.blog/checking-all-array-keys-are-the-same-with-php)
Try this code : ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (!in_array(RESULT_OF_SEARCH_NEGATIVE)) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(!in_array(RESULT_OF_SEARCH_POSITIVE)) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
A much simplified version of the code which if `array_unique` just has 1 value, then return it (also I only call it once rather than repeatedly calling it which is very inefficient)... ``` private function calculateResultOfSearch(array $imagesResultArray) { $unique = array_unique($imagesResultArray); return (count($unique) == 1 ) ? $unique[0] : self::RESULT_OF_SEARCH_PARTLY; } ``` **Edit:** I am unfortuantly back after realising I've wasted 20% of the lines I wrote :( If all the items are the same, I can just return the first item of the array passed in so I don't need to store the result of `array_unique()` at all :-/ ``` private function calculateResultOfSearch(array $imagesResultArray) { return ( count(array_unique($imagesResultArray)) == 1 ) ? $imagesResultArray[0]: RESULT_OF_SEARCH_PARTLY; } ```
As we know the `count()` function always returns the count of the array. So it goes to the else case in every match of the condition. You should try something like this: ``` class Demo{ const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; function calculateResultOfSearch(array $imagesResultArray) { if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return current($imagesResultArray); } elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } } $demo = new Demo(); print_r($demo->calculateResultOfSearch(["positive","positive"])); ``` `array_count_values()` returns an array using the values of the array as keys and their frequency in the array as values. Here is a simple way to check the values of an array containing the same value using `array_count_values` function and count if all keys are the same this should equal. [Reference](https://daveismyname.blog/checking-all-array-keys-are-the-same-with-php)
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
As we know the `count()` function always returns the count of the array. So it goes to the else case in every match of the condition. You should try something like this: ``` class Demo{ const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; function calculateResultOfSearch(array $imagesResultArray) { if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) { return current($imagesResultArray); } elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } } $demo = new Demo(); print_r($demo->calculateResultOfSearch(["positive","positive"])); ``` `array_count_values()` returns an array using the values of the array as keys and their frequency in the array as values. Here is a simple way to check the values of an array containing the same value using `array_count_values` function and count if all keys are the same this should equal. [Reference](https://daveismyname.blog/checking-all-array-keys-are-the-same-with-php)
With your guys answers I came to this "clean" solution. ``` private function calculateResultOfSearch(array $imagesResultArray) { $results = array_unique($imagesResultArray); if(count($results) == 1 && $results[0] === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } if(count($results) == 1 && $results[0] === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } return self::RESULT_OF_SEARCH_PARTLY; } ```
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
A much simplified version of the code which if `array_unique` just has 1 value, then return it (also I only call it once rather than repeatedly calling it which is very inefficient)... ``` private function calculateResultOfSearch(array $imagesResultArray) { $unique = array_unique($imagesResultArray); return (count($unique) == 1 ) ? $unique[0] : self::RESULT_OF_SEARCH_PARTLY; } ``` **Edit:** I am unfortuantly back after realising I've wasted 20% of the lines I wrote :( If all the items are the same, I can just return the first item of the array passed in so I don't need to store the result of `array_unique()` at all :-/ ``` private function calculateResultOfSearch(array $imagesResultArray) { return ( count(array_unique($imagesResultArray)) == 1 ) ? $imagesResultArray[0]: RESULT_OF_SEARCH_PARTLY; } ```
Try this code : ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (!in_array(RESULT_OF_SEARCH_NEGATIVE)) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(!in_array(RESULT_OF_SEARCH_POSITIVE)) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
53,408,671
I have an array with 2 possible values `negative` and `positive`. If all the values are `positive` my function has to return `positive`. If all values are `negative` my function has to return `negative`. If the values are a mix then my function has to return `partly`. My code always returns `partly`, unfortunately, I don't know why. ``` const RESULT_OF_SEARCH_POSITIVE = "positive"; const RESULT_OF_SEARCH_NEGATIVE = "negative"; const RESULT_OF_SEARCH_PARTLY = "partly"; ... private function calculateResultOfSearch(array $imagesResultArray) { if (array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } elseif(array_unique($imagesResultArray) === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } else { return self::RESULT_OF_SEARCH_PARTLY; } } ```
2018/11/21
[ "https://Stackoverflow.com/questions/53408671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10320170/" ]
A much simplified version of the code which if `array_unique` just has 1 value, then return it (also I only call it once rather than repeatedly calling it which is very inefficient)... ``` private function calculateResultOfSearch(array $imagesResultArray) { $unique = array_unique($imagesResultArray); return (count($unique) == 1 ) ? $unique[0] : self::RESULT_OF_SEARCH_PARTLY; } ``` **Edit:** I am unfortuantly back after realising I've wasted 20% of the lines I wrote :( If all the items are the same, I can just return the first item of the array passed in so I don't need to store the result of `array_unique()` at all :-/ ``` private function calculateResultOfSearch(array $imagesResultArray) { return ( count(array_unique($imagesResultArray)) == 1 ) ? $imagesResultArray[0]: RESULT_OF_SEARCH_PARTLY; } ```
With your guys answers I came to this "clean" solution. ``` private function calculateResultOfSearch(array $imagesResultArray) { $results = array_unique($imagesResultArray); if(count($results) == 1 && $results[0] === self::RESULT_OF_SEARCH_NEGATIVE) { return self::RESULT_OF_SEARCH_NEGATIVE; } if(count($results) == 1 && $results[0] === self::RESULT_OF_SEARCH_POSITIVE) { return self::RESULT_OF_SEARCH_POSITIVE; } return self::RESULT_OF_SEARCH_PARTLY; } ```
48,624,971
I've done a heightmap in android studio. It has a Main activity that looks like this: ``` public class MainActivity extends AppCompatActivity { private GLSurfaceView glSurfaceView; private boolean rendererSet = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); glSurfaceView = new GLSurfaceView(this); final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000 || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && (Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86"))); final FirstOpenGLProjectRenderer firstOpenGLProjectRenderer = new FirstOpenGLProjectRenderer(this); if(!firstOpenGLProjectRenderer.getError()) { if (supportsEs2) { glSurfaceView.setEGLContextClientVersion(2); glSurfaceView.setRenderer(firstOpenGLProjectRenderer); rendererSet = true; } else { Toast.makeText(this, "this device does not support OpenGL ES 2.0", Toast.LENGTH_LONG).show(); return; } setContentView(glSurfaceView); }else{ setContentView(R.layout.error); } } @Override protected void onPause(){ super.onPause(); if(rendererSet) {glSurfaceView.onPause();} } @Override protected void onResume(){ super.onResume(); if(rendererSet){ glSurfaceView.onResume(); } } public static void main(String []args){} } ``` and i also have the renderer class that looks like this: ``` public class FirstOpenGLProjectRenderer implements Renderer { private float min; private float max; private float ratio; private FloatBuffer vertexPositions; private FloatBuffer vertexColors; private int alpha = 1000; private float[] positions; private float[] colors; private Context context; private boolean error; private ArrayList<Float> nodePositions; private static final int BYTES_PER_FLOAT = 4; private int program; private static final String A_COLOR = "a_Color"; private int aColorLocation; private static final String A_POSITION = "a_Position"; private int aPositionLocation; private final int POSITION_COMPONENT_COUNT = 3; //x,y,z private ArrayList<Float> triangleZList; public FirstOpenGLProjectRenderer(Context context) { this.context = context; ArcGridReader arcGridReader = new ArcGridReader(context); this.nodePositions = arcGridReader.getNodePositions(); this.triangleZList = arcGridReader.getTriangleZList(); error = arcGridReader.getError(); if(!error) { calc(); } } public boolean calc(){ positions = new float[nodePositions.size()]; //Todo: färgerna colors = new float[triangleZList.size() * 3]; min = Collections.min(triangleZList) / alpha; max = Collections.max(triangleZList) / alpha; ratio = (200 / (max - min)); int i = 0; for (Float test : nodePositions) { positions[i] = test / alpha; i++; } double amount = (max/3)*alpha; i = 0; for (Float test : triangleZList) { if(test<=0){ setColors(test,i,0); i=i+3; } if(test>0 && test<=amount){ setColors(test,i,10); i=i+3; } if(test>amount && test<=(2*amount)){ setColors(test,i,20); i=i+3; } if(test>(2*amount) && test<=(3*amount)){ setColors(test,i,30); i=i+3; } } vertexPositions = ByteBuffer .allocateDirect(positions.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexPositions.put(positions); vertexColors = ByteBuffer .allocateDirect(colors.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexColors.put(colors); return true; } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); GLES20.glEnable(GLES20.GL_CULL_FACE); GLES20.glEnable(GLES20.GL_DEPTH_TEST); String vertexShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.vertex_shader); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.fragment_shader); int vertexShader = ShaderHelper.compileVertexShader(vertexShaderSource); int fragmentShader = ShaderHelper.compileFragmentShader(fragmentShaderSource); program = ShaderHelper.linkProgram(vertexShader, fragmentShader); if (LoggerConfig.ON) { ShaderHelper.validateProgram(program); } glUseProgram(program); aColorLocation = glGetAttribLocation(program, A_COLOR); aPositionLocation = glGetAttribLocation(program, A_POSITION); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 glUnused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); glUseProgram(program); vertexPositions.position(0); glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexPositions); glEnableVertexAttribArray(aPositionLocation); vertexColors.position(0); glVertexAttribPointer(aColorLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexColors); glEnableVertexAttribArray(aColorLocation); glDrawArrays(GL_TRIANGLES, 0, positions.length); } public void setColors (Float test, int i,int number){ switch (number){ case 0: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 10: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 20: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 30: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; } } public boolean getError(){ return error; } } ``` so now i would like to add a zoom function, with the help of two buttons. I know the code for the zoomfunction, but I'm stuck with the implementation of the buttons. What is the best/easiest way to make the buttons and to reach them? I have only thought of one way, which is to make a fragment in the main activity, is there a better way? i have searched, but came up with nothing. Perhaps I'm lacking some keywords since I'm not a frequent user in Android Studio. Cheers! :)
2018/02/05
[ "https://Stackoverflow.com/questions/48624971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8752206/" ]
I found something that suited me better, i just added the following code in mainactivity: ``` ... setContentView(glSurfaceView); LinearLayout ll = new LinearLayout(this); Button zoomIn = new Button(this); zoomIn.setText("zoomIn"); Button zoomOut = new Button(this); zoomOut.setText("zoomOut"); ll.addView(zoomIn); ll.addView(zoomOut); this.addContentView(ll,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ... ``` where this.addContentView were a keypart in it.
The easiest way is to use separate layer for your UI(buttons, texts, edits, etc) and put it above your `GLSurfaceView`. Define your layout in xml: ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <GLSurfaceView android:id="@+id/gl_surface_view" android:background="#ff0000" android:layout_width="match_parent" android:layout_height="match_parent"/> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btn_zoom_in" android:text="ZoomIn" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_zoom_out" android:text="ZoomOut" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </FrameLayout> ``` And then get your `glSurfaceView` in activity and handle button clicks: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); glSurfaceView = new GLSurfaceView(this); findViewById(R.id.btn_zoom_in).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //handle zoom in } }); findViewById(R.id.btn_zoom_out).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //handle zoom out } }); //... } ``` That's all. Worth mentioning another much more complicated way: draw UI completely in OpenGL and intercept touch events from your GL Surface: ``` class Surface extends GLSurfaceView{ public Surface(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } } ```
48,624,971
I've done a heightmap in android studio. It has a Main activity that looks like this: ``` public class MainActivity extends AppCompatActivity { private GLSurfaceView glSurfaceView; private boolean rendererSet = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); glSurfaceView = new GLSurfaceView(this); final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000 || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && (Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86"))); final FirstOpenGLProjectRenderer firstOpenGLProjectRenderer = new FirstOpenGLProjectRenderer(this); if(!firstOpenGLProjectRenderer.getError()) { if (supportsEs2) { glSurfaceView.setEGLContextClientVersion(2); glSurfaceView.setRenderer(firstOpenGLProjectRenderer); rendererSet = true; } else { Toast.makeText(this, "this device does not support OpenGL ES 2.0", Toast.LENGTH_LONG).show(); return; } setContentView(glSurfaceView); }else{ setContentView(R.layout.error); } } @Override protected void onPause(){ super.onPause(); if(rendererSet) {glSurfaceView.onPause();} } @Override protected void onResume(){ super.onResume(); if(rendererSet){ glSurfaceView.onResume(); } } public static void main(String []args){} } ``` and i also have the renderer class that looks like this: ``` public class FirstOpenGLProjectRenderer implements Renderer { private float min; private float max; private float ratio; private FloatBuffer vertexPositions; private FloatBuffer vertexColors; private int alpha = 1000; private float[] positions; private float[] colors; private Context context; private boolean error; private ArrayList<Float> nodePositions; private static final int BYTES_PER_FLOAT = 4; private int program; private static final String A_COLOR = "a_Color"; private int aColorLocation; private static final String A_POSITION = "a_Position"; private int aPositionLocation; private final int POSITION_COMPONENT_COUNT = 3; //x,y,z private ArrayList<Float> triangleZList; public FirstOpenGLProjectRenderer(Context context) { this.context = context; ArcGridReader arcGridReader = new ArcGridReader(context); this.nodePositions = arcGridReader.getNodePositions(); this.triangleZList = arcGridReader.getTriangleZList(); error = arcGridReader.getError(); if(!error) { calc(); } } public boolean calc(){ positions = new float[nodePositions.size()]; //Todo: färgerna colors = new float[triangleZList.size() * 3]; min = Collections.min(triangleZList) / alpha; max = Collections.max(triangleZList) / alpha; ratio = (200 / (max - min)); int i = 0; for (Float test : nodePositions) { positions[i] = test / alpha; i++; } double amount = (max/3)*alpha; i = 0; for (Float test : triangleZList) { if(test<=0){ setColors(test,i,0); i=i+3; } if(test>0 && test<=amount){ setColors(test,i,10); i=i+3; } if(test>amount && test<=(2*amount)){ setColors(test,i,20); i=i+3; } if(test>(2*amount) && test<=(3*amount)){ setColors(test,i,30); i=i+3; } } vertexPositions = ByteBuffer .allocateDirect(positions.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexPositions.put(positions); vertexColors = ByteBuffer .allocateDirect(colors.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexColors.put(colors); return true; } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); GLES20.glEnable(GLES20.GL_CULL_FACE); GLES20.glEnable(GLES20.GL_DEPTH_TEST); String vertexShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.vertex_shader); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.fragment_shader); int vertexShader = ShaderHelper.compileVertexShader(vertexShaderSource); int fragmentShader = ShaderHelper.compileFragmentShader(fragmentShaderSource); program = ShaderHelper.linkProgram(vertexShader, fragmentShader); if (LoggerConfig.ON) { ShaderHelper.validateProgram(program); } glUseProgram(program); aColorLocation = glGetAttribLocation(program, A_COLOR); aPositionLocation = glGetAttribLocation(program, A_POSITION); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 glUnused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); glUseProgram(program); vertexPositions.position(0); glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexPositions); glEnableVertexAttribArray(aPositionLocation); vertexColors.position(0); glVertexAttribPointer(aColorLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexColors); glEnableVertexAttribArray(aColorLocation); glDrawArrays(GL_TRIANGLES, 0, positions.length); } public void setColors (Float test, int i,int number){ switch (number){ case 0: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 10: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 20: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 30: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; } } public boolean getError(){ return error; } } ``` so now i would like to add a zoom function, with the help of two buttons. I know the code for the zoomfunction, but I'm stuck with the implementation of the buttons. What is the best/easiest way to make the buttons and to reach them? I have only thought of one way, which is to make a fragment in the main activity, is there a better way? i have searched, but came up with nothing. Perhaps I'm lacking some keywords since I'm not a frequent user in Android Studio. Cheers! :)
2018/02/05
[ "https://Stackoverflow.com/questions/48624971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8752206/" ]
The easiest way is to use separate layer for your UI(buttons, texts, edits, etc) and put it above your `GLSurfaceView`. Define your layout in xml: ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <GLSurfaceView android:id="@+id/gl_surface_view" android:background="#ff0000" android:layout_width="match_parent" android:layout_height="match_parent"/> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/btn_zoom_in" android:text="ZoomIn" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_zoom_out" android:text="ZoomOut" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </FrameLayout> ``` And then get your `glSurfaceView` in activity and handle button clicks: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); glSurfaceView = new GLSurfaceView(this); findViewById(R.id.btn_zoom_in).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //handle zoom in } }); findViewById(R.id.btn_zoom_out).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //handle zoom out } }); //... } ``` That's all. Worth mentioning another much more complicated way: draw UI completely in OpenGL and intercept touch events from your GL Surface: ``` class Surface extends GLSurfaceView{ public Surface(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } } ```
1. Design the xml layout. Yes, buttons, bells and whistles. ConstraintLayout will do just fine 2. LayoutInflater inflater = getLayoutInflater(); 3. getWindow().addContentView(inflater.inflate(R.layout.your\_xml\_layout, null), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH\_PARENT, ViewGroup.LayoutParams.MATCH\_PARENT)); 4. Add events to the buttons and such 5. You are done! Now you have a perfectly designed UI on top of your GLSurfaceView!
48,624,971
I've done a heightmap in android studio. It has a Main activity that looks like this: ``` public class MainActivity extends AppCompatActivity { private GLSurfaceView glSurfaceView; private boolean rendererSet = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); glSurfaceView = new GLSurfaceView(this); final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000 || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && (Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86"))); final FirstOpenGLProjectRenderer firstOpenGLProjectRenderer = new FirstOpenGLProjectRenderer(this); if(!firstOpenGLProjectRenderer.getError()) { if (supportsEs2) { glSurfaceView.setEGLContextClientVersion(2); glSurfaceView.setRenderer(firstOpenGLProjectRenderer); rendererSet = true; } else { Toast.makeText(this, "this device does not support OpenGL ES 2.0", Toast.LENGTH_LONG).show(); return; } setContentView(glSurfaceView); }else{ setContentView(R.layout.error); } } @Override protected void onPause(){ super.onPause(); if(rendererSet) {glSurfaceView.onPause();} } @Override protected void onResume(){ super.onResume(); if(rendererSet){ glSurfaceView.onResume(); } } public static void main(String []args){} } ``` and i also have the renderer class that looks like this: ``` public class FirstOpenGLProjectRenderer implements Renderer { private float min; private float max; private float ratio; private FloatBuffer vertexPositions; private FloatBuffer vertexColors; private int alpha = 1000; private float[] positions; private float[] colors; private Context context; private boolean error; private ArrayList<Float> nodePositions; private static final int BYTES_PER_FLOAT = 4; private int program; private static final String A_COLOR = "a_Color"; private int aColorLocation; private static final String A_POSITION = "a_Position"; private int aPositionLocation; private final int POSITION_COMPONENT_COUNT = 3; //x,y,z private ArrayList<Float> triangleZList; public FirstOpenGLProjectRenderer(Context context) { this.context = context; ArcGridReader arcGridReader = new ArcGridReader(context); this.nodePositions = arcGridReader.getNodePositions(); this.triangleZList = arcGridReader.getTriangleZList(); error = arcGridReader.getError(); if(!error) { calc(); } } public boolean calc(){ positions = new float[nodePositions.size()]; //Todo: färgerna colors = new float[triangleZList.size() * 3]; min = Collections.min(triangleZList) / alpha; max = Collections.max(triangleZList) / alpha; ratio = (200 / (max - min)); int i = 0; for (Float test : nodePositions) { positions[i] = test / alpha; i++; } double amount = (max/3)*alpha; i = 0; for (Float test : triangleZList) { if(test<=0){ setColors(test,i,0); i=i+3; } if(test>0 && test<=amount){ setColors(test,i,10); i=i+3; } if(test>amount && test<=(2*amount)){ setColors(test,i,20); i=i+3; } if(test>(2*amount) && test<=(3*amount)){ setColors(test,i,30); i=i+3; } } vertexPositions = ByteBuffer .allocateDirect(positions.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexPositions.put(positions); vertexColors = ByteBuffer .allocateDirect(colors.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); vertexColors.put(colors); return true; } @Override public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); GLES20.glEnable(GLES20.GL_CULL_FACE); GLES20.glEnable(GLES20.GL_DEPTH_TEST); String vertexShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.vertex_shader); String fragmentShaderSource = TextResourceReader .readTextFileFromResource(context, R.raw.fragment_shader); int vertexShader = ShaderHelper.compileVertexShader(vertexShaderSource); int fragmentShader = ShaderHelper.compileFragmentShader(fragmentShaderSource); program = ShaderHelper.linkProgram(vertexShader, fragmentShader); if (LoggerConfig.ON) { ShaderHelper.validateProgram(program); } glUseProgram(program); aColorLocation = glGetAttribLocation(program, A_COLOR); aPositionLocation = glGetAttribLocation(program, A_POSITION); } @Override public void onSurfaceChanged(GL10 glUnused, int width, int height) { glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 glUnused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); glUseProgram(program); vertexPositions.position(0); glVertexAttribPointer(aPositionLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexPositions); glEnableVertexAttribArray(aPositionLocation); vertexColors.position(0); glVertexAttribPointer(aColorLocation, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, vertexColors); glEnableVertexAttribArray(aColorLocation); glDrawArrays(GL_TRIANGLES, 0, positions.length); } public void setColors (Float test, int i,int number){ switch (number){ case 0: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 10: colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 20: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; case 30: colors[i] = 1*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; colors[i] = 0*(((test - min) / alpha) * ratio + 20) / 255f; i++; break; } } public boolean getError(){ return error; } } ``` so now i would like to add a zoom function, with the help of two buttons. I know the code for the zoomfunction, but I'm stuck with the implementation of the buttons. What is the best/easiest way to make the buttons and to reach them? I have only thought of one way, which is to make a fragment in the main activity, is there a better way? i have searched, but came up with nothing. Perhaps I'm lacking some keywords since I'm not a frequent user in Android Studio. Cheers! :)
2018/02/05
[ "https://Stackoverflow.com/questions/48624971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8752206/" ]
I found something that suited me better, i just added the following code in mainactivity: ``` ... setContentView(glSurfaceView); LinearLayout ll = new LinearLayout(this); Button zoomIn = new Button(this); zoomIn.setText("zoomIn"); Button zoomOut = new Button(this); zoomOut.setText("zoomOut"); ll.addView(zoomIn); ll.addView(zoomOut); this.addContentView(ll,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ... ``` where this.addContentView were a keypart in it.
1. Design the xml layout. Yes, buttons, bells and whistles. ConstraintLayout will do just fine 2. LayoutInflater inflater = getLayoutInflater(); 3. getWindow().addContentView(inflater.inflate(R.layout.your\_xml\_layout, null), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH\_PARENT, ViewGroup.LayoutParams.MATCH\_PARENT)); 4. Add events to the buttons and such 5. You are done! Now you have a perfectly designed UI on top of your GLSurfaceView!
45,872,647
I drew a multi series line using d3 and added a vertical line when mouse hover over points. And I want to hide the vertical line and the text in 2018 point which has no data. I don't know how to select the line at the specific point which is `translate(415,0)`, so I am not able to change the style to `display:none`; Here is the code: ```js var data =[ { 'timescale': '2015', 'Not': 31, 'Nearly': 59, 'Standard': 81, 'Exceed':100 }, { 'timescale': '2016', 'Not': 28, 'Nearly': 55, 'Standard': 78, 'Exceed':100 }, { 'timescale': '2017', 'Not': 25, 'Nearly': 51, 'Standard': 75, 'Exceed':100 }, { 'timescale': '2018', 'Not': "null", 'Nearly': "null", 'Standard': "null", 'Exceed':"null" }, { 'timescale': '2019', 'Not': 41, 'Nearly': 67, 'Standard': 90, 'Exceed':100 }, { 'timescale': '2020', 'Not': 36, 'Nearly': 61, 'Standard': 86, 'Exceed':100 }, { 'timescale': '2021', 'Not': 31, 'Nearly': 55, 'Standard': 82, 'Exceed':100 } ]; //d3.csv("test.csv", function(error,data){ console.log(data); // set the dimensions and margins of the graph var margin = { top: 20, right: 80, bottom: 30, left: 50 }, svg = d3.select('svg'), width = +svg.attr('width') - margin.left - margin.right, height = +svg.attr('height') - margin.top - margin.bottom; var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // set the ranges var x = d3.scaleBand().rangeRound([0, width]).padding(1), y = d3.scaleLinear().rangeRound([height, 0]), z = d3.scaleOrdinal(["#BBB84B","#789952","#50DB51","#2D602A"]); // define the line var line = d3.line() .defined(function (d) { return !isNaN(d.total); }) .x(function(d) { return x(d.timescale); }) .y(function(d) { return y(d.total); }); // scale the range of the data z.domain(d3.keys(data[0]).filter(function(key) { return key !== "timescale"; })); var trends = z.domain().map(function(name) { return { name: name, values: data.map(function(d) { return { timescale: d.timescale, total: +d[name] }; }) }; }); x.domain(data.map(function(d) { return d.timescale; })); y.domain([0, d3.max(trends, function(c) { return d3.max(c.values, function(v) { return v.total; }); })]); // Draw the line var trend = g.selectAll(".trend") .data(trends) .enter() .append("g") .attr("class", "trend"); trend.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return z(d.name); }); // Draw the empty value for every point var points = g.selectAll('.points') .data(trends) .enter() .append('g') .attr('class', 'points') .append('text'); // Draw the circle trend .style("fill", "#FFF") .style("stroke", function(d) { return z(d.name); }) .selectAll("circle.line") .data(function(d){return d.values} ) .enter() .append("circle") .filter(function(d) { return d.timescale !== "2018" }) .attr("r", 5) .style("stroke-width", 3) .attr("cx", function(d) { return x(d.timescale); }) .attr("cy", function(d) { return y(d.total); }); // Draw the axis g.append("g") .attr("class", "axis axis-x") .attr("transform", "translate(0, " + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis axis-y") .call(d3.axisLeft(y).ticks(6)); var focus = g.append('g') .attr('class','focus') .style('display', 'none'); focus.append('line') .attr('class', 'x-hover-line hover-line') .attr('y1' , 0) .attr('y2', height) .style('stroke',"black"); svg.append('rect') .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", mouseover) .on("mouseout", mouseout) .on("mousemove", mousemove); // var timeScales = data.map(function(name) { return x(name.timescale); }); // console.log(timeScales); var timeScales = [106,209,312,415,518,621,724]; // d3.select('.focus') // .attr("x1",415) // .attr("y1",0) // .attr("x2",415) // .attr("y2",height) // .style("display","none"); function mouseover() { focus.style("display", null); d3.selectAll('.points text').style("display", null); } function mouseout() { focus.style("display", "none"); d3.selectAll('.points text').style("display", "none"); } function mousemove() { var i = d3.bisect(timeScales, d3.mouse(this)[0], 1); var di = data[i-1]; focus.attr("transform", "translate(" + x(di.timescale) + ",0)"); d3.selectAll('.points text') .attr('x', function(d) { return x(di.timescale) + 5; }) .attr('y', function(d) { return y(d.values[i-1].total)-5; }) .text(function(d) { return d.values[i-1].total; }) .style('fill', function(d) { return z(d.name); }); } ``` ```css body { font-family: 'Proxima Nova', Georgia, sans-serif; } .line { fill: none; stroke-width: 3px; } .overlay { fill: none; pointer-events: all; } .hover-line { stroke-width: 2px; stroke-dasharray: 3,3; } ``` ```html <svg width="960" height="500"></svg> <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js'></script> ```
2017/08/25
[ "https://Stackoverflow.com/questions/45872647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435842/" ]
In the mousemove function only perform the transformation if timescale is not 2018: ``` function mousemove() { var i = d3.bisect(timeScales, d3.mouse(this)[0], 1); var di = data[i-1]; if (di.timescale !== '2018') { focus.attr("transform", "translate(" + x(di.timescale) + ",0)"); d3.selectAll('.points text') .attr('x', function(d) { return x(di.timescale) + 5; }) .attr('y', function(d) { return y(d.values[i-1].total)-5; }) .text(function(d) { return d.values[i-1].total; }) .style('fill', function(d) { return z(d.name); }); } } ```
> > you have using bisection as a tip > > > so it will draw only when it selected, lets change that so it will not draw the 2018 when mouseover it ```js var data =[ { 'timescale': '2015', 'Not': 31, 'Nearly': 59, 'Standard': 81, 'Exceed':100 }, { 'timescale': '2016', 'Not': 28, 'Nearly': 55, 'Standard': 78, 'Exceed':100 }, { 'timescale': '2017', 'Not': 25, 'Nearly': 51, 'Standard': 75, 'Exceed':100 }, { 'timescale': '2018', 'Not': "null", 'Nearly': "null", 'Standard': "null", 'Exceed':"null" }, { 'timescale': '2019', 'Not': 41, 'Nearly': 67, 'Standard': 90, 'Exceed':100 }, { 'timescale': '2020', 'Not': 36, 'Nearly': 61, 'Standard': 86, 'Exceed':100 }, { 'timescale': '2021', 'Not': 31, 'Nearly': 55, 'Standard': 82, 'Exceed':100 } ]; //d3.csv("test.csv", function(error,data){ // console.log(data); // set the dimensions and margins of the graph var margin = { top: 20, right: 80, bottom: 30, left: 50 }, svg = d3.select('svg'), width = +svg.attr('width') - margin.left - margin.right, height = +svg.attr('height') - margin.top - margin.bottom; var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // set the ranges var x = d3.scaleBand().rangeRound([0, width]).padding(1), y = d3.scaleLinear().rangeRound([height, 0]), z = d3.scaleOrdinal(["#BBB84B","#789952","#50DB51","#2D602A"]); // define the line var line = d3.line() .defined(function (d) { return !isNaN(d.total); }) .x(function(d) { return x(d.timescale); }) .y(function(d) { return y(d.total); }); // scale the range of the data z.domain(d3.keys(data[0]).filter(function(key) { return key !== "timescale"; })); var trends = z.domain().map(function(name) { return { name: name, values: data.map(function(d) { return { timescale: d.timescale, total: +d[name] }; }) }; }); x.domain(data.map(function(d) { return d.timescale; })); y.domain([0, d3.max(trends, function(c) { return d3.max(c.values, function(v) { return v.total; }); })]); // Draw the line var trend = g.selectAll(".trend") .data(trends) .enter() .append("g") .attr("class", "trend"); trend.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return z(d.name); }); // Draw the empty value for every point var points = g.selectAll('.points') .data(trends) .enter() .append('g') .attr('class', 'points') .append('text'); // Draw the circle trend .style("fill", "#FFF") .style("stroke", function(d) { return z(d.name); }) .selectAll("circle.line") .data(function(d){return d.values} ) .enter() .append("circle") .filter(function(d) { return d.timescale !== "2018" }) .attr("r", 5) .style("stroke-width", 3) .attr("cx", function(d) { return x(d.timescale); }) .attr("cy", function(d) { return y(d.total); }); // Draw the axis g.append("g") .attr("class", "axis axis-x") .attr("transform", "translate(0, " + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis axis-y") .call(d3.axisLeft(y).ticks(6)); var focus = g.append('g') .attr('class','focus') .style('display', 'none'); focus.append('line') .attr('class', 'x-hover-line hover-line') .attr('y1' , 0) .attr('y2', height) .style('stroke',"black"); svg.append('rect') .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", mouseover) .on("mouseout", mouseout) .on("mousemove", mousemove); // var timeScales = data.map(function(name) { return x(name.timescale); }); // console.log(timeScales); var timeScales = [106,209,312,415,518,621,724]; // d3.select('.focus') // .attr("x1",415) // .attr("y1",0) // .attr("x2",415) // .attr("y2",height) // .style("display","none"); function mouseover() { focus.style("display", null); d3.selectAll('.points text').style("display", null); } function mouseout() { focus.style("display", "none"); d3.selectAll('.points text').style("display", "none"); } function mousemove() { var i = d3.bisect(timeScales, d3.mouse(this)[0], 1); var di = data[i-1]; console.log(di) if (di.timescale =="2018"){ focus.style('display','none') d3.selectAll('.points text').style("display", "none"); }else{ focus.style('display','block') d3.selectAll('.points text').style("display", "block"); focus.attr("transform", "translate(" + x(di.timescale) + ",0)");} d3.selectAll('.points text') .attr('x', function(d) { return x(di.timescale) + 5; }) .attr('y', function(d) { return y(d.values[i-1].total)-5; }) .text(function(d) { return d.values[i-1].total; }) .style('fill', function(d) { return z(d.name); }); } ``` ```css body { font-family: 'Proxima Nova', Georgia, sans-serif; } .line { fill: none; stroke-width: 3px; } .overlay { fill: none; pointer-events: all; } .hover-line { stroke-width: 2px; stroke-dasharray: 3,3; } ``` ```html <svg width="960" height="500"></svg> <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js'></script> ```
61,822,329
I'm confused as how to correctly use vueDraggable together with Laravel. I can drag and sort the elements in the browser but the array is not changing (when I check in the console)/ it seems to me the changes aren't reflected in the array. Shouldn't the array index numbers change after moving items? In the overview.blade.php I have the component: ``` <qm-draggable :list="{{ $mylaravelarray }}"></qm-draggable> ``` In the qm-draggable.vue I have: ``` <template> <draggable group="fragenblatt" @start="drag=true" @end="endDrag" handle=".handle"> <li v-for="(item, index) in draggablearray" :key="item.index"> // list items here </li> </draggable> </template> <script> data() { return { draggablearray:{}, }; }, props: { list: Array, }, mounted: function(){ this.draggablearray = this.list; // create a new array so I don't alter the prop directly. }, [..] </script> ``` In the [documentation](https://github.com/SortableJS/Vue.Draggable#props) it says, one way to pass the array is: value Type: Array Required: false Default: null Input array to draggable component. Typically same array as referenced by inner element v-for directive. This is the preferred way to use Vue.draggable as it is compatible with Vuex. It should not be used directly but only though the v-model directive: ``` <draggable v-model="myArray"> ``` But where do I do that? in overview.blade.php or in the component (.vue), or both?
2020/05/15
[ "https://Stackoverflow.com/questions/61822329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12056985/" ]
Try setting `v-model` on your `draggable` as that's what will update `draggablearray`. Also if `draggablearray` is supposed to be an array, initialise it as one, so `draggablearray:{}` should be `draggablearray:[]`. ```js new Vue({ el: '#app', data: () => { return { drag: false, draggablearray: [{ id: 1, name: "1" }, { id: 2, name: "2" }, { id: 3, name: "3" }] } } }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"> </script> <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.7.0/Sortable.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script> <div class="container"> <div id="app"> <draggable v-model="draggablearray" group="fragenblatt"> <li v-for="(item, index) in draggablearray"> {{item.name}} </li> </draggable> {{draggablearray}} </div> </div> <script type="text/x-template" id="tree-menu"> <div class="tree-menu"> <div class="label-wrapper"> <div :style="indent" :class="labelClasses" @click.stop="toggleChildren"> <i v-if="nodes" class="fa" :class="iconClasses"></i> <input type="checkbox" :checked="selected" @input="tickChildren" @click.stop /> {{label}} </div> </div> <draggable v-model="nodes" :options="{group:{ name:'g1'}}"> <tree-menu v-if="showChildren" v-for="node in nodes" :nodes="node.nodes" :label="node.label" :depth="depth + 1" :selected="node.selected" :key="node"> </tree-menu> </draggable> </div> </script> ```
Ah, I solved it, now I get the altered array back, I achieved it with this: 1. Had to add v-model="draggablearray" in the component .vue file 2. Needed to change my 'draggablearray' in data to an Array, instead of object. It looks like this now: In the overview.blade.php I have the component: ``` <qm-draggable :list="{{ $mylaravelarray }}"></qm-draggable> ``` In the qm-draggable.vue I have: ``` <template> <draggable v-model="draggablearray" group="fragenblatt" @start="drag=true" @end="endDrag" handle=".handle"> <li v-for="(item, index) in draggablearray" :key="item.index"> // list items here </li> </draggable> </template> <script> data() { return { draggablearray:[], //has to be an Array, was '{}' before }; }, props: { list: Array, }, mounted: function(){ this.draggablearray = this.list; // create a new array so I don't alter the prop directly. }, [..] </script> ```
32,432,277
I was wondering if there is any efficient way to compare 2 large files line by line. **File 1** ``` 2 3 2 ``` **File 2** ``` 2 | haha 3 | hoho 4 | hehe ``` I am just taking the first character of each file and comparing against them. Currently i am using a very naive method of iterating through them in a double for loop. **Like** ``` For i in file 1: line number = 0 For j in file 2: loop until line number == counter else add 1 to line number Compare line 1 increase counter ``` Reading both files into memory is not an option. I am using python on linux but i am open to both bash solutions and python script solutions
2015/09/07
[ "https://Stackoverflow.com/questions/32432277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1939166/" ]
What about something like this: ``` diff <(cut -c 1 file1.txt) <(cut -c 1 file2.txt) ``` [`diff`](http://man7.org/linux/man-pages/man1/diff.1.html) is the tool you use to compare files' lines. You can use [process substitution](https://en.wikipedia.org/wiki/Process_substitution) (anonymous pipe) to compare a version of each file only containing the first character (using [`cut`](http://linux.die.net/man/1/cut)).
You could zip the two files and iterate them together. ``` f1 = open('File 1') f2 = open('File 2') flag = True for file1_line, file2_line in zip(f1, f2): if file1_line[0] != file2_line[0]: flag = False break print(flag) ```
29,870,713
I'm trying to generate a query like the following via Knex.js: ```sql INSERT INTO table ("column1", "column2") SELECT "someVal", 12345 WHERE NOT EXISTS ( SELECT 1 FROM table WHERE "column2" = 12345 ) ``` Basically, I want to insert values only if a particular value does not already exist. But Knex.js doesn't seem to know how to do this; if I call `knex.insert()` (with no values), it generates an "insert default values" query. I tried the following: ```js pg.insert() .into(tableName) .select(_.values(data)) .whereNotExists( pg.select(1) .from(tableName) .where(blah) ); ``` but that still just gives me the default values thing. I tried adding a `.columns(Object.keys(data))` in hopes that `insert()` would honor that, but no luck. Is it possible to generate the query I want with knex, or will I just have to build up a raw query, without Knex.js methods?
2015/04/25
[ "https://Stackoverflow.com/questions/29870713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324399/" ]
I believe the select needs to be passed into the insert: ``` pg.insert(knex.select().from("tableNameToSelectDataFrom")).into("tableToInsertInto"); ``` Also in order to select constant values or expressions you'll need to use a knex.raw expression in the select: ``` knex.select(knex.raw("'someVal',12345")).from("tableName") ``` This is my first post and I didn't test your specific example but I've done similar things like what you're asking using the above techniques.
The most comprehensive answer I've found (with explicit column names for `INSERT`, and custom values in the `SELECT`-statement) is here: <https://github.com/knex/knex/issues/1056#issuecomment-156535234> by [Chris Broome](https://github.com/chrisbroome) here is a copy of that solution: ```js const query = knex // this part generates this part of the // query: INSERT "tablename" ("field1", "field2" ..) .into(knex.raw('?? (??, ??)', ['tableOrders', 'field_user_id', 'email_field'])) // and here is the second part of the SQL with "SELECT" .insert(function() { this .select( 'user_id', // select from column without alias knex.raw('? AS ??', ['jdoe@gmail.com', 'email']), // select static value with alias ) .from('users AS u') .where('u.username', 'jdoe') }); console.log(query.toString()); ``` and the SQL-output: ```sql insert into "orders" ("user_id", "email") select "user_id", 'jdoe@gmail.com' AS "email" from "users" as "u" where "u"."username" = 'jdoe' ``` --- another one approach (by Knex developer): <https://github.com/knex/knex/commit/e74f43cfe57ab27b02250948f8706d16c5d821b8#diff-cb48f4af7c014ca6a7a2008c9d280573R608> - also with `knex.raw`
29,870,713
I'm trying to generate a query like the following via Knex.js: ```sql INSERT INTO table ("column1", "column2") SELECT "someVal", 12345 WHERE NOT EXISTS ( SELECT 1 FROM table WHERE "column2" = 12345 ) ``` Basically, I want to insert values only if a particular value does not already exist. But Knex.js doesn't seem to know how to do this; if I call `knex.insert()` (with no values), it generates an "insert default values" query. I tried the following: ```js pg.insert() .into(tableName) .select(_.values(data)) .whereNotExists( pg.select(1) .from(tableName) .where(blah) ); ``` but that still just gives me the default values thing. I tried adding a `.columns(Object.keys(data))` in hopes that `insert()` would honor that, but no luck. Is it possible to generate the query I want with knex, or will I just have to build up a raw query, without Knex.js methods?
2015/04/25
[ "https://Stackoverflow.com/questions/29870713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324399/" ]
I believe the select needs to be passed into the insert: ``` pg.insert(knex.select().from("tableNameToSelectDataFrom")).into("tableToInsertInto"); ``` Also in order to select constant values or expressions you'll need to use a knex.raw expression in the select: ``` knex.select(knex.raw("'someVal',12345")).from("tableName") ``` This is my first post and I didn't test your specific example but I've done similar things like what you're asking using the above techniques.
I've managed to make it work in my project and it doesn't look all that bad! ```js .knex .into(knex.raw('USER_ROLES (ORG_ID, USER_ID, ROLE_ID, ROLE_SOURCE, ROLE_COMPETENCE_ID)')) .insert(builder => { builder .select([ 1, 'CU.USER_ID', 'CR.ROLE_ID', knex.raw(`'${ROLES.SOURCE_COMPETENCE}'`), competenceId, ]) .from('COMPETENCE_USERS as CU') .innerJoin('COMPETENCE_ROLES as CR', 'CU.COMPETENCE_ID', 'CR.COMPETENCE_ID') .where('CU.COMPETENCE_ID', competenceId) .where('CR.COMPETENCE_ID', competenceId); ``` Note that this doesn't seem to work properly with the [returning](https://knexjs.org/#Builder-returning) clause on MSSQL (it's just being ignored by Knex) at the moment.
29,870,713
I'm trying to generate a query like the following via Knex.js: ```sql INSERT INTO table ("column1", "column2") SELECT "someVal", 12345 WHERE NOT EXISTS ( SELECT 1 FROM table WHERE "column2" = 12345 ) ``` Basically, I want to insert values only if a particular value does not already exist. But Knex.js doesn't seem to know how to do this; if I call `knex.insert()` (with no values), it generates an "insert default values" query. I tried the following: ```js pg.insert() .into(tableName) .select(_.values(data)) .whereNotExists( pg.select(1) .from(tableName) .where(blah) ); ``` but that still just gives me the default values thing. I tried adding a `.columns(Object.keys(data))` in hopes that `insert()` would honor that, but no luck. Is it possible to generate the query I want with knex, or will I just have to build up a raw query, without Knex.js methods?
2015/04/25
[ "https://Stackoverflow.com/questions/29870713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324399/" ]
The most comprehensive answer I've found (with explicit column names for `INSERT`, and custom values in the `SELECT`-statement) is here: <https://github.com/knex/knex/issues/1056#issuecomment-156535234> by [Chris Broome](https://github.com/chrisbroome) here is a copy of that solution: ```js const query = knex // this part generates this part of the // query: INSERT "tablename" ("field1", "field2" ..) .into(knex.raw('?? (??, ??)', ['tableOrders', 'field_user_id', 'email_field'])) // and here is the second part of the SQL with "SELECT" .insert(function() { this .select( 'user_id', // select from column without alias knex.raw('? AS ??', ['jdoe@gmail.com', 'email']), // select static value with alias ) .from('users AS u') .where('u.username', 'jdoe') }); console.log(query.toString()); ``` and the SQL-output: ```sql insert into "orders" ("user_id", "email") select "user_id", 'jdoe@gmail.com' AS "email" from "users" as "u" where "u"."username" = 'jdoe' ``` --- another one approach (by Knex developer): <https://github.com/knex/knex/commit/e74f43cfe57ab27b02250948f8706d16c5d821b8#diff-cb48f4af7c014ca6a7a2008c9d280573R608> - also with `knex.raw`
I've managed to make it work in my project and it doesn't look all that bad! ```js .knex .into(knex.raw('USER_ROLES (ORG_ID, USER_ID, ROLE_ID, ROLE_SOURCE, ROLE_COMPETENCE_ID)')) .insert(builder => { builder .select([ 1, 'CU.USER_ID', 'CR.ROLE_ID', knex.raw(`'${ROLES.SOURCE_COMPETENCE}'`), competenceId, ]) .from('COMPETENCE_USERS as CU') .innerJoin('COMPETENCE_ROLES as CR', 'CU.COMPETENCE_ID', 'CR.COMPETENCE_ID') .where('CU.COMPETENCE_ID', competenceId) .where('CR.COMPETENCE_ID', competenceId); ``` Note that this doesn't seem to work properly with the [returning](https://knexjs.org/#Builder-returning) clause on MSSQL (it's just being ignored by Knex) at the moment.
9,977,839
I am running a simple code of MapReduce and am getting the following error: ``` `Exception in thread "main" java.io.IOException: Error opening job jar: Test.jar at org.apache.hadoop.util.RunJar.main(RunJar.java:90) Caused by: java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:114) at java.util.jar.JarFile.<init>(JarFile.java:133) at java.util.jar.JarFile.<init>(JarFile.java:70) at org.apache.hadoop.util.RunJar.main(RunJar.java:88)` ``` Some details of the problem: My hadoop version is 0.20. I have set `new JobConf(Statecount.class)` where `Statecount.class` is the class from which I am running this job. What do I have to do to resolve this error? Can anyone help me? Thanks.
2012/04/02
[ "https://Stackoverflow.com/questions/9977839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1307738/" ]
An approach I’m using for this is to generate the thumbnail PNG on the fly via the `thumb` method from Dragonfly’s ImageMagick plugin: ``` <%= image_tag rails_model.file.thumb('100x100#', format: 'png', frame: 0).url %> ``` So long as Ghostscript is installed, ImageMagick/Dragonfly will honour the format / frame (i.e. page of the PDF) settings. If `file` is an image rather than a PDF, it will be converted to a PNG, and the frame number ignored (unless it’s a GIF).
Try this ``` def to_pdf_thumbnail(temp_object) ret = '' tempfile = new_tempfile('png') system("convert",tmp_object.path[0],tmpfile.path) tempfile.open {|f| ret = f.read } ret end ``` The problem is you are likely handing convert ONE argument not two
9,977,839
I am running a simple code of MapReduce and am getting the following error: ``` `Exception in thread "main" java.io.IOException: Error opening job jar: Test.jar at org.apache.hadoop.util.RunJar.main(RunJar.java:90) Caused by: java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:114) at java.util.jar.JarFile.<init>(JarFile.java:133) at java.util.jar.JarFile.<init>(JarFile.java:70) at org.apache.hadoop.util.RunJar.main(RunJar.java:88)` ``` Some details of the problem: My hadoop version is 0.20. I have set `new JobConf(Statecount.class)` where `Statecount.class` is the class from which I am running this job. What do I have to do to resolve this error? Can anyone help me? Thanks.
2012/04/02
[ "https://Stackoverflow.com/questions/9977839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1307738/" ]
An approach I’m using for this is to generate the thumbnail PNG on the fly via the `thumb` method from Dragonfly’s ImageMagick plugin: ``` <%= image_tag rails_model.file.thumb('100x100#', format: 'png', frame: 0).url %> ``` So long as Ghostscript is installed, ImageMagick/Dragonfly will honour the format / frame (i.e. page of the PDF) settings. If `file` is an image rather than a PDF, it will be converted to a PNG, and the frame number ignored (unless it’s a GIF).
Doesn't convert rely on the extension to determine the type? Are you sure the tempfiles have the proper extensions?
30,484,265
I'm trying to write a Python library to parse our version format strings. The (simplified) version string format is as follows: `<product>-<x>.<y>.<z>[-alpha|beta|rc[.<n>]][.<extra>]][.centos|redhat|win][.snb|ivb]` This is: * product, ie `foo` * numeric version, ie: `0.1.0` * [optional] pre-release info, ie: `beta`, `rc.1`, `alpha.extrainfo` * [optional] operating system, ie: `centos` * [optional] platform, ie: `snb`, `ivb` So the following are valid version strings: ``` 1) foo-1.2.3 2) foo-2.3.4-alpha 3) foo-3.4.5-rc.2 4) foo-4.5.6-rc.2.extra 5) withos-5.6.7.centos 6) osandextra-7.8.9-rc.extra.redhat 7) all-4.4.4-rc.1.extra.centos.ivb ``` For all of those examples, the following regex works fine: ``` ^(?P<prod>\w+)-(?P<maj>\d).(?P<min>\d).(?P<bug>\d)(?:-(?P<pre>alpha|beta|rc)(?:\.(?P<pre_n>\d))?(?:\.(?P<pre_x>\w+))?)?(?:\.(?P<os>centos|redhat|win))?(?:\.(?P<plat>snb|ivb))?$ ``` But the problem comes in versions of this type (no 'extra' pre-release information, but with os and/or platform): ``` 8) issue-0.1.0-beta.redhat.snb ``` With the above regex, for string #8, `redhat` is being picked up in the pre-release extra info `pre_x`, instead of the `os` group. I tried using look-behind to avoid picking the os or platform strings in `pre_x`: ``` ...(?:\.(?P<pre_x>\w+))?(?<!centos|redhat|win|ivb|snb))... ``` That is: ``` ^(?P<prod>\w+)-(?P<maj>\d).(?P<min>\d).(?P<bug>\d)(?:-(?P<pre>alpha|beta|rc)(?:\.(?P<pre_n>\d))?(?:\.(?P<pre_x>\w+))?(?<!centos|redhat|win|ivb|snb))?(?:\.(?P<os>centos|redhat|win))?(?:\.(?P<plat>snb|ivb))?$ ``` This would work fine if Python's standard module [`re`](https://docs.python.org/2/library/re.html) could accept variable width look behind. I would rather try to stick to the standard module, rather than using [regex](https://pypi.python.org/pypi/regex) as my library is quite likely to be distributed to a large number machines, where I want to limit dependencies. I've also had a look at similar questions: [this](https://stackoverflow.com/questions/2613237/python-regex-look-behind-requires-fixed-width-pattern), [this](https://stackoverflow.com/questions/20089922/python-regex-engine-look-behind-requires-fixed-width-pattern-error) and [this](https://stackoverflow.com/questions/8194470/python-regex-with-look-behind-and-alternatives) are not aplicable. Any ideas on how to achieve this? My regex101 link: <https://regex101.com/r/bH0qI7/3> [For those interested, this is the full regex I'm actually using: <https://regex101.com/r/lX7nI6/2]>
2015/05/27
[ "https://Stackoverflow.com/questions/30484265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/794401/" ]
You need to use negative lookahead assertion to make `(?P<pre_x>\w+)` to match any except for `centos` or `redhat`. ``` ^(?P<prod>\w+)-(?P<maj>\d)\.(?P<min>\d)\.(?P<bug>\d)(?:-(?P<pre>alpha|beta|rc)(?:\.(?P<pre_n>\d))?(?:\.(?:(?!centos|redhat)\w)+)?)?(?:\.(?P<os>centos|redhat))?(?:\.(?P<plat>snb|ivb))?$ ``` [DEMO](https://regex101.com/r/bH0qI7/4)
Actually I'd avoid using the regex, since it looks pretty horrible already, and you told us it's only simplified. It's much more readable to parse it by hand: ``` def extract(text): parts = text.split('-') ret = {} ret['name'] = parts.pop(0) ret['version'] = parts.pop(0).split('.') if len(parts) > 0: rest_parts = parts.pop(0).split('.') if rest_parts[-1] in ['snb', 'ivb']: ret['platform'] = rest_parts.pop(-1) if rest_parts[-1] in ['redhat', 'centos', 'win']: ret['os'] = rest_parts.pop(-1) ret['extra'] = rest_parts return ret tests = \ [ 'foo-1.2.3', 'foo-2.3.4-alpha', 'foo-3.4.5-rc.2', 'foo-4.5.6-rc.2.extra', 'withos-5.6.7.centos', 'osandextra-7.8.9-rc.extra.redhat', 'all-4.4.4-rc.1.extra.centos.ivb', 'issue-0.1.0-beta.redhat.snb', ] for test in tests: print(test, extract(test)) ``` Result: ``` ('foo-1.2.3', {'version': ['1', '2', '3'], 'name': 'foo'}) ('foo-2.3.4-alpha', {'version': ['2', '3', '4'], 'name': 'foo', 'extra': ['alpha']}) ('foo-3.4.5-rc.2', {'version': ['3', '4', '5'], 'name': 'foo', 'extra': ['rc', '2']}) ('foo-4.5.6-rc.2.extra', {'version': ['4', '5', '6'], 'name': 'foo', 'extra': ['rc', '2', 'extra']}) ('withos-5.6.7.centos', {'version': ['5', '6', '7', 'centos'], 'name': 'withos'}) ('osandextra-7.8.9-rc.extra.redhat', {'version': ['7', '8', '9'], 'os': 'redhat', 'name': 'osandextra', 'extra': ['rc', 'extra']}) ('all-4.4.4-rc.1.extra.centos.ivb', {'platform': 'ivb', 'version': ['4', '4', '4'], 'os': 'centos', 'name': 'all', 'extra': ['rc', '1', 'extra']}) ('issue-0.1.0-beta.redhat.snb', {'platform': 'snb', 'version': ['0', '1', '0'], 'os': 'redhat', 'name': 'issue', 'extra': ['beta']}) ```
60,757,253
i am trying to add component shared between modules. Only thing i am getting is this error. I was searching for answer on similiar questions, but it did not help and i am constantly getting this error. Tried to declare it in app.module too, but it results with same error. Code: **Component** ``` import { Component, Input, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-action-button', templateUrl: './action-button.component.html', styleUrls: ['./action-button.component.scss'], }) export class ActionButtonComponent { private _className = ''; private _buttonText = ''; @Input() set className(className: string) { this._className = (className && className.trim() || 'default'); } get className(): string { return this._className; } @Input() set buttonText(buttonText: string) { this._buttonText = (buttonText && buttonText.trim() || 'n/n'); } get buttonText(): string { return this._buttonText; } @Output() buttonActionEvent = new EventEmitter(); constructor() { } buttonAction() { this.buttonActionEvent.emit(true); } } ``` **Module where i am declaring this component** ``` import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MaterialModule } from '../../material.module'; import { ActionButtonComponent } from '../../shared/action-button/action-button.component'; import { ActionButtonModule } from '../../shared/action-button/action-button.module'; import { LoginComponent } from './login.component'; import { LoginService } from './login.service'; @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule, ActionButtonModule], declarations: [LoginComponent], entryComponents: [ActionButtonComponent], providers: [LoginService] }) export class LoginModule {} ``` **html template** ``` <div class="login-wrapper"> <ng-container *ngIf="isLoading"> <mat-spinner class="loading" diameter="32"></mat-spinner> </ng-container> <ng-container *ngIf="!isLoading"> <h2>Zaloguj się za pomocą czytnika</h2> <form [formGroup]="operator"> <mat-form-field appearance="outline"> <mat-label>ID Operatora *</mat-label> <input type="text" matInput placeholder="Zeskanuj kod kreskowy" formControlName="id"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Wybór maszyny *</mat-label> <mat-select formControlName="machine"> <mat-option *ngFor="let machine of machinesList" [value]="machine.externalId"> {{ machine.name }} </mat-option> </mat-select> </mat-form-field> </form> <!-- <div class="buttons-wrapper"> <button (click)="getUrl()" mat-raised-button>maszyna Bullmer</button> <button mat-raised-button color="primary">maszyna nieBullmer</button> </div> --> <app-action-button [className]="logout-button" (buttonActionEvent)="test()"></app-action-button> <button [disabled]="!operator.valid" (click)="loginAndSetMachine()" mat-raised-button> <mat-icon color="primary" fontSet="fas" fontIcon="fa-check" class="material-icons"></mat-icon> </button> </ng-container> </div> ``` @Edit I made ActionButton module and imported it in LoginModule. Still getting same error. **ActionButton module** ``` import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MaterialModule } from '../../material.module'; import { ActionButtonComponent } from './action-button.component'; @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule], declarations: [ActionButtonComponent], exports : [ActionButtonComponent], entryComponents: [], providers: [] }) export class ActionButtonModule {} ```
2020/03/19
[ "https://Stackoverflow.com/questions/60757253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11172846/" ]
If you want to share it between modules, you have to add it to the exports of the module where you declare it and import that module to the module where you want to use your `ActionButtonComponent`. ``` @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule], declarations: [LoginComponent, ActionButtonComponent], entryComponents: [], providers: [LoginService], exports:[ActionButtonComponent] }) export class LoginModule {} ``` Your other module: ------------------ ``` @NgModule({ imports: [...,LoginModule], declarations: [], exports:[] }) export class OtherModule {} ``` Now you can use `ActionButtonComponent` in any component which is declared in `OtherModule`
Problem was in other template file i tried to use this component declaration...
60,757,253
i am trying to add component shared between modules. Only thing i am getting is this error. I was searching for answer on similiar questions, but it did not help and i am constantly getting this error. Tried to declare it in app.module too, but it results with same error. Code: **Component** ``` import { Component, Input, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-action-button', templateUrl: './action-button.component.html', styleUrls: ['./action-button.component.scss'], }) export class ActionButtonComponent { private _className = ''; private _buttonText = ''; @Input() set className(className: string) { this._className = (className && className.trim() || 'default'); } get className(): string { return this._className; } @Input() set buttonText(buttonText: string) { this._buttonText = (buttonText && buttonText.trim() || 'n/n'); } get buttonText(): string { return this._buttonText; } @Output() buttonActionEvent = new EventEmitter(); constructor() { } buttonAction() { this.buttonActionEvent.emit(true); } } ``` **Module where i am declaring this component** ``` import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MaterialModule } from '../../material.module'; import { ActionButtonComponent } from '../../shared/action-button/action-button.component'; import { ActionButtonModule } from '../../shared/action-button/action-button.module'; import { LoginComponent } from './login.component'; import { LoginService } from './login.service'; @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule, ActionButtonModule], declarations: [LoginComponent], entryComponents: [ActionButtonComponent], providers: [LoginService] }) export class LoginModule {} ``` **html template** ``` <div class="login-wrapper"> <ng-container *ngIf="isLoading"> <mat-spinner class="loading" diameter="32"></mat-spinner> </ng-container> <ng-container *ngIf="!isLoading"> <h2>Zaloguj się za pomocą czytnika</h2> <form [formGroup]="operator"> <mat-form-field appearance="outline"> <mat-label>ID Operatora *</mat-label> <input type="text" matInput placeholder="Zeskanuj kod kreskowy" formControlName="id"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Wybór maszyny *</mat-label> <mat-select formControlName="machine"> <mat-option *ngFor="let machine of machinesList" [value]="machine.externalId"> {{ machine.name }} </mat-option> </mat-select> </mat-form-field> </form> <!-- <div class="buttons-wrapper"> <button (click)="getUrl()" mat-raised-button>maszyna Bullmer</button> <button mat-raised-button color="primary">maszyna nieBullmer</button> </div> --> <app-action-button [className]="logout-button" (buttonActionEvent)="test()"></app-action-button> <button [disabled]="!operator.valid" (click)="loginAndSetMachine()" mat-raised-button> <mat-icon color="primary" fontSet="fas" fontIcon="fa-check" class="material-icons"></mat-icon> </button> </ng-container> </div> ``` @Edit I made ActionButton module and imported it in LoginModule. Still getting same error. **ActionButton module** ``` import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MaterialModule } from '../../material.module'; import { ActionButtonComponent } from './action-button.component'; @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule], declarations: [ActionButtonComponent], exports : [ActionButtonComponent], entryComponents: [], providers: [] }) export class ActionButtonModule {} ```
2020/03/19
[ "https://Stackoverflow.com/questions/60757253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11172846/" ]
You need to make sure that `ActionButtonComponent` is exported by it's module. After exporting, you can import this `LoginModule` anywhere and use the component: ``` @NgModule({ imports: [CommonModule, FormsModule, ReactiveFormsModule, MaterialModule], declarations: [LoginComponent, ActionButtonComponent], exports: [ActionButtonComponent], // This exports the shared component entryComponents: [], providers: [LoginService] }) export class LoginModule {} ```
Problem was in other template file i tried to use this component declaration...
63,008,593
I have recently taken over running a Logstash system which runs on debian 9. The previous owner had installed an older version of Logstash and has left incomplete documentation on the project. I have successfully configured Logstash 7.2 locally on windows 10 and have tried to transfer this across to the Debian system replacing the necessary paths etc. I'm comming up against the following error and despite hours searching for a clue I'm left scratching my head. Any pointers would be appreciated! ``` WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.headius.backport9.modules.Modules (file:/home/user/logstash/logstash-7.2.0/logstash-core/lib/jars/jruby-complete-9.2.7.0.jar) to field java.io.FileDescriptor.fd WARNING: Please consider reporting this to the maintainers of com.headius.backport9.modules.Modules WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release Thread.exclusive is deprecated, use Thread::Mutex Sending Logstash logs to /home/user/logstash/logstash-7.2.0/ which is now configured via log4j2.properties [2020-07-21T08:04:35,773][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified [2020-07-21T08:04:35,781][INFO ][logstash.runner ] Starting Logstash {"logstash.version"=>"7.2.0"} [2020-07-21T08:04:37,165][INFO ][logstash.outputs.jdbc ] JDBC - Starting up [2020-07-21T08:04:37,195][INFO ][com.zaxxer.hikari.HikariDataSource] HikariPool-1 - Starting... [2020-07-21T08:04:45,302][INFO ][com.zaxxer.hikari.HikariDataSource] HikariPool-1 - Start completed. [2020-07-21T08:04:45,404][ERROR][logstash.javapipeline ] Pipeline aborted due to error {:pipeline_id=>"main", :exception=>#<ArgumentError: invalid byte sequence in UTF-8>, :backtrace=>["org/jruby/RubyRegexp.java:1113:in `=~'", "org/jruby/RubyString.java:1664:in `=~'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/jls-grok-0.11.5/lib/grok-pure.rb:72:in `block in add_patterns_from_file'", "org/jruby/RubyIO.java:3329:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/jls-grok-0.11.5/lib/grok-pure.rb:70:in `add_patterns_from_file'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:403:in `block in add_patterns_from_files'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:399:in `add_patterns_from_files'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:279:in `block in register'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:275:in `block in register'", "org/jruby/RubyHash.java:1419:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:270:in `register'", "org/logstash/config/ir/compiler/AbstractFilterDelegatorExt.java:56:in `register'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:192:in `block in register_plugins'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:191:in `register_plugins'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:463:in `maybe_setup_out_plugins'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:204:in `start_workers'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:146:in `run'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:105:in `block in start'"], :thread=>"#<Thread:0x1bda40f7 run>"} [2020-07-21T08:04:45,422][ERROR][logstash.agent ] Failed to execute action {:id=>:main, :action_type=>LogStash::ConvergeResult::FailedAction, :message=>"Could not execute action: PipelineAction::Create<main>, action_result: false", :backtrace=>nil} [2020-07-21T08:04:45,553][INFO ][logstash.agent ] Successfully started Logstash API endpoint {:port=>9600} [2020-07-21T08:04:50,602][INFO ][logstash.runner ] Logstash shut down. ```
2020/07/21
[ "https://Stackoverflow.com/questions/63008593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018566/" ]
CV qualifier is left-associative, `const T` is the same as `T const`. For example 1. `const T *p` = `T const *p`, so `p` is *mutable*, but `*p` is *immutable* 2. `T * const p`, `p` is *immutable*, while `*p` is *mutable* 3. `T const * const p`, both `p` and `*p` are *immutable*
this here: `const int *ptr` is a `pointer to const value` meaning you can not change the value of the variable the pointer is pointing to... ``` const int value = 5; const int* ptr = &value; *ptr = 0; //<-- this is invalid ``` now, this here: `int *const ptr` is a `const pointer` meaning the address value hold by the pointer can not be changed ``` int value1 = 0; int value2 = 1; int* const ptr = &value1; ptr = &value2; // <-- this is invalid ```
63,008,593
I have recently taken over running a Logstash system which runs on debian 9. The previous owner had installed an older version of Logstash and has left incomplete documentation on the project. I have successfully configured Logstash 7.2 locally on windows 10 and have tried to transfer this across to the Debian system replacing the necessary paths etc. I'm comming up against the following error and despite hours searching for a clue I'm left scratching my head. Any pointers would be appreciated! ``` WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.headius.backport9.modules.Modules (file:/home/user/logstash/logstash-7.2.0/logstash-core/lib/jars/jruby-complete-9.2.7.0.jar) to field java.io.FileDescriptor.fd WARNING: Please consider reporting this to the maintainers of com.headius.backport9.modules.Modules WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release Thread.exclusive is deprecated, use Thread::Mutex Sending Logstash logs to /home/user/logstash/logstash-7.2.0/ which is now configured via log4j2.properties [2020-07-21T08:04:35,773][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified [2020-07-21T08:04:35,781][INFO ][logstash.runner ] Starting Logstash {"logstash.version"=>"7.2.0"} [2020-07-21T08:04:37,165][INFO ][logstash.outputs.jdbc ] JDBC - Starting up [2020-07-21T08:04:37,195][INFO ][com.zaxxer.hikari.HikariDataSource] HikariPool-1 - Starting... [2020-07-21T08:04:45,302][INFO ][com.zaxxer.hikari.HikariDataSource] HikariPool-1 - Start completed. [2020-07-21T08:04:45,404][ERROR][logstash.javapipeline ] Pipeline aborted due to error {:pipeline_id=>"main", :exception=>#<ArgumentError: invalid byte sequence in UTF-8>, :backtrace=>["org/jruby/RubyRegexp.java:1113:in `=~'", "org/jruby/RubyString.java:1664:in `=~'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/jls-grok-0.11.5/lib/grok-pure.rb:72:in `block in add_patterns_from_file'", "org/jruby/RubyIO.java:3329:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/jls-grok-0.11.5/lib/grok-pure.rb:70:in `add_patterns_from_file'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:403:in `block in add_patterns_from_files'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:399:in `add_patterns_from_files'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:279:in `block in register'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:275:in `block in register'", "org/jruby/RubyHash.java:1419:in `each'", "/home/user/logstash/logstash-7.2.0/vendor/bundle/jruby/2.5.0/gems/logstash-filter-grok-4.0.4/lib/logstash/filters/grok.rb:270:in `register'", "org/logstash/config/ir/compiler/AbstractFilterDelegatorExt.java:56:in `register'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:192:in `block in register_plugins'", "org/jruby/RubyArray.java:1792:in `each'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:191:in `register_plugins'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:463:in `maybe_setup_out_plugins'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:204:in `start_workers'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:146:in `run'", "/home/user/logstash/logstash-7.2.0/logstash-core/lib/logstash/java_pipeline.rb:105:in `block in start'"], :thread=>"#<Thread:0x1bda40f7 run>"} [2020-07-21T08:04:45,422][ERROR][logstash.agent ] Failed to execute action {:id=>:main, :action_type=>LogStash::ConvergeResult::FailedAction, :message=>"Could not execute action: PipelineAction::Create<main>, action_result: false", :backtrace=>nil} [2020-07-21T08:04:45,553][INFO ][logstash.agent ] Successfully started Logstash API endpoint {:port=>9600} [2020-07-21T08:04:50,602][INFO ][logstash.runner ] Logstash shut down. ```
2020/07/21
[ "https://Stackoverflow.com/questions/63008593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018566/" ]
There are 3 different cases in related to pointer and const: 1)pointer to const value: This is a pointer to point to a const value and should put const keyword before type. For example: ``` const int var = 7; const int *ptr = &var; ``` 2)const pointer: This type of pointer just initialize in declaration and can not modify. To declare should put const keyword between \* and name of pointer. for example: ``` int var = 7; int *const ptr = &var; ``` 3)const pointer to const value: This type of pointer is const pointer to point to const value. To declare should put const keyword before type and after \*. For example: ``` int var = 5; const int *const ptr = &var; ```
this here: `const int *ptr` is a `pointer to const value` meaning you can not change the value of the variable the pointer is pointing to... ``` const int value = 5; const int* ptr = &value; *ptr = 0; //<-- this is invalid ``` now, this here: `int *const ptr` is a `const pointer` meaning the address value hold by the pointer can not be changed ``` int value1 = 0; int value2 = 1; int* const ptr = &value1; ptr = &value2; // <-- this is invalid ```
37,340,189
Why can't I match values in between dashes? For example: 2016-05-20, when I tried to match number five using like function it will give no result even 05 but if I will match 2016 and 20 it will have a result. How do I match month in dates?? ``` public IEnumerable<NCABal> FindByNCABalDate(Int32 Month) { var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE NCABalDate LIKE '%"+ @Month +"%'"; return this._db.Query<NCABal>(query).ToList(); } ``` When I enter 5 or 05, no results will display.
2016/05/20
[ "https://Stackoverflow.com/questions/37340189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5881482/" ]
Use `Convert(nvarchar(20),NCABalDate, 20) LIKE '%"+ @Month +"%'` This will convert your datetime column to nvarchar, on which like will work fine. So, your query will become `var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Convert(nvarchar(20),NCABalDate, 20) LIKE '%"+ @Month +"%'";`
The value for month will go in as one character for values < 10 as you're not formatting it to be two characters. Try: ``` var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE NCABalDate LIKE '%"+ Month.ToString("D2") +"%'"; ```
37,340,189
Why can't I match values in between dashes? For example: 2016-05-20, when I tried to match number five using like function it will give no result even 05 but if I will match 2016 and 20 it will have a result. How do I match month in dates?? ``` public IEnumerable<NCABal> FindByNCABalDate(Int32 Month) { var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE NCABalDate LIKE '%"+ @Month +"%'"; return this._db.Query<NCABal>(query).ToList(); } ``` When I enter 5 or 05, no results will display.
2016/05/20
[ "https://Stackoverflow.com/questions/37340189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5881482/" ]
``` //for searching month var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(mm,NCABalDate) = 5"; //for searching year var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(yyyy,NCABalDate) = 2016"; //for searching day var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(dd,NCABalDate) = 20"; //for searching month,year and day var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(mm,NCABalDate) = 5 and Datepart(yyyy,NCABalDate) = 2016 and Datepart(dd,NCABalDate) = 20"; ```
The value for month will go in as one character for values < 10 as you're not formatting it to be two characters. Try: ``` var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE NCABalDate LIKE '%"+ Month.ToString("D2") +"%'"; ```
37,340,189
Why can't I match values in between dashes? For example: 2016-05-20, when I tried to match number five using like function it will give no result even 05 but if I will match 2016 and 20 it will have a result. How do I match month in dates?? ``` public IEnumerable<NCABal> FindByNCABalDate(Int32 Month) { var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE NCABalDate LIKE '%"+ @Month +"%'"; return this._db.Query<NCABal>(query).ToList(); } ``` When I enter 5 or 05, no results will display.
2016/05/20
[ "https://Stackoverflow.com/questions/37340189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5881482/" ]
``` //for searching month var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(mm,NCABalDate) = 5"; //for searching year var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(yyyy,NCABalDate) = 2016"; //for searching day var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(dd,NCABalDate) = 20"; //for searching month,year and day var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Datepart(mm,NCABalDate) = 5 and Datepart(yyyy,NCABalDate) = 2016 and Datepart(dd,NCABalDate) = 20"; ```
Use `Convert(nvarchar(20),NCABalDate, 20) LIKE '%"+ @Month +"%'` This will convert your datetime column to nvarchar, on which like will work fine. So, your query will become `var query = @"SELECT * FROM [dbo].[NCA_Balance] WHERE Convert(nvarchar(20),NCABalDate, 20) LIKE '%"+ @Month +"%'";`
9,426,346
I want to close total application in android when i click on "NO" Button in Dialog. i have used the following code. ``` protected Dialog onCreateDialog(int id) { switch (id) { case 0: AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("GASIMIZER"); builder1.setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent i = new Intent(Finalpage.this,NewproActivity.class); startActivity(i); } }) .setNegativeButton("NO",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { quit(); } }); AlertDialog alert1 = builder1.create(); alert1.show(); break; } return null; } public void quit() { onDestroy(); } ``` please any one tell me how can i solve this problem.
2012/02/24
[ "https://Stackoverflow.com/questions/9426346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084935/" ]
You should **NOT** kill your applications. You should let the ActivityManager handle that. Specifically if you want the user to leave your application, then send them home via an Intent to the homescreen.
You should't call `onDestroy()` yourself.. instead call `finish()` to close the Activity.. Calling Activity life cycle method by yourself is bad practice (Don't know if its possible). They are handled by Android OS itself..
9,426,346
I want to close total application in android when i click on "NO" Button in Dialog. i have used the following code. ``` protected Dialog onCreateDialog(int id) { switch (id) { case 0: AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("GASIMIZER"); builder1.setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent i = new Intent(Finalpage.this,NewproActivity.class); startActivity(i); } }) .setNegativeButton("NO",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { quit(); } }); AlertDialog alert1 = builder1.create(); alert1.show(); break; } return null; } public void quit() { onDestroy(); } ``` please any one tell me how can i solve this problem.
2012/02/24
[ "https://Stackoverflow.com/questions/9426346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084935/" ]
you can call the `finish()` method on your activity and call the homescreen (simulate the homebutton) programmatically like this: ``` private void endApplication() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } ```
You should't call `onDestroy()` yourself.. instead call `finish()` to close the Activity.. Calling Activity life cycle method by yourself is bad practice (Don't know if its possible). They are handled by Android OS itself..
9,426,346
I want to close total application in android when i click on "NO" Button in Dialog. i have used the following code. ``` protected Dialog onCreateDialog(int id) { switch (id) { case 0: AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("GASIMIZER"); builder1.setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent i = new Intent(Finalpage.this,NewproActivity.class); startActivity(i); } }) .setNegativeButton("NO",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { quit(); } }); AlertDialog alert1 = builder1.create(); alert1.show(); break; } return null; } public void quit() { onDestroy(); } ``` please any one tell me how can i solve this problem.
2012/02/24
[ "https://Stackoverflow.com/questions/9426346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084935/" ]
Let's do this a bit simply.Suppose you have a class `Constants.java` where you put all your reused constants of the application.In that declare an activity stack like this: ``` public static ArrayList<WeakReference<Activity>> activity_stack=new ArrayList<WeakReference<Activity>>(); /** * Add the activity as weak reference to activity stack. * @param act */ public static void addToActivityStack(Activity act) { WeakReference<Activity> ref = new WeakReference<Activity>(act); activity_stack.add(ref); } ``` And whenever you create some activity,in it's onCreate at the last line you put something like this: ``` Constants.addToActivityStack(this); ``` Now define a method like following in `Constants.java` ``` /** * Kill all the activities on activity stack except act. * To kill all the passed parameter should be null. */ public static void killAllExcept(Activity act) { for(WeakReference<Activity> ref:Global.activity_stack) { if(ref != null && ref.get() != null) { if(act != null && ref.get().equals(act)) { continue;//dont finish this up. } ref.get().finish(); } } activity_stack.clear();//but clear all the activity references } ``` Now,when you need to finish up all your activities,just call `Constants.killAllExcept(null)` or `Constants.killAllExcept(this)` if you want to keep this activity. This method is convenient when you want to keep one activity but the others/if you want you can finish them up all.
You should't call `onDestroy()` yourself.. instead call `finish()` to close the Activity.. Calling Activity life cycle method by yourself is bad practice (Don't know if its possible). They are handled by Android OS itself..
9,426,346
I want to close total application in android when i click on "NO" Button in Dialog. i have used the following code. ``` protected Dialog onCreateDialog(int id) { switch (id) { case 0: AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setTitle("GASIMIZER"); builder1.setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent i = new Intent(Finalpage.this,NewproActivity.class); startActivity(i); } }) .setNegativeButton("NO",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { quit(); } }); AlertDialog alert1 = builder1.create(); alert1.show(); break; } return null; } public void quit() { onDestroy(); } ``` please any one tell me how can i solve this problem.
2012/02/24
[ "https://Stackoverflow.com/questions/9426346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084935/" ]
you can call the `finish()` method on your activity and call the homescreen (simulate the homebutton) programmatically like this: ``` private void endApplication() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } ```
You should **NOT** kill your applications. You should let the ActivityManager handle that. Specifically if you want the user to leave your application, then send them home via an Intent to the homescreen.