text:
Q: Android SQLite query error "no such column" all.
I am working on one assignment with SQLite.
I really appreciate to help me.
The situation is very simple SQL query but does not work
public class TasksDBHelper extends SQLiteOpenHelper {

    private static final String LOGTAG = "Task Manager";

    public static final String DB_COL_TITLE = "title";
    public static String DB_COL_DESCRIPTION = "description";
    public static String DB_COL_DUEDATE = "duedate";
    public static String DB_COL_CATEGORY = "category";
    public static String DB_COL_PRIORITY = "priority";
    public static String DB_COL_BODY = "body";

    public static String DB_COL_ID = BaseColumns._ID; //same as setting to "_id"
    public static final String[] DB_ALL_COLUMNS = { DB_COL_ID, DB_COL_TITLE, DB_COL_DESCRIPTION, DB_COL_DUEDATE,
                                                    DB_COL_CATEGORY, DB_COL_PRIORITY};

    private static final String DB_NAME = "my_tasks.db";
    public  static final String DB_TABLE = "tasks";
    private static final int DB_VERSION = 1;

    private static final String DB_TABLE_CREATE =
            "CREATE TABLE tasks (" +
                    DB_COL_ID + " integer primary key autoincrement," +
                    DB_COL_TITLE + " text not null," +
                    DB_COL_DESCRIPTION + " text not null," +
                    DB_COL_DUEDATE + " text not null," +
                    DB_COL_CATEGORY + " text not null," +
                    DB_COL_PRIORITY + " text not null);";

    private static TasksDBHelper INSTANCE;
    public static TasksDBHelper getInstance(Context ctx){
        if (INSTANCE == null)
            INSTANCE = new TasksDBHelper(ctx.getApplicationContext());

        return INSTANCE;
    }

    private TasksDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(LOGTAG, "onCreate() of the SQLite Demo");
        db.execSQL(DB_TABLE_CREATE);
        Log.d(LOGTAG, "Notes DB table created");
        //Populate with some sample notes
        ContentValues cv = new ContentValues();
        for (int i = 0; i < 10; i++) {
            cv.put(DB_COL_TITLE, String.format("Title : %d", i));
            cv.put(DB_COL_DESCRIPTION, String.format("Body : %d", i));
            cv.put(DB_COL_DUEDATE, String.format("Body : %d", i));
            cv.put(DB_COL_CATEGORY, String.format("Body : %d", i));
            cv.put(DB_COL_PRIORITY, String.format("Body : %d", i));
            db.insert(DB_TABLE, null, cv);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
        onCreate(db);
    }

    /////CRUD Methods

    public Task createTask(Task task) {
        Log.d(LOGTAG, "Calling createNote()");

        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(TasksDBHelper.DB_COL_TITLE, task.getTitle());
        cv.put(TasksDBHelper.DB_COL_DESCRIPTION, task.getDescription());
        cv.put(TasksDBHelper.DB_COL_DUEDATE, task.getDuedate());
        cv.put(TasksDBHelper.DB_COL_CATEGORY, task.getCategory());
        cv.put(TasksDBHelper.DB_COL_PRIORITY, task.getPriority());

        long id =  db.insert(TasksDBHelper.DB_TABLE, null, cv);
        task.setId(id);
        Log.d(LOGTAG, "Task created : " + id);
        return task;
    }

    public int updateTask(Task task) {
        Log.d(LOGTAG, "Calling updateNote()");

        SQLiteDatabase notesDB = getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(TasksDBHelper.DB_COL_TITLE, task.getTitle());
        cv.put(TasksDBHelper.DB_COL_DESCRIPTION, task.getDescription());
        cv.put(TasksDBHelper.DB_COL_DUEDATE, task.getDuedate());
        cv.put(TasksDBHelper.DB_COL_CATEGORY, task.getCategory());
        cv.put(TasksDBHelper.DB_COL_PRIORITY, task.getPriority());
        return notesDB.update(TasksDBHelper.DB_TABLE, cv, TasksDBHelper.DB_COL_ID + "=" + task.getId(), null);
    }

    public ArrayList<Task> getTasks() {
        Log.d(LOGTAG, "Calling getTasks()");
        SQLiteDatabase notesDB = getReadableDatabase();
        Cursor c = null;
        ArrayList<Task> tasks = new ArrayList<Task>();

        try {
            //c = notesDB.query(TasksDBHelper.DB_TABLE, TasksDBHelper.DB_ALL_COLUMNS, null, null, null, null, null);
            String query = String.format("SELECT _id, %s, %s, %s, %s, %s FROM %s",
            TasksDBHelper.DB_COL_TITLE, TasksDBHelper.DB_COL_DESCRIPTION, TasksDBHelper.DB_COL_DUEDATE,
                     TasksDBHelper.DB_COL_CATEGORY, TasksDBHelper.DB_COL_PRIORITY, TasksDBHelper.DB_TABLE);

            c = notesDB.rawQuery(query, null);

            if ((c != null) && c.getCount() > 0 ) {
                while(c.moveToNext())
                    tasks.add(getNoteFromCursor(c));
            }
        }
        finally
        {
            if (c != null)
                c.close();
        }
        return tasks;
    }

    public Task getTask(long rowId) {
        Cursor c = null;
        Task task = null;
        Log.d(LOGTAG, "Calling getNote()");
        SQLiteDatabase tasksDB = getReadableDatabase();

        try {
            c = tasksDB.query(TasksDBHelper.DB_TABLE, new String[]
                            { TasksDBHelper.DB_COL_ID, TasksDBHelper.DB_COL_TITLE,
                                    TasksDBHelper.DB_COL_DESCRIPTION, TasksDBHelper.DB_COL_DUEDATE,
                                    TasksDBHelper.DB_COL_CATEGORY, TasksDBHelper.DB_COL_PRIORITY},
                    TasksDBHelper.DB_COL_ID + "=" + rowId, null, null, null, null);
            if (c != null)
                c.moveToFirst();
            task = getNoteFromCursor(c);
            return task;

        } catch (Exception e) {
            Log.e(LOGTAG, "Error on getNote()", e);
        }
        finally {
            if (c != null)
                c.close();
        }
        return task;

    }

    public boolean delete(long rowId) {
        SQLiteDatabase notesDB = getWritableDatabase();
        return notesDB.delete(TasksDBHelper.DB_TABLE, TasksDBHelper.DB_COL_ID + "=" + rowId, null) > 0;
    }

    private static Task getTaskFromCursor(Cursor c){
        if ((c == null) || (c.getCount() == 0))
            return null;
        else {
            Task task = new Task();
            task.setId(c.getLong(c.getColumnIndex(TasksDBHelper.DB_COL_ID)));
            task.setTitle(c.getString(c.getColumnIndex(TasksDBHelper.DB_COL_TITLE)));
            task.setdescription(c.getString(c.getColumnIndex(TasksDBHelper.DB_COL_DESCRIPTION)));
            task.setdescription(c.getString(c.getColumnIndex(TasksDBHelper.DB_COL_DUEDATE)));
            task.setdescription(c.getString(c.getColumnIndex(TasksDBHelper.DB_COL_CATEGORY)));
            task.setdescription(c.getString(c.getColumnIndex(TasksDBHelper.DB_COL_PRIORITY)));
            return task;
        }

    }
}

07-06 00:35:23.621 5558-5558/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.comp3617.assignment3.chiseongoh, PID: 5558
                                                   java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.comp3617.assignment3.chiseongoh/com.comp3617.assignment3.chiseongoh.DisplayTasksActivity}:
  android.database.sqlite.SQLiteException: no such column: title (code
  1): , while compiling: SELECT _id, title, description, duedate,
  category, priority FROM tasks
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                    Caused by: android.database.sqlite.SQLiteException: no such column: title (code
  1): , while compiling: SELECT _id, title, description, duedate,
  category, priority FROM tasks
                                                       at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                       at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                       at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                       at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                       at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                       at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                       at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                       at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                       at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                       at com.comp3617.assignment3.chiseongoh.db.TasksDBHelper.getTasks(TasksDBHelper.java:128)
                                                       at com.comp3617.assignment3.chiseongoh.DisplayTasksActivity.bindListViewToNotes(DisplayTasksActivity.java:76)
                                                       at com.comp3617.assignment3.chiseongoh.DisplayTasksActivity.onCreate(DisplayTasksActivity.java:71)
                                                       at android.app.Activity.performCreate(Activity.java:6237)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                       at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Errors at here
public Task getTask(long rowId) {
        Cursor c = null;
        Task task = null;
        Log.d(LOGTAG, "Calling getNote()");
        SQLiteDatabase tasksDB = getReadableDatabase();

        try {
            c = tasksDB.query(TasksDBHelper.DB_TABLE, new String[]
                            { TasksDBHelper.DB_COL_ID, TasksDBHelper.DB_COL_TITLE,
                                    TasksDBHelper.DB_COL_DESCRIPTION, TasksDBHelper.DB_COL_DUEDATE,
                                    TasksDBHelper.DB_COL_CATEGORY, TasksDBHelper.DB_COL_PRIORITY},
                    TasksDBHelper.DB_COL_ID + "=" + rowId, null, null, null, null);
            if (c != null)
                c.moveToFirst();
            task = getNoteFromCursor(c);
            return task;

        } catch (Exception e) {
            Log.e(LOGTAG, "Error on getNote()", e);
        }
        finally {
            if (c != null)
                c.close();
        }
        return task;

    }

Thank you!

A: You can change DB_VERSION or uninstall the old app on your device then reinstall. I thinks old database with no title column existed in that device.

A: Maybe you can run your code in emulator and then drag the db file out。Then open the file in "SQLite Expert"  to see whether or not that  you had created the table contains the column "title".


text:
Q: SQLCLR stored procedure gets "SecurityException: Request for the permission of type 'System.Data.OleDb.OleDbPermission" error I have created .NET SQLCLR stored procedure, and built and published it on my local SQL Server.
In the .NET code I am using this connection string:
OleDbConnection connection = new OleDbConnection(
      "provider=MSOLAP.7;data source=(local);initial catalog=AdventureWorksDW2014");

This .NET code contains a cube update query. Thus, the assembly needs to update the cube hosted on my local Analysis server.
When executing the SQLCLR stored procedure in SSMS I get the following error:

Msg 6522, Level 16, State 1, Procedure dbo.SqlStoredProcedure1, Line 0
[Batch Start Line 0] A .NET Framework error occurred during execution
  of user-defined routine or aggregate "SqlStoredProcedure1":
  System.Security.SecurityException: Request for the permission of type
  'System.Data.OleDb.OleDbPermission, System.Data, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
  System.Security.SecurityException:     at
  System.Security.CodeAccessSecurityEngine.Check(Object demand,
  StackCrawlMark& stackMark, Boolean isPermSet)    at
  System.Security.PermissionSet.Demand()    at
  System.Data.Common.DbConnectionOptions.DemandPermission()    at
  System.Data.OleDb.OleDbConnectionFactory.PermissionDemand(DbConnection
  outerConnection)    at
  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource`1 retry, DbConnectionOptions userOptions)    at
  System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory)    at
  System.Data.OleDb.OleDbConnection.Open()    at
  StoredProcedures.SqlStoredProcedure1()

For some reason, the OleDb connection isn't working from the assembly. But, when debugged from Visual studio, the code runs perfectly fine and updates the cube.
Please share with me the potential fixes to the above error.

A: You are getting a security permission error when trying to open the connection. The connection is external (i.e. not using the internal "context connection"), so the Assembly needs to have a PERMISSION_SET of at least EXTERNAL_ACCESS. But, in order to do that, you need to sign the Assembly (since you are using Visual Studio, this means giving it a strong name), create an Asymmetric Key in master from that strong name key, create a Login from that Asymmetric Key, and grant that Login the EXTERNAL ACCESS ASSEMBLY permission. Or, if you are using SQL Server 2017 (or newer), then that last step changes to be granting that Login the UNSAFE ASSEMBLY permission.
After doing those steps, then you can either create the Assembly WITH PERMISSION_SET = EXTERNAL_ACCESS, or ALTER ASSEMBLY [{assembly_name}] WITH PERMISSION_SET = EXTERNAL_ACCESS;
For detailed instructions, including how to automate this in Visual Studio, with the ability to have it work in SQL Server 2017 and beyond, and without relying upon external files beyond the T-SQL script, please see the following two posts of mine:

*

*SQLCLR vs. SQL Server 2017, Part 2: "CLR strict security" – Solution 1

*SQLCLR vs. SQL Server 2017, Part 3: "CLR strict security" – Solution 2
Solution 1 describes how to accomplish this assuming you want to stay fully within the strong name key / Asymmetric Key framework used by Visual Studio. Solution 2 describes a less complicated approach using only Certificates.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Worker Role and Nunit I have some Azure worker roles that I'd like to unit test.
I choose NUnit for this and I have Resharper on my VS2013
Everytime I debug the tests it seem to initialise stuff and then it stops. I never go to the debug mode.
Looking at the output window I find this:
    Microsoft.WindowsAzure.ServiceRuntime Information: 100 : Role environment . INITIALIZING
Microsoft.WindowsAzure.ServiceRuntime Information: 100 : Role environment . INITIALED RETURNED. HResult=-2147024894
Microsoft.WindowsAzure.ServiceRuntime Error: 102 : Role environment . FAILED TO INITIALIZE. hr: -2147024894

Not sure if this is the problem but I'm kinda stuck here...
Any clue?

A: -2147024894 is file not found. All files available? Use procmon to see which files are being read and which ones are not being found.


text:
Q: Acess JSF resource library from JS without ?ln=xxx There is a very good article on JSF resource libraries: What is the JSF resource library for and how should it be used?
I'm implementing a simple JSF wrapper for a existing JS library. This library is referencing some images and provide a function setImagePath:
setImagePath("/test/javax.faces.resource/img/");

This is a first step to access the JSF resource library. Obviously I need a suffix like
.jsf?ln=xxx

to access the resource library. Unfortunately the JS library does not provide a setImageSuffix. If I modify the JS library and add this suffix manually to all images it works, but that's not a ideal solution.
Is there any to access my xxx resource library with setImagePath only?

A: I've had a similar problem.  To do so you would have to extend your ResourceHandler to map your resources.
Fortunately, this was done after asking my question and added to OmniFaces.  So there is no real need for you to do so again.
By implementing an UnmappedResourceHandler you will then be able to map your resources without the appended suffix.
You will then be able to map your resources(images) in such a fashion :
setImagePath("/test/img/");

Links

*

*UnmappedresourceHandler

*Original Question
Thanks goes to BalusC and OmniFaces


text:
Q: Blazor - How do you customize InputNumber validation message for values that exceed max for that data type? For example, if I have an InputNumber with underlying datatype of int I want to display a message that says a number greater than int.MaxValue is not allowed. As it is currently if I were to try any number bigger than the max value for an integer I get a default message that says 'The field must be a number'. The message is not correct obviously and I want to change it. Is there a way to do that in blazor?

A: By adding ParsingErrorMessage attribute I was able to display the custom error message.
<InputNumber @bind-Value="anything.Age" class="form-control" ParsingErrorMessage="number out of range"></InputNumber>


text:
Q: Android set color of icon and text in bottomNavigationBar by program fails I create a xml file to control my bottomNavigation bar, like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:color="@color/bottomNavigationBarCheckedNormal" />

    <item
        android:state_pressed="true"
        android:color="@color/bottomNavigationBarCheckedNormal" />

    <item
        android:color="@color/bottomNavigationBarUncheckedNormal" />
</selector>

It is works when I set this in my activity xml file, like this:
<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/activity_news_bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    app:menu="@menu/bottom_navigation_menu"
    app:itemIconTint="@drawable/custom_bottom_navigation_normal"
    app:itemTextColor="@drawable/custom_bottom_navigation_normal"
    app:labelVisibilityMode="labeled" />

But I want to change this by program, so I try to use this:
bottomNavigationView.setBackgroundColor(Color.parseColor(AppColor.bottomNavigationBarBackgroundColor));
bottomNavigationView.setItemIconTintList(ColorStateList.valueOf(R.drawable.custom_bottom_navigation_normal));
bottomNavigationView.setItemTextColor(ColorStateList.valueOf(R.drawable.custom_bottom_navigation_normal));

But it is not work, icon and text color are not different when select and unselect, and the color is not I set. How can I fix it, thank you.

A: You should use:
bottomNavigationView.setItemTextColor(
      AppCompatResources.getColorStateList(this,R.drawable.custom_bottom_navigation_normal));

The method valueOf:

Returns A ColorStateList containing a single color. This value cannot be null.


text:
Q: Getting an error that says: found value, required variable in Java I am trying to create a computer generated Black Jack that shuffles 54 cards and displays them along with the score and if the person gets blackjack or not. I keep on getting this error and I have no idea why, if anyone can help, that would be great (:
import java.awt.GridLayout;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DisplayCards extends JFrame {
public DisplayCards() {
    int cardCount = 54;
    Random ran = new Random();
    setLayout(new GridLayout(1,4,5,5));

    //Generate 3 random numbers
    for(int i=0;i<3;i++){
      int imageId = ran.nextInt(cardCount)+1;
      int blackjack = 0,
            result = 0;
      add(new JLabel(new ImageIcon("image/card/"+imageId+".png")));

        switch (imageId)
        {
        case 1:
                blackjack = 1;

        case 2:
                blackjack = 2;

            case 3:
                blackjack = 3;

            case 4:
                blackjack = 4;

            case 5:
                blackjack = 5;

            case 6:
                blackjack = 6;

            case 7:
                blackjack = 7;

            case 8:
                blackjack = 8;

            case 9:
                blackjack = 9;

            case 10:
                blackjack = 10;

            case 11:
                blackjack = 10;

        case 12:
                blackjack = 10;

            case 13:
                blackjack = 10;

            case 14:
                blackjack = 1;

            case 15:
                blackjack = 2;

            case 16:
                blackjack = 3;

            case 17:
                blackjack = 4;

            case 18:
                blackjack = 5;

            case 19:
                blackjack = 6;

            case 20:
                blackjack = 7;

            case 21:
                blackjack = 8;

        case 22:
                blackjack = 9;

            case 23:
                blackjack = 10;

            case 24:
                blackjack = 10;

            case 25:
                blackjack = 10;

            case 26:
                blackjack = 10;

            case 27:
                blackjack = 1;

            case 28:
                blackjack = 2;

            case 29:
                blackjack = 3;

            case 30:
                blackjack = 4;

            case 31:
                blackjack = 5;

        case 32:
                blackjack = 6;

            case 33:
                blackjack = 7;

            case 34:
                blackjack = 8;

            case 35:
                blackjack = 9;

            case 36:
                blackjack = 10;

            case 37:
                blackjack = 10;

            case 38:
                blackjack = 10;

            case 39:
                blackjack = 10;

            case 40:
                blackjack = 1;

            case 41:
                blackjack = 2;

        case 42:
                blackjack = 3;

            case 43:
                blackjack = 4;

            case 44:
                blackjack = 5;

            case 45:
                blackjack = 6;

            case 46:
                blackjack = 7;

            case 47:
                blackjack = 8;

            case 48:
                blackjack = 9;

            case 49:
                blackjack = 10;

            case 50:
                blackjack = 10;

            case 51:
                blackjack = 10;

        case 52:
                blackjack = 10;

            case 53:
                blackjack = 0;

            case 54:
                blackjack = 0;

            blackjack + result = result; // error here
    }
}
    //add(new JLabel(result));
    //if (result == 21)
    add(new JLabel("Black Jack!"));
    //else if(result != 21)
    //add(new JLabel("Sorry, You do not have Black Jack."));

}
public static void main(String[] args) {
    DisplayCards frame = new DisplayCards();
    frame.setTitle("Black Jack!");
    frame.setSize(300, 170);
    frame.setDefaultCloseOperation(3);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
}

Error:
DisplayCards.java:196: error: unexpected type
            blackjack + result = result;
                      ^
 required: variable
 found:    value
 1 error

A: In Java, you should perform assignments like this:
result = blackjack + result;

Probably it should also a good idea for you to follow a basic tutorial on the language. Try this one.


text:
Q: How to get GPS location on application ported from android to BB10? My problem is i am not able to get network or GPS location when BB10 Device is in sleep mode.My device is Q10 Dev Alpha C i have done following testing.

*

*Added run_when_backgrounded permission

*left application running in background.

*logcat is showing its requesting for location update.

*but location is not coming when device is in sleep mode.

same problem has been reported here
permission added are using custom MANIFEST.MF
access_internet,access_shared,access_pimdomain_contacts,play_audio,post_notification,run_when_backgrounded,access_location_services


text:
Q: Minecraft: How to I detect if nothing is in an item frame? I want to know, if it's possible, how I would go about detecting if an item frame has nothing in it. I've looked online a lot and haven't found anything yet. I would say what I've got so far, but I don't really know where to start. I have

/testfor @e[type=item_frame] {TileX:4,TileY:101,TileZ:37,{id:}}

but I don't know where to go or what to do from here.

A: You can tag all item frames that have an item in them, then test if any don't have that tag:
/scoreboard players tag @e[type=item_frame] add HasItem {Item:{}}
/testfor @e[type=item_frame,tag=!HasItem]


text:
Q: Function Fill some field and Submit on Select <script type="text/javascript">

function FillCode(info) {
  var str = '';
  if (info != '') { str = info; }
  document.getElementById('coupon_code').value = str;
}

</script>

<div class="input-box">
<input class="input-text" type="hidden" id="coupon_code" name="coupon_code" value="<?php echo $this->htmlEscape($this->getCouponCode()) ?>" />
<select id="SBox" style="background-color: #666;" onchange="FillCode(value)">
      <option value="">Select Code</option>
      <option value="CODEDISCOUNT">X% Discount</option>
    </select>

I want to make this in a automatic send on select the X% Discount
  option on dropdown.

On select this fill the Coupon Code form, but i need to press the submit button to auto update the form.

A: Would it be acceptable to use jQuery to do this ?
If so, I have put up a working example here
Using jQuery this is what you would do :
$("#SBox").change(function() {
    //alert($(this).val());
    $("input#coupon_code").val($(this).val());
    $("form").submit();
});


text:
Q: How to activate VT-x on a Acer Aspire E1-571G? How to activate the hardware virtualization an this laptop if on the BIOS i don't have any options...It's very simplified ( the only tabs on the BIOs are those:

I searched and the processor supports VT-x ...

A: Download the official Microsoft virtualisation checker tool. This will confirm whether VT-x is enabled.
http://www.microsoft.com/en-us/download/details.aspx?id=592

A: Maybe your processor supports but its seems as far i can see your bios dont, look for the model of your  motherboard of your manufacter webpage and download the latest bios update.


text:
Q: Custom lookup field on rails 3 form So heres what I am trying to do:
I want a field that is text based, "a coupon code"
in a nested form.
So basically f.text_field :coupon
But that value should be a relationship to an item in a coupons table, but not by id.
Coupon table could look like
|ID| CouponCode |
+--+------------+
|1 | a89sd9asda |
+--+------------+

and my main table would look like
|ID| OrderTitle |   Coupon   |
+--+------------+------------+
|1 | sdfsdfsdfd | a89sd9asda |
+--+------------+------------+

Is there a way in rails to link these two via a has_one and use a non ID field?

A: To answer your question:
class Order < ActiveRecord::Base
   has_one :coupon_code, :foreign_key => 'CouponCode'
end

class CouponCode < ActiveRecord::Base
   belongs_to :order, :foreign_key => 'CouponCode'
end

However, I agree with damien: this looks a bit off of the common db design approaches.


text:
Q: Python string replace not working (bytes input expected?) I am trying to use Pyner (https://github.com/dat/pyner) for NER. I give it a string of text to extract named entities from it. But I get an error. I am attaching the snipet where the error arises:
for s in ('\f', '\n', '\r', '\t', '\v'): #strip whitespaces
    text = text.replace(s, '')

Error message: {TypeError: a bytes-like object is required, not 'str'}

This error occurs even when I try multiple types of inputs (bytes objects)
text = b'This'
text = bytes("This".encode('utf-8'))

I think the problem is that replace is not getting the right input type. I am using python 3.5. What am I doing wrong? Please help!

A: replace works with str or bytes but not both mixed.
You could rewrite it like this:
for s in (b'\f', b'\n', b'\r', b'\t', b'\v'): #strip whitespaces except space!
    text = text.replace(s, b'')

you could also to apply strip which works with bytes type:
text = text.strip()  # remove all of the above + space

Also possible: convert back to str beforehand, trying:
text = str(text)

or
text = text.decode('utf-8')

(choose the best solution to avoid modifying a third-party package, as Patrick noted)


text:
Q: Azure App Service Plan, incorrect load balancing when scaling in or out My Azure App Service Plan is behaving strangely when scaling in and out. The unconfigurable load balancer that I get with my plan seems to be redirecting traffic in an incorrect way. My plan hosts multiple C# .NET API's, with only one of them serving traffic in below screenshot. ARR affinity is turned off for all apps in the plan.
Sometimes when scaling down from 3 to 2 instances, all traffic suddenly goes to only one instance instead of the 2 that are still up and ready to serve request (causing CPU overload one no requests being served). The same can happen when scaling out from 2 to 3 instances, so only one of the currently 2 processing instances continue to process until the new third instance is up and running (causing CPU overload again). Please see picture for better exaplanation.
Looking at thread dumps it is waiting for System.Threading.Monitor.Wait with the call stack only being System.Threading stuff. So it isn't giving me much either.


text:
Q: How to do a broad-match search with TSQL FreeText search with numeric values? I am trying to do a free text search on terms like "sony model number np-fx110" or "carrying case for sony sz-vgn770N" or "asus laptop model g60v".
I know that freetext treats numbers like noise, so I figured I would edit out numbers from the noise SQL Server 2008 noiseENU.txt file but I'm unable to locate any noise files on my server.
The FTData directory only contains a bunch of 2kb xml files and an empty FilterData folder.
I've got a split Function that will return all words in a given string with a split character of a space.  I need a CTE that will concatenate the AND text for each word in returned from the SPLIT() function.
> SELECT *  FROM MyTable WHERE
> Description LIKE '%asus%'  AND
> Description LIKE '%laptop%'  AND
> Description LIKE '%model%'  AND
> Description LIKE '%g60v%'

Essentially the model number can be anywhere in the description field.  I can easily do a LIKE [model number], however I would want to match that up with other words contained in the description.
This doesn't seem like an optimal approach, but workable.  Any other suggestions on how to tackle this would be appreciated.
Thanks.
UPDATE
Here is the result of running "exec sp_help_fulltext_catalogs"
> ftcatid:5 NAME: CTIMytemDataCatalog
> PATH: NULL
> STATUS: 0
> NUMBER_FULLTEXT_TABLES: 1

UPDATE
A problem arises when the model number is simply a number, such as "4" in "iphone 4".
I am already dynamically building a CONTAINS query, inserting AND in between each term.  However, here are some issues:
> **WHERE CONTAINS(*, 'iphone AND 4 AND battery')** - returns 0 results
> **WHERE FREETEXT(*, 'iphone 4 battery')** - is matching for iphone
> OR battery which is sub-optimal
> **WHERE CONTAINS(*, '"iphone 4" AND "battery"')** - returns the most
> accurate result set

Given these findings I'm thinking that I should maintain a list of these "special cases" in a table, and generate my CONTAINS query dynamically based on this.
Any suggestions about this approach?

A: Have you tried using a full text index?
You are correct that SQL treats "1" or "2" as noise by default (you can change this)... but it should find "g60v" or "sz-vgn770N" no problem.  I have used FTS in similar fashion searching a catalog of books by ISBN and it worked fine.
Lastly, I may be wrong on this one... but I don't think the noise file gets created until you actually build/use FTS.
Also note that searching FTS isn't similar to using a like statement.  Read up on the different methods for searching FTS with Books Online if you're not familiar with the syntax.
A query like this should work for your needs:  (how I use FTS with my book catalog search)
WHERE FREETEXT (*, 'g60v asus laptop model' );

Read more about freetext queries here: http://msdn.microsoft.com/en-us/library/ms176078.aspx


text:
Q: How to mark selected options in for the option HTML tag? I am using normal select and mutliselect boxes on my site.
should I use <option selected="selected"> or simply <option selected> for selected items ?

A: Correct method according to W3C will be selected = "selected" as noted here
http://www.w3.org/TR/html-markup/option.html#option
Quentin: Not duplicated because this question is related to select,option meanwhile your response is related to checkboxes
(Same answer, different order to avoid "not an answer, it's a comment" comments for those unable to read a full post

A: If you want set selected more than 1 option in select, dont forget add to select attribute multiple and add to name of select [] else it doesnt work.

<select name="mega_select[]" multiple>
  <option value="some" selected="selected">some</option>
  <option value="value" selected="selected">value</option>
  <option value="non">non</option>
</select>

A: HTML5 spec:
https://www.w3.org/TR/html5/forms.html#attr-option-selected

The selected attribute is a boolean attribute.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:
The following are valid, equivalent and true:
<option selected />
<option selected="" />
<option selected="selected" />
<option selected="SeLeCtEd" />

The following are invalid:
<option selected="0" />
<option selected="1" />
<option selected="false" />
<option selected="true" />

The absence of the attribute is the only valid syntax for false:
<option />

Recommendation
If you care about writing valid XHTML, use selected="selected", since <option selected> is invalid XHTML (but valid HTML) and other alternatives are less readable. Else, just use <option selected> as it is shorter.


text:
Q: How can deploy node.js application in openshift I created node.js project, with express and angularjs and mongodb.
How can i deploy it to Openshift
the project structure look like this
My user name for the openshift is admin
password is X5900XJSLW4
db name is : topic
Now these are just fake , but they look like this. thanks
THIS WORK LOCALLY VERY FINE, BUT I GET Service Temporarily Unavailable @
http://topic-aggregator16.rhcloud.com/
error log found her
https://github.com/chihabSD/TopicAggregator/blob/master/images/errorlog.png
I REALLY NEED THIS TO WORK ASAP
    config.db.mongo = {};
config.web.port = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || process.env.WEB_PORT || 8080;
config.web.ip = process.env.OPENSHIFT_NODEJS_IP || process.env.IP;
config.db.mongo.url = process.env.OPENSHIFT_MONGODB_DB_URL || 'mongodb://localhost/topic';

A:
To deploy an existing project into openshift you need to modify your
  package.json and server.json files:

package.json

*

*Add the server.js file to the main key

*Add a start script in the scripts key
"main": "server.js",
"scripts": {
    "start": "node server.js",
 }
example
{
      "name": "to-do",
      "version": "1.0.0",
      "description": "Simple todo app",
      "main": "server.js",
      "scripts": {
           "start": "node server.js",
           "test": "echo \"Error: no test specified\" && exit 1"
       },
      "keywords": [
          "node",
          "angular"
      ],
      "dependencies" : {
          "express"    : "~4.7.2",
          "mongoose"   : "~3.6.2",
          "morgan"     : "~1.2.2",
          "body-parser": "~1.5.2",
          "method-override": "~2.1.2"
      },
      "author": "atefth@gmail.com",
      "license": "MIT"
}

server.js

*

*Add dynamic port from the openshift env

*Add dynamic IP from the openshift env
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

app.listen(server_port, server_ip_address, function () {

    console.log( "Listening on " + server_ip_address + ", server_port " + server_port  );

});

Now you can use the rhc --from-code flag to deploy a project from existing code

rhc app create appName nodejs-0.10 -s --from-code=https://github.com/username/app.git

UPDATE

If you're using mongodb you need to update your server.js file

if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
  connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
  process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
  process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
  process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
  process.env.OPENSHIFT_APP_NAME;
  config.db.mongo.url = connection_string;
}

Hope this helps.

A: In general, OpenShift Online (V2) will publish connection information to your application using environment variables (https://developers.openshift.com/languages/nodejs/environment-variables.html#listen).
Your nodejs webservice will need to use this information to connect to OpenShift's load-balancers.
For this example code, you would need to change
config.web.port = process.env.PORT || process.env.WEB_PORT || 3000;
config.web.ip = process.env.IP;

to:
config.web.port = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || process.env.WEB_PORT || 3000;
config.web.ip = process.env.OPENSHIFT_NODEJS_IP || process.env.IP;

For more information, see https://developers.openshift.com/languages/nodejs/environment-variables.html#listen
Npm modules cloud-env or config-multipaas may also be helpful if you prefer to stick with simpler, vendor-neutral application config strings (normalized to PORT and IP)


text:
Q: Why is SqlException severity class different from what the spec says it should be? I'm staring into logs of our service and see that there was a bunch of exceptions like this:
System.Data.SqlClient.SqlException
Class 14
Number 40613
LineNumber 65536
Source .Net SqlClient Data Provider

Database 'OurDatabase' on server 'ourserver' is not currently available.  Please retry the connection later.  If the problem persists, contact customer support, and provide them the session tracing ID of 'GUID-IN-HERE'.

Okay, we should retry... I open our retry logic code and clearly that code expects Number 40613 with severity class set to 17. Documentation confirms that this error message should have severity class set to 17.
Why the difference? Is this a bug in the .NET Framework or what?

A: Thanks for bringing this to our attention.  What you are seeing is due to a bug that's been exposed on V12.  The systems should report Severity = 17 (not 14) for error 40613.  We will fix this.
Please reach out to me if you have any questions.


text:
Q: How do I convert GWT Query to widget? I just started working with GWT Widgets. I am familiar with jQuery and GWT Query is similar and hence I'm comfortable with it.
I need to make a custom widget in GWT which encompasses the functionality I made in GQuery.
I know that GWT widgets need to be contained in a panel, but I have an existing element in GQuery. So I guess I need to convert that element to a widget first. How should I go about it ?

A: Using last code in GQuery (1.2.1-SNAPSHOT), you should be able to convert any element into a gwt panel using the panel() method.
GQuery myGQueryWidget = $("

Hello
World
");
Panel myGwtWidget = myGQueryWidget.as(Widgets.Widgets).panel();

Of course you can use this panel as any widget which you can add to any other gwt panel, or even you could add other gwt widgets to it.
You have to be aware about events because if you add gwt events to the panel it will remove events added with gquery

A: you can use GWTQuerys WidgetsHtmlPanel(http://gwtquery.googlecode.com/svn/trunk/gwtquery-core/javadoc/com/google/gwt/query/client/plugins/widgets/WidgetsHtmlPanel.html ) to convert HTML content to Panel.
This should do the trick.


text:
Q: Header issue and Sum up multiple excel rows I have the following data with missing header

I used the following code to add the header
df_output = df_output.rename_axis(['Hour','Input'])

The output seems to be fine, but when i try to sum up the data based on hour i get the error KeyError: 'Hour'
df_output = df.groupby(['Hour'], as_index=False).sum()

A: Your 'Hour' column is currently the index for you dataframe therefore you get the keyword error as the column does is not actually a column in the dataframe.
Try to reset the index first and then group by.
df_output = df_output.reset_index()

df_hour_sum = df.groupby(['Hour'], as_index=False).sum()


text:
Q: How do add drop down menu for the folium map? For example, given the various months columns containing temperatures per specific region, how can I change the heatmap based on each month using drop down menu? I already have a map built using the geodataframe.explore(column = 'col_name').
Thanks!

A: If you're working in jupyterlab, this is pretty easy! You can combine a ipywidgets.Output widget with a ipywidgets.Dropdown to set up your canvas, then capture the follium map with the output. You then need to link them by adding an event handler.
import geopandas as gpd
import ipywidgets
from IPython.display import HTML, display

df = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

out = ipywidgets.Output(layout={'border': '1px solid black'})

w = ipywidgets.Dropdown(
    options=df.columns.values.tolist(),
    value=df.columns.values[0],
    description='Column:',
    disabled=False,
)

def on_dropdown_change(change):
    out.clear_output()
    with out:
        display(df.explore(w.value, cmap="Blues"))

w.observe(on_dropdown_change, names='value')
display(w)

with out:
    display(df.explore(df.columns[0], cmap="Blues"))

out


text:
Q: Probability of picking m numbers from a subset of n numbers [Bingo game] I have one problem that I'm not able to solve. Let's say we have set A of 50 integers (1 to 50). We choose randomly 30 numbers (one by one, no repeat) from set A and let's name this new set, set B. Now, let's create third set C of 6 integers (possible numbers are from set A). This is some sort of a bingo game, so whats the probability that in n-th picking from set A (where we create set B) that we hit all 6 numbers from set C.
I'm looking for a formula in terms of A, B and C where this represents size of these set and n which indicates n-th picking.
Hope I was clear enough. Thanks in advance :)
EDIT: I wasn't clear enough.
I'm picking 30 times from set A. My question is what's the probability that in n-th picking I'll hit all 6 numbers I choosed in set C. I understand that in first 5 picks the probability is 0.

A: I hope I've understood your question correctly. I'll use $a=|A|$ and $c=|C|$.
Disregarding order, the number of ways to get all $c$ numbers in your first $n$ numbers for $B$ is the number of ways to choose the other $n-c$ numbers from the other $a-c\;$ non-$C$ numbers available. This equals $\binom{a-c}{n-c}$.
The total number of ways to choose $n$ numbers from $a$ available is $\binom{a}{n}$.
So the probability of your $n$ numbers having all $c$ numbers is $$\binom{a-c}{n-c}\bigg/\binom{a}{n}.$$
However, it sounds like you only want the cases where the $n^{th}$ number belongs to set $C$ so that you haven't got all $c$ numbers until you choose your $n^{th}$ number.
The fraction of the $\binom{a-c}{n-c}$ ways of having all $c$ numbers that have the $n^{th}$ number belonging to set $C$ is just $\dfrac{c}{n}$ because the $n^{th}$ number is equally likely to be any of the $n$ numbers selected.
So with this additional requirement, the probability is $$\dfrac{c}{n}\binom{a-c}{n-c}\bigg/\binom{a}{n}.$$

A: Let
$$
S(k, n)
$$
denote the probability that after $n$ picks, you have selected exactly $k$ of the $c = |C|$ numbers in $C$. You're wondering about $S(c, n)$. I can't tell you a formula for that, but I can at least write down a recurrence, for general $k$ and $n$, based on the idea that the only ways you can have $k$ good numbers on the $n$th pick are (a) to have $k$ on the $n-1$th pick, and pick a bad number, or (b) to have $k-1$ on the $n-1$th pick, and pick a good number. The result is therefore in general
$$
S(k, n) = pS(k-1, n-1) + q S(k, n-1)
$$
where $0 < k \le c$ and $1 \le n \le a$, and $p$ is the chance of picking a "good" number (one that's in the set $A$, but has not yet been picked in the first n-1 picks) from the set of all numbers not yet picked, and $q$ is the change of picking a "bad" number (one not in $A$), given that $n-1$ numbers have been picked. In the left-hand part, the number of "good" numbers remaining, under the assumption that $k-1$ have been picked, is $c - (k-1) = 1 + c - k$.
The total count of numbers remaining in $A$ is $a - (k-1) = 1 + a - k$. The probability $p$ is therefore
$$
p = \frac{1 + c - k}{1 + a - k}.
$$
Similarly, for the right-hand term, given that $k$ "good" numbers have already been picked, there are $c - k$ numbers remaining in $C$, and $a - k$ numbers remaining in $a$, and we want to pick one of the non-C numbers; thus
$$
q = \frac{(a-k) - (c - k)}{a-k} = \frac{a - c}{a - k}.
$$
Given these, we now have to think about the corner cases.

*

*What about when $n = 1$? To use the recurrence, we need a formula for $S(k, 0)$ for every $k$. That's not tough: $S(0,0) = 1; S(k, 0) = 0$ for all $k > 0$.

*What about when $k = c+1$? You can't every pick $c+1$ of the $c$ elements in $C$, so $S(k, n) = 0$ for every $k > c$.

*What about when $n > a$? You can't possibly pick more than $a$ items from a set of $a$ items, so $S(n, k) = 0$ for every $n > a$.
Now we can write down a general recurrence:
\begin{align}
S(k, n) &= \begin{cases}
1 & k = 0, n = 0 \\
0 & k > 0, n = 0 \\
0 & k > c\\
0 & n > a \\
\frac{1 + c - k}{1 + a - k}S(k-1, n-1) + \frac{a - c}{a - k} S(k, n-1) & \text{else}
\end{cases}
\end{align}
Using dynamic programming or memoization (yeah, that's a word!), you can now compute $S(k, n)$ for any $k,n$ pair in a number of operations proportional to $nk$, which for practical matters isn't too bad.
As for an explicit formula -- I doubt that's easy to find, but perhaps some MSE person can prove me wrong. I'd love to see it!


text:
Q: Using Callbacks with NetTcpBinding Is it possible to use callback like with WsDualHttpBinding in NetTcpBinding. Is NetTcpBinding support callbacks or events?

A: Yes, you can have a duplex binding over tcp. The TCP protocol allows duplex communication by design. It's not one of the system-provided ones but have a look at custom binding. Here you can find information regarding DuplexBindingElement.


text:
Q: Who's winning this coin drawing game? There are 2 piles of coins, each containing 2010 pieces. Two players A and B play a game taking turns (A plays first). In each turn the player on play has to take 1 or more coins from 1 pile or exactly 1 coin from both piles. Whoever takes the last coin is the winner. Which player will win if both play in the best possible way? We represent the present state of a game as config.(a+b) which means there are "a" coins in one pile an "b" coins in the other pile. Now it can be easily seen that a (2+1) config is a losing one for the person to play. Similarly a (3+3) config is a losing one for the person to play. Hence a (4+4) is a winning config because the player will then draw 1 coin each from both pile and force the other to a losing config. (5+5) is also a winning config because then the player to play(say A) will draw 1 coin from one of the piles. Hence depending on the other player's move it will turn into a (4+4) for A or a (3+3) for B after the next chance. So how do I proceed?

A: As Ross pointed out, you can solve this using nimbers. Working out the nimbers for some low coin counts leads to the winning strategy: Always make sure the coin counts are roughly equal, $\pm1$, and that their sum is divisible by $3$. That is, if the coin counts are equal and both have remainder $1$ mod $3$, take one coin from each pile; if the coin counts are equal and both have remainder $2$ mod $3$, take a coin from either pile: if the coin counts are different, take as many from the larger pile that you end up with the same count $\pm1$ and the sum is divisible by $3$. Such a move is always possible if the position isn't one of the losing positions $(3k,3k)$ or $(3k+1,3k+2)$ or $(3k+2,3k+1)$.
In particular, since $2010$ is divisible by $3$, the initial position is a losing position for player $A$.


text:
Q: Export variable from within while loop I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.
Any suggestion would be great help
var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done

A: The idea is right, just use the declare variable to create variables on the fly. Also avoid using un-quoted variable expansion(for i in ${var}) for looping. Use a proper array syntax as
var=("ahs" "tcs" "amq" "tos")

for i in "${var[@]}"; do
    declare ${i}_log="/var/tmp/pmp_${i}_log"
    export "${i}_log"
done

As a side note for good practice, always specify the interpreter to run your script. It could be #!/bin/bash or #!/bin/sh or best do it by #!/usr/bin/env bash

A: An alternative could be to use a single exported associative array instead of multiple variables:
EDIT: oops, this won't work since arrays can't be exported. :\
var="ahs tcs amq tos"

declare -A logs

for i in ${var}
do
  logs[$i]="/var/tmp/pmp_${i}_log"
done

echo ${logs[@]}
#### export logs

Also see Inian's answer for better practices for looping and arrays.

A: This works on dash and bash (as long as the i's and the path to interpolate them into are reasonable):
#!/bin/sh
var="a b c d"

for i in $var
do
        export "${i}_log=/var/tmp/pmp_${i}_log"

        #test
        sh -c "echo \$${i}_log"
done

A: This can be done in one line without a loop
printf '%s\n' {ahs,tcs,amq,tos} | xargs -I {} bash -c 'export {}_log="/var/tmp/pmp_{}_log"; echo {}_log=${{}_log}'

or with a loop
#!/bin/bash
for i in {ahs,tcs,amq,tos}; do
    #export
    export "${i}_log=/var/tmp/pmp_${i}_log";

    #test
    bash -c 'echo '"${i}_log"'='"\$${i}_log"; done
done

The reason  ${i}_log="/var/tmp/pmp_${i}_log" failed is because ${i}_log is unquoted and the syntax for exporting is export somevar=somedefintion. In order to dynamically generate the variable name, surround the statement in quotes so that it gets interpolated. ie. export "${dynamic}_var=${dynamic}_definition"
see http://wiki.bash-hackers.org/syntax/quoting


text:
Q: Why is a wine glass shaped the way it is? Why is a wine glass shaped the way it is? And why are there different shapes for different wines? Is this a tradition, or is there any scientific reason behind it?

A: A little bit of physics - but mostly just fashion.
Red wines (supposedly) need to oxidize to release the flavo(u)r so red wine glasses have wider necks to allow more air. White wines don't and so the glasses have narrower necks.
If there really was a significant difference then you would drink white wines from a sealed pouch through a straw and shake red wines like a cocktail. So it's probably now more a question of fashion and pretend insider knowledge.


text:
Q: WebRTC instead of UDP stream on webpage to remove VLC Player Is it possible to stream life broadcast video on closed network via WebRTC to webpage 1-many? I used to use VLC and UDP streaming for life video, but all browsers discontinued support for VLC plugin and HTML5 video does not support life streaming. The goal is to use webpage for life video streaming when users  only watch that page (no 2 way communication).
Thank you

A: Yes you can.
This will be more expensive to do (processing power and servers that you'll need), but definitely possible.
Janus and Jitsi are used a lot for it. Red5Pro, nanocosmos and Wowza seem to have suitable offerings in this domain as well.


text:
Q: Power of two to get an integer I need a (fairly) fast way to get the following for my code.
Background: I have to work with powers of numbers and their product, so I decided to use logs.
Now I need a way to convert the log back to an integer.
I can't just take 2^log_val (I'm working with log base 2) because the answer will be too large. In fact i need to give the answer mod M for given M.
I tried doing this. I wrote log_val as p+q, where q is a float, q < 1 and p is an integer.
Now i can calculate 2^p very fast using log n exponentiation along with the modulo, but i can't do anything with the 2^q. What I thought of doing is finding the first integral power of 2, say x, such that 2^(x+q) is very close to an integer, and then calculate 2^p-x.
This is too long for me because in the worst case I'll take O(p) steps.
Is there a better way?

A: While working with large numbers as logs is usually a good approach, it won't work here. The issue is that working in log space throws away the least significant digits, thus you have lost information, and won't be able to go back. Working in mod space will also throw away information (otherwise your number gets to big, as you say), but it throws away the most significant ones instead.
For your particular problem POWERMUL, what I would do is to calculate the prime factorizations of the numbers from 1 to N. You have to be careful how you do it, since your N is fairly large.
Now, if your number is k with the prime factorization {2: 3, 5: 2} you get the factorization of k^m by {2: m*3, 5:m*2}. Division similarly turns into subtraction.
Once you have the prime factorization representation of f(N)/(f(r)*f(N-r)) you can recreate the integer with a combination of modular multiplication and exponentiation. The later is a cool technique to look up. (In fact languages like python has it built in with pow(3, 16, 7)=4.
Have fun :)

A: If you need an answer mod N, you can often do each step of your whole calculation mod N.  That way, you never exceed your system's integer size restrictions.


text:
Q: Uninstall PCI device driver I want to uninstall a pci device driver from the computer via c++ code.
Im looking for the same action like right-clicking on a device in the device manager, and clicking 'Uninstall'.
I found a function called DiUninstallDevice, but it is available only in Windows 7 and later versions of Windows.
Im using Windows XP. Is it possible to do this?

A: you should take a look the following sample DevCon the sample code exits also in WDK that support XP. also in the WDK there is alot of sample of using the DiFX


text:
Q: Workflow to - Send Email when Field in List updated SP 2010 I have a large list that is used to manage Projects, I want to trigger an email to certain users when a Project Status is changed from "New Project" to "In Assessment" etc.
I've been looking at having two additional columns Previous State and Previous State 2.

*

*When a new item is created the Project Status is copied to the Previous State Field.

*When an item is modified the Previous State value is copied to the Previous State 2 field.

*If the Project Status and Previous State 2 values don't match an email would be sent.

Would this logic work and how can i avoid an email being sent every time an unrelated field in the list is updated?
Many Thanks

A: Few questions. Is there some other status than those two you mentioned?
If yes, what if status changes from In assessment to lets say Paused or Non Assigned or something else?
Is it allowed only once for mail to be sent and to notify certain users?
If you need to send only once notification mail, you don't need those two columns. You can manage it with Status column and with additional column Email sent type of column Yes/No or choice and than out Yes/No.
Than, when status of your item is changed to in assessment trigger workflow to send email and change your status of Column Sent from No to Yes.
In your workflow put first If to check if status Email sent is Yes or No. If it is No than go to second If where it should check what is the value of your Project status column and than send an email if that rule is good.
If status of Email send is Yes, than workflow will go to the end and just make a log with some sentance like Email already sent or similar.

A: To send an email based on a status field (or any field), you only need to add one field to the list. In your case, add a text field LastProjectStatus (name it whatever). Check to see if the 2 fields are different. If they are, then check for the current status and send the appropriate email. After that, set the 'last' field equal to the current field so the next change that doesn't have anything to do with status won't send the email. We do this all the time - we have complex tasks that have up to 20 status - they move an item between many departments.
Then, in your workflow that runs on a change:
If CurrentItem:Project Status not equals CurrentItem:LastProjectStatus
    If(CurrentItem:Project Status equals "In Assessment"
         send an email
    else
      if(CurrentItem:project Status equals "xxx"
         send an email for that
        else if..... etc for each status that needs an email
    then set CurrentItem:LastProjectStatus to CurrentItem:Project Status

When I do this, I don't limit it to 'when change from this to that'. I send the email 'when change to that'. Then users can go back and forth with the different statuses, resetting them if they want to go through the whole ting again.


text:
Q: Running into socket saturation/IO Exceptions wen issuing more than 500 concurrent requests to Apache Solr index update I am using Apache Solr with Hitachi and running some load tests, I am creating a large number of Index update requests and using c# tasks to send them at the same time.
If I keep my number below 500 then everything works fine, I can keep making multiple requests as long as at a time it does not exceed 500 requests
But if I increase that number I start getting IO Exception, connection has been terminated errors, all of them pointing to the socket saturation (no more socket available) problem
500 is not a lot of requests and we will have peak times where 1000's of users might be making changes that leads to index updates, I have explored setting Max http connection for a server in C# code and that works but that will limit the scalability and because the requests will be queued the average response time will increase.
Is there a way to change the number of concurrent connection Solr can handle.


text:
Q: Accordeon на mouseenter `
помогите добить аккордеон.
Реализация на mouseenter.
Суть задачи:
1)Ховер на название  - открывается описание.
2)Ховер на другое название - открытое описание закрывается и открывается новое в соответствии с ховером.
3)Курсор уходит в сторону - описание остается открытым.
4)То есть описание реагирует на курсор.
5)Одно описание открыто всегда.
у меня ступор по реализации второго и пятого пункта.

if (document.readyState !== 'loading') {
  console.log("ready!");
  ready();
} else {
  document.addEventListener('DOMContentLoaded', ready);
}

function ready() {
  let accordion = document.querySelectorAll(".accordion-item-header");
  console.log(accordion);
  for (let i = 0; i < accordion.length; i++) {
    accordion[i].addEventListener('mouseenter', function() {
      accordionMouseenter(event);
    });
  }
}

let accordionMouseenter = (eventHappened) => {
  let targetEnterMouse = event.target;
  let classEnter = targetEnterMouse.classList;
  while ((classEnter[0] != "accordion-item-header")) {
    targetEnterMouse = targetEnterMouse.parentElement;
    classEnter = targetEnterMouse.classList;
  }
  let description = targetEnterMouse.nextElementSibling;
  if (description.style.maxHeight) {
    description.style.maxHeight = null;
  } else {
    let allDescriptions = document.querySelectorAll(".accordion-item-body-content");
    for (let i = 0; i < allDescriptions.length; i++) {
      if (allDescriptions[i].style.maxHeight) {
        console.log(allDescriptions[i].style.maxHeight);
        allDescriptions[i].style.maxHeight = null;
      }
    }
    description.style.maxHeight = description.scrollHeight + "px";

  }
}
.sell_accordion {
  padding: 20px 0 120px 20px;
  width: 75%;
}

.sell_accordion .accordion_content {
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.sell_accordion .accordion_content .accordion {
  width: 100%;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header {
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
  font-weight: bold;
  font-size: 48px;
  line-height: 59px;
  color: black;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  position: relative;
  cursor: pointer;
  margin: 0 0 50px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header:last-child {
  margin: 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header.active {
  border-bottom: 3px solid #FF6C00;
  margin: 0 0 15px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body {
  max-height: 0;
  overflow: hidden;
  -webkit-transition: max-height 0.2s ease-out;
  transition: max-height 0.2s ease-out;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content {
  padding: 0 0 50px 0px;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content p {
  font-weight: 500;
  font-size: 18px;
  line-height: 22px;
  color: black;
  margin: 0 0 25px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content p:last-child {
  margin: 0;
}

          Мы продаем

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos aspernatur non voluptates adipisci sapiente architecto, quod temporibus blanditiis fugit praesentium.

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, aspernatur.

              Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae voluptates nisi, dolorem esse ut placeat autem dolorum, quia in beatae non praesentium enim quis et sunt aperiam cum eius voluptatem a voluptate optio quibusdam maiores? Amet corporis
              eos iusto error beatae similique molestias, reiciendis consequuntur, quae quaerat aspernatur sit qui.

          Мы доставляем

          Аренда полей и предзаказ урожая

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Animi quae fuga cumque similique deserunt quisquam. Culpa accusantium eum animi et!

          Овощи и фрукты. Что-нибудь еще?

              HTTP, aka HyperText Transfer Protocol, is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

          Нужен представитель в Турции:

              CORS, aka Cross-Origin Resource Sharing, is a mechanism that enables many resources (e.g. images, stylesheets, scripts, fonts) on a web page to be requested from another domain outside the domain from which the resource originated.

          Работа с контрагентами

              CORS, aka Cross-Origin Resource Sharing, is a mechanism that enables many resources (e.g. images, stylesheets, scripts, fonts) on a web page to be requested from another domain outside the domain from which the resource originated.

`

A: При каждом наведии мышки на элемент, нужно было скрывать все остальные элементы, вы просто обращались не к тем элементам.
Нужно было писать вот-так:
 let allDescriptions = document.querySelectorAll(".accordion-item-body");

вместо этого:
let allDescriptions = document.querySelectorAll(".accordion-item-body-content");

if (document.readyState !== 'loading') {
  console.log("ready!");
  ready();
} else {
  document.addEventListener('DOMContentLoaded', ready);
}

function ready() {
  let accordion = document.querySelectorAll(".accordion-item-header");

  for (let i = 0; i < accordion.length; i++) {
    accordion[i].addEventListener('mouseenter', function() {
      accordionMouseenter(event);
    });
  }

  let allDescriptions = document.querySelectorAll(".accordion-item-body");
  allDescriptions[0].style.maxHeight = allDescriptions[0].scrollHeight + "px";
}

let accordionMouseenter = (eventHappened) => {
  let allDescriptions = document.querySelectorAll(".accordion-item-body");

  for (let i = 0; i < allDescriptions.length; i++) {
    if (allDescriptions[i].style.maxHeight) {

      allDescriptions[i].style.maxHeight = null;
    }
  }
  let targetEnterMouse = event.target;
  let classEnter = targetEnterMouse.classList;
  while ((classEnter[0] != "accordion-item-header")) {
    targetEnterMouse = targetEnterMouse.parentElement;
    classEnter = targetEnterMouse.classList;
  }
  let description = targetEnterMouse.nextElementSibling;
  if (description.style.maxHeight) {
    description.style.maxHeight = null;
  } else {
    description.style.maxHeight = description.scrollHeight + "px";
  }
}
.sell_accordion {
  padding: 20px 0 120px 20px;
  width: 75%;
}

.sell_accordion .accordion_content {
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.sell_accordion .accordion_content .accordion {
  width: 100%;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header {
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
  font-weight: bold;
  font-size: 8px;
  line-height: 9px;
  color: black;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  position: relative;
  cursor: pointer;
  margin: 0 0 10px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header:last-child {
  margin: 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-header.active {
  border-bottom: 3px solid #FF6C00;
  margin: 0 0 15px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body {
  max-height: 0;
  overflow: hidden;
  -webkit-transition: max-height 0.2s ease-out;
  transition: max-height 0.2s ease-out;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content {
  padding: 0 0 10px 0px;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content p {
  font-weight: 500;
  font-size: 8px;
  line-height: 12px;
  color: black;
  margin: 0 0 5px 0;
}

.sell_accordion .accordion_content .accordion .accordion-item .accordion-item-body .accordion-item-body-content p:last-child {
  margin: 0;
}

          Мы продаем

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos aspernatur non voluptates adipisci sapiente architecto, quod temporibus blanditiis fugit praesentium.

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Praesentium, aspernatur.

              Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae voluptates nisi, dolorem esse ut placeat autem dolorum, quia in beatae non praesentium enim quis et sunt aperiam cum eius voluptatem a voluptate optio quibusdam maiores? Amet corporis
              eos iusto error beatae similique molestias, reiciendis consequuntur, quae quaerat aspernatur sit qui.

          Мы доставляем

          Аренда полей и предзаказ урожая

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Animi quae fuga cumque similique deserunt quisquam. Culpa accusantium eum animi et!

          Овощи и фрукты. Что-нибудь еще?

              HTTP, aka HyperText Transfer Protocol, is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

          Нужен представитель в Турции:

              CORS, aka Cross-Origin Resource Sharing, is a mechanism that enables many resources (e.g. images, stylesheets, scripts, fonts) on a web page to be requested from another domain outside the domain from which the resource originated.

          Работа с контрагентами

              CORS, aka Cross-Origin Resource Sharing, is a mechanism that enables many resources (e.g. images, stylesheets, scripts, fonts) on a web page to be requested from another domain outside the domain from which the resource originated.


text:
Q: How can I trace out modification of stored procedure with TSQL Command in SQL Server? Using this query I can get created date and last modified date:
SELECT name, create_date, modify_date ,*
FROM sys.objects
WHERE type = 'P'

But how can I get command?

A: There are several ways you can do this, for example:
SELECT  o.name,
        o.create_date,
        o.modify_date,
        m.[definition]
FROM sys.objects o
LEFT JOIN sys.sql_modules m ON o.[object_id] = m.[object_id]
WHERE o.[type] = 'P'

You can also use OBJECT_DEFINITION() or sp_helptext if you'd prefer - the latter returns a table with one row for each line of the source code for the specified object.
You'll find some more information on this MSDN page.


text:
Q: javascript i wrote not working, can't figure out why I'm working on a menu script for my custom menu. It's a horizontal menu, with four tabs. What I want the menu to do is:

*

*When you click on a tab, it opens a submenu underneath with different options;

*When you click on the same tab again, hide the submenu;

*The menu and submenus are laid out using GRID CSS, cause tab one displays one cell with text and only one link (using the whole width); tab two displays four cells; tab three displays two cells using both 50% of width, etc.
I can't seem to figure out why my script isn't working. Maybe jQuery would be better, I got no idea, I'm new to all of this. Also, maybe there's a simpler way to do this using WP, but again, I haven't found a tutorial on how to do this. :/
Could someone please help me? Thanks.
Code fiddle: JSfiddle

A: Have you looked at the debugging the javascript code? It shows bunch of errors when you run your fiddle.
such as
Uncaught ReferenceError: openDisplay is not defined
at HTMLButtonElement.onclick ((index):181)

and this one too once you fix the above one
Uncaught TypeError: document.getElementsById is not a function
at openDisplay ((index):164)

This one is because there is no function called getElementsById since there should only be unique id for all the elements. So it should be getElementById
Jquery is certainly a better idea (For me)  because of ease of using the jquery selectors.
    /* Click Handlers */
$('#menu-aquo').on('click', function(e) {
  e.preventDefault();
  openDisplay(e, 'aquo');
});

$('#menu-categories').on('click', function(e) {
  e.preventDefault();
  openDisplay(e, 'categories');

});

$('#menu-involve').on('click', function(e) {
  e.preventDefault();
  openDisplay(e, 'involve');
});

$('#menu-search').on('click', function(e) {
  e.preventDefault();
  openDisplay(e, 'search');
});

function openDisplay(evt, tabName) {
  //Declare all variables
  var i, target, menutab, submenu;

  // Remove 'active' class from all menutabs
  $('.menutab').removeClass("active");
  // Add active to the current menutab
  evt.currentTarget.classList.toggle("active");

  target = "div." + tabName;

  // Select all except currently clicked submenu and hide them
  toHide = $('.submenu:not(.' + tabName + '.hidden)')
    .each(function() {

      if (!$(this).hasClass(tabName)) {
        $(this).addClass("hidden");
      }

    });
    //Select all current submenu and hide or show them
  submenu = $(target)
    .each(function() {
      if ($(this).hasClass("hidden")) {
        $(this).removeClass("hidden");
      } else {
        $(this).addClass("hidden");
      }

    });

}

Here is a working jquery JsFiddle with comments.
Also just my two cents:
I would have organized the menu a bit differently.
For example, Instead of

some text with one link

    <img src="<?php echo get_template_directory_uri(); ?>/img/zebra.png" />Zebrology

    <img src="<?php echo get_template_directory_uri(); ?>/img/clip.png" />Clips

I would have each submenu under separate div so that i just put hidden on the main one.
Example

some text with one link

          <img src="<?php echo get_template_directory_uri(); ?>/img/zebra.png" />Zebrology

           <img src="<?php echo get_template_directory_uri(); ?>/img/clip.png" />Clips

But each coder has his/her own style. So doesn't matter much.
As for WordPress, it already provides an easy way to build and organize menus. All you have to do this modify the css to make it look the way you want it to look.
Check the Method 2 for manually styling the WordPress Menu from this tutorial.
Basically WordPress adds some classes to the menu which you can use to modify the look and feel of the menu.
// container class
#header .primary-menu{}

// container class first unordered list
#header .primary-menu ul {}

//unordered list within an unordered list
#header .primary-menu ul ul {}

 // each navigation item
#header .primary-menu li {}

// each navigation item anchor
#header .primary-menu li a {}

// unordered list if there is drop down items
#header .primary-menu li ul {}

// each drop down navigation item
#header .primary-menu li li {}

// each drap down navigation item anchor
#header .primary-menu li li a {}


text:
Q: how can I apply Datatable jquery on asp.net GridView?  <asp:GridView ID="grdDonationRequests" runat="server" SelectMethod="grdDonationRequests_GetData" AutoGenerateColumns="False"
                                 AllowPaging="True"  PagerSettings-Mode="NumericFirstLast"  PageSize="10" DataKeyNames="DonationRequestID" ItemType="Tayf.Models.DonationRequest"
                                AllowSorting="true" Width="100%" CssClass=" table-striped table-condensed table table-bordered table-hover" meta:resourcekey="grdDonationRequestsResource1">

I tried to do this
    $(function () {
         $("#<%=grdDonationRequests.ClientID%>").prepend(
$("thead>/thead>").append($(this).find("tr:first"))).dataTable({
                    });
                });

but It gives me an Error
Uncaught TypeError: Cannot read property 'className' of undefined
Update:-

When I tried this '$("#<%=grdDonationRequests.ClientID%>").dataTable({ "aaSorting": [] });' it gives me no error also draw gridview as datatable but display it as a empty

A: I am in the process of doing this very thing right now. the following code is all that was required to actually convert the gridview to a datatable:
$(document).ready(function () {
var table = $('#your_gridview_id').DataTable();

Hope this helps!

A: Try this
$(function () {
  $("#<%=grdDonationRequests.ClientID%>").dataTable({
  });
});

Also look at this answer


text:
Q: Trying to build angular4 old project with webpack but failing I am totally new in angular and getting a lot of errors during building an old angular project. Using old node version to be compatible.
version :
    @angular/compiler : 4
    webpack : 1.x
    awesome-typescript-loader : 3.x
    node-version - 6

warning starts with :
    "can't find source file main.ts : Error : can't resolve file or directory ./main.ts in ~\ag-grid-angular"
     follows with almost same 1000 errors
    "ERROR in [at-loader] node_moduler\@types\lodash\common\array.d.ts 23:10"
     ';' expected (repeats 1000 times same error with ';', ',', '(' combinations. Looked the code at
      that line but found nothing wrong)

...
during maven build got :
    Error in bail mode : [at-loader] node-moduler/.../array.d.ts
    npm ERR! code ELIFECYCLE
    npm ERR! build.prod : 'webpack .. --bail'
    npm ERR! Exit status 1

I tried with different webpack version, ts-loader instead of awesome-typescript-loader. In ts-loader the errors more decrypted. Should I move to angular-cli first or building with webpack possible?


text:
Q: Ionic 2/3 Pushing items in Array based on ID I'm looking to push items from one page to another, based on the category ID. Then I went to push all the contents from the array(who have the category ID that matches) to the next page.
I'm caught between using an if statement to pass the parameters to the second page, or to call the array in the second page and use an NgIf. Below is my code for a better visual. I'm fairly new to Ionic. Thank you for the help!
First Page
if(id = 1) {
    category_id: this.referenceList.category_id = 1;

    this.navCtrl.push(ReferencePage,{category_id:"category_id"});
  }
  else {
    console.log("nope")
  }

Second Page
<div *ngfor = let reference of referenceList></div>
<div *ngif = category.id === 1> {{reference.referenceField1}} {{reference.referenceField2}} {{reference.media}} </div>

Not sure which one to use and why. Thanks again! Happy to clarify if there's any confusion.

A: You stored the category_id in a variable, so use this:
this.navCtrl.push(ReferencePage,{category_id:category_id});
In the second page controller you need:
import ( NavParams ) from 'ionic-angular';

category_id: number;

constructor(public navParams: NavParams) {
    ...
}

ionViewDidLoad() {
    this.category_id = this.navParams.get('category_id');
}

Also, your html should be (if I understand what you are doing):
<div *ngFor = let reference of referenceList>
    <div *ngIf = category_id === 1>
        {{reference.referenceField1}};
        {{reference.referenceField2}};
        {{reference.media}};
    </div>
</div>


text:
Q: Removing duplicate rows using delete query? This question was asked for an interview, I still cant find an answer by googling it.
I have a table with two columns. Table doesn't have any primary key. I want to delete the duplicate rows. I can do it by alter table but they want a delete query.
Here is the table data.
empid name
1     rahul
2     rajeev
1     rahul
2     rajeev
2     rajeev
3     elias
4     amith
2     rajeev

The result should be be
1     rahul
2     rajeev
3     elias
4     amith

A: As @Marc B says in the comments, this sounds like a trick question. But if it's not...
The only solution I know of (without being aware of a proper ranking function in mysql) is to somehow loop through each name and running the following query:
DELETE FROM tbl_name
WHERE name=@name
LIMIT 1

This wouldn't be one query so it wouldn't be a valid answer but I'm not sure of any other way to do it in mysql.
Another option would be to use SELECT DISTINCT into a temp table, TRUNCATE the original table, and INSERT the records back into it from a temp table. Again, this doesn't satisfy the requirements.


text:
Q: JUnit how to save DisplayName in xml report file I want to generate XML report file with info of executed tests. Previously I used shown below @Rule in JUnit4 but now I want to display comment or some short of short description instead of testName. After some research I found @DisplayNamein JUnit5 that seems to suit my needs. Now I have to update my @Rule to display @DisplayNamecontent instead of testName[number].className.
Tests are written in JUnit classes and have following structure
@Test
@DisplayName("This text should be displayed as name")
public void testy1() {...}

To display outcome and name of run test I created new rule with following scheme
@Rule
public TestRule watchman = new TestWatcher() {
    @Override
    public Statement apply(Statement base, Description description) {
                return super.apply(base, description);
            }
@Override
protected void succeeded(Description description) {
        try {

            junitWriter.write("\n   <test>"
                            + "\n       <name>" + description.getDisplayName() + "</name>"
                            + "\n       <result>..
                            + "\n       <message>..
                            + "\n   </test>");
        } catch [..]
    }
@Override
        protected void failed(Throwable e, Description description) {
            //same scheme with error
        }
}

To start tests I run
Result result = JUnitCore.runClasses(mainSuiteClassCreatingReport);
System.out.printf("Test ran: %s, Failed: %s%n", result.getRunCount(), result.getFailureCount());

In generated XML file instead of "DisplayName" annotation I keep getting methodName[number].className. Can anybody help me to display/save it the way I want?

A: You cannot use @DisplayName with JUnit 4.
If you want to use @DisplayName, you'll need to switch to JUnit Jupiter (a.k.a., JUnit 5) and implement an Extension.
Note that JUnit Jupiter does not yet support an extension API like the TestWatcher rule from JUnit 4; however, such support is coming in JUnit 5.4: https://github.com/junit-team/junit5/issues/542
To customize what is returned from getDisplayName() in Description in JUnit 4, you would need to write your own custom Runner. As an alternative, you could simply parse the value returned from getDisplayName() and use that to generate your own display name.
Or, if you want to support your own custom display name annotation with JUnit 4, such as this:
package foo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyDisplayName {

    String value();

}

You could look it up in your TestWatcher implementation using reflection like this:
package foo;

import java.lang.reflect.Method;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class ExampleTests {

    @Rule
    public TestRule watchman = new TestWatcher() {

        @Override
        protected void succeeded(Description description) {
            System.out.println("Display name: " + getDisplayName(description));
        }

        private String getDisplayName(Description description) {
            Class<?> testClass = description.getTestClass();
            String methodName = description.getMethodName();
            try {
                Method method = testClass.getDeclaredMethod(methodName);
                MyDisplayName myDisplayName = method.getAnnotation(MyDisplayName.class);
                return myDisplayName.value();
            }
            catch (Exception ex) {
                // do something with the exception if you want...
            }
            // default:
            return testClass.getName() + "." + methodName + "()";
        }
    };

    @Test
    public void testWithoutCustomDisplayName() {
    }

    @Test
    @MyDisplayName("Custom display name!")
    public void testWithCustomDisplayName() {
    }

}

Running that test class outputs the following:
Display name: foo.ExampleTests.testWithoutCustomDisplayName()
Display name: Custom display name!


text:
Q: Passing an URL with parameters in Google Charts API I want to generate a QrCode image with the Google Chart API. The QrCode encloses an URL with multiple parameters
http://example.com/page.php?param=nothing&param2=nothing

The Google Chart URL to generate this code would be
http://chart.apis.google.com/chart?cht=qr&chs=230x230&choe=UTF-8&chld=L&chl=*http://example.com/page.php?param=nothing**&param2**=nothing*

But this doesn't work. Obviously, the browser consider param2 to be part of the original URL.
Any hack to solve this?

A: Check out this flex example out. Full call looks like this:
https://www.google.com/jsapi/chart?cht=bvs&chs=500x500&chd=t:100,200,300,400,500,600,700&chds=0,700&chl=Savings|Checking|Money Market|Taxable Stocks|Taxable Bonds|IRA|Pension


text:
Q: Get a Windows Form to behave similar to a taskbar I've got a problem (well, rather no clue how to do something) about my Windows Form.
I have set up a windows form that, much like the task bar, goes from the left to the right of the screen. Now I would like it to, instead of being "above" other windows, "push" them down / make them smaller so they fit between a sort of "top-task-bar" and the normal taskbar - here you have a screenshot of what it looks like right now:

As you can see, it's in the way of other programs' controls etc.. Since I would like it to stay TopMost, I have to do what the task bar does - decrease the working area so programs have no problems but it's still there. I'm using Windows Forms.
Any advice on how to achieve this?
Thanks!


text:
Q: null pointer exception at FragmentPage.java I am getting a null pointer exception error at runtime.I am mentioned the error line in below coding.I am posted the codes relevant to that.I am unable to solve this.Anybody can help me if you know how to solve these.Thank You.
StackTrace:
11-03 05:14:58.729: E/AndroidRuntime(18247): java.lang.NullPointerException
11-03 05:14:58.729: E/AndroidRuntime(18247):    at com.qrme.FragmentPage.highlightCell(FragmentPage.java:473)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at com.qrme.FragmentPage.moveToNext(FragmentPage.java:455)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at com.qrme.FragmentPage$10.onItemClick(FragmentPage.java:351)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.widget.AbsListView$3.run(AbsListView.java:3638)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.os.Handler.handleCallback(Handler.java:733)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.os.Handler.dispatchMessage(Handler.java:95)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.os.Looper.loop(Looper.java:136)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at android.app.ActivityThread.main(ActivityThread.java:5017)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at java.lang.reflect.Method.invokeNative(Native Method)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at java.lang.reflect.Method.invoke(Method.java:515)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-03 05:14:58.729: E/AndroidRuntime(18247):    at dalvik.system.NativeStart.main(Native Method)

FragmentPage.java:
public class FragmentPage extends Fragment {

    GridView gridTable;
static LinearLayout ll;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

         rootView = inflater.inflate(R.layout.fragmentxml, container, false);

        initialize(rootView);
        clickEvents();

        return rootView;

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    tablelist = DatabaseQueryHelper.getInstance().getContentTable(pageId);
        System.out.println(tablelist);
        System.out.println(pageId);
        if (tablelist != null && !tablelist.isEmpty()) {
            CustomeTableAdapter tableAdapter = new CustomeTableAdapter(
                    getActivity(), R.layout.frame_table, tablelist);
            gridTable.setAdapter(tableAdapter);

        } else {
            ll.setVisibility(View.GONE);
            if(tableVisible && !getactivitytable)
            {
                if (tablelist == null
                        || tablelist.isEmpty()
                        && sharedpreference.get_sharedvalue(
                                QRMConstants.VERSION).equals("1.0")) {
                    showDialog();

                }

            }
        }

    }

public void initialize(View v) {

        gridTable = (GridView) rootView.findViewById(R.id.gridViewTable);
        ll.setVisibility(View.GONE);

        gridTable.setDrawSelectorOnTop(true);

    }

public void moveToNext(int nextposition) {

        highlightCell(nextposition); --->455 th line error
        ispaused = false;
        play(nextposition);

    }

gridTable.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    final int position, long id) {
                if (tablelist != null && !tablelist.isEmpty()) {
                    ll.setVisibility(View.VISIBLE);
                    player.reset();
                    currentSelection = position;
                    moveToNext(currentSelection); --->351 th line error
                } else {
                    ll.setVisibility(View.GONE);
                }
            }
        });

public void highlightCell(int position) {

        for (int i = 1; i < tablelist.size(); i++) {

            gridTable.getChildAt(i - 1)
                    .setBackgroundResource(R.drawable.border); ---->473 rd line Error

        }

        gridTable.getChildAt(position).setBackgroundColor(
                getResources().getColor(R.color.dusty_grey));

    }

fragmentxml.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
    android:id="@+id/linearlayoutControll"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@color/light_grey"
    android:gravity="center"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/imagebuttonLast"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/ic_action_previous"
        android:scaleType="fitXY" />
      </LinearLayout>
      <GridView
        android:id="@+id/gridViewTable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearlayoutControll"
        android:layout_alignParentTop="true"
        android:layout_margin="15dp"
        android:listSelector="#00000000"
        android:numColumns="2"
        android:rotationY="180" >
    </GridView>

</RelativeLayout>


text:
Q: Not able to simulate key events in Message app using Tizen::Ui::SystemUtil::GenerateKeyEvent I have created sample application that will launch Message app, which in turn generates and sends KEY_1 using Tizen::Ui::SystemUtil::GenerateKeyEvent().
Here is code snippet:
String strAppName = L"tizen.messages";
result r;

Tizen::App::AppControl* pAc = AppManager::FindAppControlN(strAppName, L"http://tizen.org/appcontrol/operation/compose");
if (pAc)
{
    r = pAc->Start(null, null, null, null);
    delete pAc;
}
AppLog("Application launch status : [%s]", GetErrorMessage(r));

sleep(2);

Tizen::Ui::KeyCode keyToSimulate = Tizen::Ui::KEY_1;

r = Tizen::Ui::SystemUtil::GenerateKeyEvent(Tizen::Ui::KEY_EVENT_TYPE_PRESSED, keyToSimulate);
AppLog("KEY_EVENT_TYPE_PRESSED [%d] and result :: %s", keyToSimulate, GetErrorMessage(r));
r = Tizen::Ui::SystemUtil::GenerateKeyEvent(Tizen::Ui::KEY_EVENT_TYPE_RELEASED, keyToSimulate);
AppLog("KEY_EVENT_TYPE_RELEASED [%d] and result :: %s", keyToSimulate, GetErrorMessage(r));

Application launched successfully and the result of the GenerateKeyEvent pressed and released is E_SUCCESS. The value '1' is not getting printed on the Message app.
Please help me to simulate the keys.
Thanks,
Anil.

A: May be its not the way to do it, you should pass the data to the message app within the parameters of pAc->Start. Thats how normally tizen app works, You are not defining where to simulate the keyEvent isn't it.You dont have control over other App to simulate an event on it. You can define the data to pass within a IList or HashMap in the parameters, Good Luck