How can I change light bulbs in a fixture located 20ft above the ground?

Question: We made the unfortunate decision of having a ceiling fan with lights in our two story family room, so the ceiling fan is about 20 feet above our heads.  At the moment, all four light bulbs in the unit have burnt out and need replacing.
Safety wise, I think it's too high for even a long ladder.
What are some options for reaching and changing those light bulbs?
Comment: Definitely buy LED lights.  Incandescents are a terrible choice for hard-to-replace lighting.
Comment: Those 20ft are a non-SI unit, I guess?!? Any translation for non-US readers?
Comment: @UweKeim 20 feet I think is just over 6 meters.
Answer: I'm not sure how much room you have to work in, but an option would be to rent a 16 foot step ladder at your local tool rental center.

If the bulbs are pointed down, maybe some type of bulb grabber on an extension pole.

Got a pic of the fixture?
Comment: Another way to do it is [demonstrated here](http://www.youtube.com/watch?feature=player_detailpage&v=2Oz1nB5-wW0#t=169s) (only in German, sorry).
Comment: I have a couple of these bulb grabers awesome when they work in tight spots like the fixtures shown but sometimes the ladder is the only way if two close to a wall.
Answer: If you are uncomfortable with working at heights you can hire someone to change the lights (and clean the fan).
Think about installing LED light bulbs. You may never need to change them again.
Comment: I'd definitely go with LED. They're still very expensive for general use, but even a half dozen years ago they were replacing traffic lights because their lifespan let them crush the competition when doing the replacement becomes a major factor.  Never changing them is probably optimistic, I believe they use the same 1000 hours use = 1 year metric as CFLs to get their 15-30 year lifespans.  For heavily used parts of your house that's generally significantly too low.
Comment: Beware of the other electronics in the LED bulbs, they (or their soldering) may not be able to take the vibration from a fan. Probably want to look for ones rated for fans.
Comment: @Dan Neely - Coloured LEDs are much more established technology then white LEDs. They also last much longer, as they don't need a phosphor (which most white LEDs do). As such, using them in traffic lights was far less of an innovation then most people think.
Answer: A small scaffolding tower might be your best option. This will give you the height and safety you need.
Something like this one.

While it might be a bit expensive for just changing light bulbs you'll need it when you come to paint the ceiling in this room.
Answer: If you are spending money on renting, it could be cheaper to hire an electrician.  Think of going to pick up the ladder, moving furniture, setting up the ladder, changing lamps, moving ladder / furniture to get eyeball recessed light, blah blah blah.  I know this is a DIY site but sometimes you can hire a professional and get it done for not much more than getting everything and doing it yourself.  If that eyeball is hard to get, or what looks like another fixture on the left, then these really could make it worth it.
You can also buy your own lamps and have the electricians just do the labor only, but if the electrician supplies the lamps then they might warranty them and if a product failure happens, then you don't have to mess with it again.
Whatever you do, use a LED lamp and a manufacture that you are familiar with.  Newer technology LED's cost more than older technology and the biggest difference between the two is the lumen output.  Normally DIY's will have brand names and they will be older technology lamps.  Use a color of 2700 to 3000 kelvins that will be about the same as incandescent colors (warmer).  Good Luck!
Answer: Like shirlock holmes said, the extension pole kits work great. I had a house once with several very high ceilings, and I already had a nice paint extension handle. Bought something like below and the suction cup worked great for changing all kinds of bulbs.
Comment: Do these work when the bulb isn't pointing down?
Comment: Some of mine where at a slight angle with the suction cup, and it worked fine. But at maybe 45 degrees, not too sure how good it would work.
Answer: Very high ones are sometimes accessed from above. We have them in our entrance and the ceiling space above has a 10x2 plank in between the two rows of lights. You crawl out over it to change the bulbs or fittings from above.
Answer: Use a pool noodle attached to a paint roller extension pole as long as it is the small bulbs it will fit right in the center of the noodle and unscrew and screw back in


Any way to override the managedQuery method to include a limit param when using a self-made content provider?

Question: I've built my own content provider and I've run into an instance where I need to execute a query and include a limit param.
The method call to managedQuery doesn't include this param and there fore I see no way to implement this w/o somehow overriding the managedQuery method?
I've created a second query method in my content provider which accepts an additional param, the limit param but I don't think I can make the managedQuery method call this custom query method of my content provider.
What's the best way to do this?
For reference, here is my content provider class...
    package com.isi.sa;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.isi.sa.SATest.Questions;
import com.isi.sa.SATest.Scores;

public class SAContentProvider extends ContentProvider {
  private static final String TAG            = "SAProvider";
    private static final String DATABASE_NAME      = "sa.db";
    private static final int DATABASE_VERSION      = 1;
    private static final String QUESTIONS_TABLE_NAME  = "questions";
    private static final String SCORES_TABLE_NAME    = "scores";

    private static HashMap<String, String> sQuestionsProjectionMap;
    private static HashMap<String, String> sScoresProjectionMap;

    private static final int QUESTIONS = 1;
    private static final int QUESTION_ID = 2;
    private static final int SCORES = 3;
    private static final int SCORE_ID = 4;

    private DatabaseHelper mOpenHelper;
    private static final UriMatcher sUriMatcher;

  @Override
  public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
    return true;
  }

  @Override
  public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    switch (sUriMatcher.match(uri)){
    case QUESTIONS:
      qb.setTables(QUESTIONS_TABLE_NAME);
      qb.setProjectionMap(sQuestionsProjectionMap);
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Questions.DEFAULT_SORT_ORDER;
      break;

    case QUESTION_ID:
      qb.setTables(QUESTIONS_TABLE_NAME);
      qb.setProjectionMap(sQuestionsProjectionMap);
      qb.appendWhere(Questions._ID + "=" + uri.getPathSegments().get(1));
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Questions.DEFAULT_SORT_ORDER;
      break;

    case SCORES:
      qb.setTables(SCORES_TABLE_NAME);
      qb.setProjectionMap(sScoresProjectionMap);
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Scores.DEFAULT_SORT_ORDER;
      break;

    case SCORE_ID:
      qb.setTables(SCORES_TABLE_NAME);
      qb.setProjectionMap(sScoresProjectionMap);
      qb.appendWhere(Scores._ID + "=" + uri.getPathSegments().get(1));
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Scores.DEFAULT_SORT_ORDER;
      break;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

        // Get the database and run the query
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

        // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
  }

  public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String limit) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    switch (sUriMatcher.match(uri)){
    case QUESTIONS:
      qb.setTables(QUESTIONS_TABLE_NAME);
      qb.setProjectionMap(sQuestionsProjectionMap);
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Questions.DEFAULT_SORT_ORDER;
      break;

    case QUESTION_ID:
      qb.setTables(QUESTIONS_TABLE_NAME);
      qb.setProjectionMap(sQuestionsProjectionMap);
      qb.appendWhere(Questions._ID + "=" + uri.getPathSegments().get(1));
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Questions.DEFAULT_SORT_ORDER;
      break;

    case SCORES:
      qb.setTables(SCORES_TABLE_NAME);
      qb.setProjectionMap(sScoresProjectionMap);
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Scores.DEFAULT_SORT_ORDER;
      break;

    case SCORE_ID:
      qb.setTables(SCORES_TABLE_NAME);
      qb.setProjectionMap(sScoresProjectionMap);
      qb.appendWhere(Scores._ID + "=" + uri.getPathSegments().get(1));
      if (TextUtils.isEmpty(sortOrder)) sortOrder = Scores.DEFAULT_SORT_ORDER;
      break;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

        // Get the database and run the query
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder, limit);

        // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
  }

  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {
        ContentValues values;
        SQLiteDatabase db;
        long rowId;

        if (sUriMatcher.match(uri) != QUESTIONS && sUriMatcher.match(uri) != SCORES) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (initialValues != null){
          values = new ContentValues(initialValues);
        }
        else{
          values = new ContentValues();
        }

    switch (sUriMatcher.match(uri)){
    case QUESTIONS:
          if (values.containsKey(Questions.QUESTION) == false) values.put(Questions.QUESTION, "");
        if (values.containsKey(Questions.QUESTION) == false) values.put(Questions.ANSWER, -1);
        if (values.containsKey(Questions.OPTION1) == false) values.put(Questions.OPTION1, "");
        if (values.containsKey(Questions.OPTION2) == false) values.put(Questions.OPTION2, "");
        if (values.containsKey(Questions.OPTION3) == false) values.put(Questions.OPTION3, "");
        if (values.containsKey(Questions.OPTION4) == false) values.put(Questions.OPTION4, "");
        if (values.containsKey(Questions.OPTION5) == false) values.put(Questions.OPTION5, "");
        if (values.containsKey(Questions.OPTION6) == false) values.put(Questions.OPTION6, "");
        if (values.containsKey(Questions.OPTION7) == false) values.put(Questions.OPTION7, "");
        if (values.containsKey(Questions.OPTION8) == false) values.put(Questions.OPTION8, "");
        if (values.containsKey(Questions.OPTION9) == false) values.put(Questions.OPTION9, "");
        if (values.containsKey(Questions.OPTION10) == false) values.put(Questions.OPTION10, "");

          if (values.get(Questions.QUESTION).toString().length() > 0 &&
            values.get(Questions.ANSWER).toString() != "-1" &&
            values.get(Questions.OPTION1).toString().length() > 0){
            db = mOpenHelper.getWritableDatabase();
            rowId = db.insert(QUESTIONS_TABLE_NAME, Questions.QUESTION, values);
            if (rowId > 0) {
                Uri noteUri = ContentUris.withAppendedId(Questions.CONTENT_URI, rowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                return noteUri;
            }
          }
          break;

    case SCORES:
        if (values.containsKey(Scores.SCORE) == false) values.put(Scores.SCORE, -1);
        if (values.containsKey(Scores.DATE_CREATED) == false) values.put(Scores.DATE_CREATED, DateFormat.getDateTimeInstance().format(new Date()));

          if (values.get(Scores.SCORE).toString() != "-1"){
            db = mOpenHelper.getWritableDatabase();
            rowId = db.insert(SCORES_TABLE_NAME, Scores.SCORE, values);
            if (rowId > 0) {
                Uri noteUri = ContentUris.withAppendedId(Questions.CONTENT_URI, rowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                return noteUri;
            }
      }
      break;
    }

        throw new SQLException("Failed to insert row into " + uri);
  }

  @Override
  public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;

    switch(sUriMatcher.match(uri)){
    case QUESTIONS:
            count = db.update(QUESTIONS_TABLE_NAME, values, where, whereArgs);
            break;

    case QUESTION_ID:
            String questionId = uri.getPathSegments().get(1);
            count = db.update(QUESTIONS_TABLE_NAME, values, Questions._ID + "=" + questionId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
      break;

    case SCORES:
            count = db.update(SCORES_TABLE_NAME, values, where, whereArgs);
      break;

    case SCORE_ID:
            String scoreId = uri.getPathSegments().get(1);
            count = db.update(SCORES_TABLE_NAME, values, Scores._ID + "=" + scoreId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
      break;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

        getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }

  @Override
  public int delete(Uri uri, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;

    switch(sUriMatcher.match(uri)){
    case QUESTIONS:
            count = db.delete(QUESTIONS_TABLE_NAME, where, whereArgs);
            break;

    case QUESTION_ID:
            String questionId = uri.getPathSegments().get(1);
            count = db.delete(QUESTIONS_TABLE_NAME, Questions._ID + "=" + questionId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
      break;

    case SCORES:
            count = db.delete(SCORES_TABLE_NAME, where, whereArgs);
      break;

    case SCORE_ID:
            String scoreId = uri.getPathSegments().get(1);
            count = db.delete(SCORES_TABLE_NAME, Scores._ID + "=" + scoreId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
      break;

    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }

        getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }

  @Override
  public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case QUESTIONS:
            return Questions.CONTENT_TYPE;
        case QUESTION_ID:
            return Questions.CONTENT_ITEM_TYPE;
        case SCORES:
            return Scores.CONTENT_TYPE;
        case SCORE_ID:
            return Scores.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
  }

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
          db.execSQL("CREATE TABLE questions ("
              + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
              + "question TEXT,"
              + "answer INTEGER,"
              + "option1 TEXT,"
              + "option2 TEXT,"
              + "option3 TEXT,"
              + "option4 TEXT,"
              + "option5 TEXT,"
              + "option6 TEXT,"
              + "option7 TEXT,"
              + "option8 TEXT,"
              + "option9 TEXT,"
              + "option10 TEXT);");

            db.execSQL("CREATE TABLE scores ("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "score NUMERIC,"
                + "date_created TEXT);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
        }
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(SATest.AUTHORITY, "questions", QUESTIONS);
        sUriMatcher.addURI(SATest.AUTHORITY, "questions/#", QUESTION_ID);
        sUriMatcher.addURI(SATest.AUTHORITY, "scores", SCORES);
        sUriMatcher.addURI(SATest.AUTHORITY, "scores/#", SCORE_ID);

        sQuestionsProjectionMap = new HashMap<String, String>();
        sQuestionsProjectionMap.put(Questions._ID, Questions._ID);
        sQuestionsProjectionMap.put(Questions.QUESTION, Questions.QUESTION);
        sQuestionsProjectionMap.put(Questions.ANSWER, Questions.ANSWER);
        sQuestionsProjectionMap.put(Questions.OPTION1, Questions.OPTION1);
        sQuestionsProjectionMap.put(Questions.OPTION2, Questions.OPTION2);
        sQuestionsProjectionMap.put(Questions.OPTION3, Questions.OPTION3);
        sQuestionsProjectionMap.put(Questions.OPTION4, Questions.OPTION4);
        sQuestionsProjectionMap.put(Questions.OPTION5, Questions.OPTION5);
        sQuestionsProjectionMap.put(Questions.OPTION6, Questions.OPTION6);
        sQuestionsProjectionMap.put(Questions.OPTION7, Questions.OPTION7);
        sQuestionsProjectionMap.put(Questions.OPTION8, Questions.OPTION8);
        sQuestionsProjectionMap.put(Questions.OPTION9, Questions.OPTION9);
        sQuestionsProjectionMap.put(Questions.OPTION10, Questions.OPTION10);

        sScoresProjectionMap = new HashMap<String, String>();
        sScoresProjectionMap.put(Scores._ID, Scores._ID);
        sScoresProjectionMap.put(Scores.SCORE, Scores.SCORE);
        sScoresProjectionMap.put(Scores.DATE_CREATED, Scores.DATE_CREATED);
    }
}

Answer: If your consumer of the content provider is in the same application as the content provider itself, don't use the content provider -- go straight to the database. ContentProvider is designed for inter-process communication, so it adds overhead and limits your API.
Comment: The only problem I see with not using content providers is an easy mechanism to observe content.. Its easy with content providers because when you get an update/insert you can notify the content resolver the change at the given URI.. How do you do this without using content providers I have no idea..
Comment: Thanks. I am using it for the same application. I'll look into just using a SQLiteOpenHelper then.
Comment: Use a content provider if your database is being used by more than one app or thread... it will make your life alot easier.


One button or two?

Question: I've got a web app where users can create two different kinds of similar things and I'm trying to decide whether to have two buttons, or one button and then present a choice as part of the resulting form. E.g.:
<code> [Create Primary Ownership] [Create Secondary Ownership]
</code>
vs.
<code>[Create Ownership]   ->    (x) Primary    ( ) Secondary
</code>
I like the second one better even though it requires an extra click -- it's more scalable and less cluttered. The situation is more complex, though, because in one version of our product (for a particular set of users), the objects being created are labeled as above, but for a second set of users, the labels reflect the underlying structure better:
<code>[Create Team]  [Grant Secondary Access]
</code>
vs.
<code>[Create Team / Grant Access]    ->   (x) Team    ( ) Secondary Access
</code>
I hate the slash in "Create Team / Grant Access".
Comment: the first example appears to be two 'modes' of the same task. The second example appears to be two different tasks. As such, I'd keep them separate buttons.
Comment: @sprugman When you say "as part of the resulting form" is that implying that there is more the user will fill out after clicking the create ownership button? Will there be common fields for the both?
Answer: Two buttons
Two different operations. "Cluttered" is subjective. Best to do a paper test with a few users of course, but based on the information given I would find the second option confusing, while choosing one of two buttons seems obvious.
As a developer, I'm suspicious of anything labeled 'primary' and 'secondary', because 'tertiary' et al is implied ;)
Comment: To combat clutter, I decided to combine those to functions with a couple others in a menu, but the solution is closer to two buttons than one.
Comment: P.S. You're right to be suspicious. ;-) In this case it's object "creator" and "others" with access to the object, so I don't think we're too likely to slide down that slope.
Answer: In General
Jakob Nielsen touts the benefits of progressive disclosure. I think this, in principal, is a question of whether or not this is 1) a primary or secondary feature, and 2) if power or simplicity is what's most needed on this page. If you want to grant more power, use separate buttons; if you want to keep it simpler, use a single button with a second step.
Use Ellipsis
If you choose to break this into two steps, be sure to add an ellipsis to the end of your button text:

download bmml source – Wireframes created with Balsamiq Mockups
Specifics
In the example you provide, it sounds like users are able to either start a group of people with access, or grant access to an existing group. It seems strange that you would go from an overview screen to grant access to a specific thing. Instead, I would follow the model you find on sites like Basecamp, or Google Docs: 1) from the index you can create a new thing, 2) from the specific thing you can edit access or other features.
In short: only have a Create Team… button, and on the Team page, have a Grant Access… button.

One button or two?


New Basement electrical wiring

Question: I'm developing my basement, I'm done doing the framing and now the electrical, do I need a new set of circuit breakers for both lights and receptacles, and if so, what type?
Comment: How can we say, knowing literally nothing about your electrical system? Revise to add details, please.
Comment: Please [edit] your question to indicate a) where you are (regulations are different in different locations.)  b) What  your current electrical setup is.
Comment: Can you please post photos of your breaker panel?
Answer: The NEC does specify verbatim that certain "rooms" get dedicated / new circuits.
For example if you are adding a laundry in the basement, then that would require a 20 amp dedicated circuit for the receptacles only, not the lights!
If you are adding a kitchenette in the basement then that would require at least (2) 20 amp dedicated circuits for the receptacles on the counter top only and/or refrigerator/wall clock outlet, no other receptacles are allowed on that circuit!
Bathroom receptacles can catch other bathrooms as long as they are not tied into the bathroom lighting.  If the receptacles and lighting are sharing the same circuit, that bathroom circuit cannot feed other bathrooms.
The sq foot of the area is a factor for the "general lighting and receptacle loads".  The formula for that is P = sq.ft x 3  e.g., 1000 x 3 = 3000 watts.   General lighting and receptacles are non-continuous loads so you do not apply the 80%.
3000 watts divided into 120 volts = 25 amps, thus you would need at least (2) 15 amp circuits for a 1000 sq ft area for the general lighting/receptacles.
The formula is out-dated too as with new lower power consuming LEDs the 3watt(sq-ft) is not giving us a proper power measurement, but currently those are the rules.
Also, certain appliances may require a dedicated circuit.
In addition the to the above, AFCI/GFCI protection should be installed.
Answer: It is certainly wiser to have lights and receptacles on separate circuits.  That way, when you're going to town with the table saw, and you trip the breaker, you aren't in the pitch black with your fingers 3 inches from a spinning saw blade.   (saw blades do not have the courtesy of instantly stopping when the power fails.  They do make saws which instantly stop if you touch them with your finger, but I doubt that detection device will work if the power cuts out).

New Basement electrical wiring


Any Office 365 REST API to sign out user of office 365?

Question: Is there any Office 365 REST API to sign out user of office 365 like Single sign out & by that way from azure active directory?
Answer: Not an API per se, but you can just have the user browse to:
https://login.windows.net/common/oauth2/logout?post_logout_redirect_uri=<some_page_in_your_app>

Whatever value you put in the post_logout_redirect_uri is where Azure will redirect the browser after logout is complete.
Comment: Just a quick addendum-- if you need to log out a user without actually redirecting them around, you can always load this logout URL in a hidden iframe, like so:

``
That will log them out when whatever page in your app loads, if its an HTML page that is.


winapi GetSystemTimes function does not fill lpIdleTime/lpKernelTime/lpUserTime

Question: I`m stuck with GetSystemTimes function. There is no any problem in c++ code, but with golang I'm getting three nils instead of expected values
My code:
package main

import (
    "log"
    "syscall"
    "unsafe"
)

var (
    modKernel32 = syscall.NewLazyDLL("kernel32.dll")
    procGetSystemTimes = modKernel32.NewProc("GetSystemTimes")
)

type SystemTimes struct {
    IdleTime   *syscall.Filetime
    KernelTime *syscall.Filetime
    UserTime   *syscall.Filetime
}

func main() {
    times, err := getSystemTimes()
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("idle=%v, kernel=%v, user=%v", times.IdleTime, times.KernelTime, times.UserTime)
}

func getSystemTimes() (times SystemTimes, err error) {
    res, _, err1 := procGetSystemTimes.Call(uintptr(unsafe.Pointer(times.IdleTime)), uintptr(unsafe.Pointer(times.KernelTime)), uintptr(unsafe.Pointer(times.UserTime)))
    if res != 1 {
        return times, err1
    }
    return
}

It's super simple and very similar to syscall`s GetProcessTimes function from stdlib.
And look, what my program prints:
idle=<nil>, kernel=<nil>, user=<nil>

Why? I expect error or result, why my fields are empty?
Confguration: win8 x64, go1.4.2 windows/amd64
Answer: You're passing the address of nil fields to the function.
Either make it point directly to the Filetime struct or initialize all 3 fields before passing them:
type SystemTimes struct {
    IdleTime   syscall.Filetime
    KernelTime syscall.Filetime
    UserTime   syscall.Filetime
}
.....
res, _, err1 := procGetSystemTimes.Call(uintptr(unsafe.Pointer(&times.IdleTime)), uintptr(unsafe.Pointer(&times.KernelTime)), uintptr(unsafe.Pointer(&times.UserTime)))

Output:
┌─ oneofone@Oa [/tmp]
└──➜ env CC=i686-w64-mingw32-gcc CGO_ENABLED=1 GOOS=windows GOARCH=386 go build -a /tmp/syscall.go; and wine syscall.exe
2015/05/09 22:31:53 idle={1292275456 39}, kernel={1436840864 41}, user={3496565408 2}

playground


Not getting correct state of groups in expandable list view after deleting an element

Question: I am passing arraylist to my expandable list adapter. when i delete an element from the specific location in arraylist and then notifies the adapter with notifyDataSetChanged(), i am not getting correct state of grp in expandable list view.
For Ex:
1 - My arraylist is having 5 elements and adaper is displaying 5 view on display.
2 - Initially all the groups will be in collapsed state.
3 - i am expanding first group.  [grp 1 - expanded, grp 2 - collapsed, grp 3 - collapsed, grp 4 - collapsed, grp 5 - collapsed].
4 - now i am deleting first grp. After deleting, my arraylist will have 4 elements and grp 2 becomes grp1, grp 3 becomes grp 2 and so on.
5 - After deleting,
the correct state of grp shd be [grp 1 - collapsed, grp 2 - collapsed, grp 3 - collapsed, grp 4 - collapsed], but instead of this i am getting,
the state of the grp is [grp 1 - expanded, grp 2 - collapsed, grp 3 - collapsed, grp 4 - collapsed].
why the hell grp 1 (prev it was grp 2) got expanded??? it should be in collapsed state.
I think this is very small issue but i am unable to find solution. Kindly suggest solution. Early reply from anyone will be highly appreciated.
Answer: When you call notifyDataSetChanged(), you let the adapter know that the data has changed, but it doesn't tell anything about the views. So adapter remembers that the first group is expanded and when you notify the adapter of changes it takes the new data and fills the ExpandableListView with it, thus keeping the first group expanded.
A solution would be to manually control which groups are expanded, see here (look at restoring the state):
https://stackoverflow.com/a/10905158/2197087
Comment: i have done as you said, but yet facing the same problem. even after calling Oncollapsegroup method for all groups, adapter is still calling getchildview method for one group and that is getting expanded.


Live Chat - Where to Place Button on a Customer Service Portal

Question: Short background is that we're working with a self service portal. The home page will feature a call-to-action of a search form for their queries e.g. "What is the flexi time policy"
Below this there will be top 10 lists of newly added FAQs, most popular and relevant sections.
Once a search has been done, the results will be appear and going into one of the results will present the user with a knowledge-base article and/or a FAQ.
In addition we will have forms the user fills out e.g. a flexi leave form. We will have FAQs listed along with examples
We will be introducing a web chat feature. My question is considering that the whole site is based around self service, FAQs and knowledgebases, should the "Web Chat" option be available on each and every page or should it be present once a search has been made or more wider than that, when they're not on the home page, based on the fact we want them to find the information themselves first?
I have reviewed other similar questions but none seem to be around a website dedicated to help/support that encourages users to self-serve.
Example of websites that will be close to what we will have:

Thanks
Comment: Could you edit your post with an image of what you guys have now? It would make it a lot easier by having a visual representation. :)
Comment: Sorry - I did mean to add that is in process of being designed. I'll try and find an example of a design close to what we want and add it
Answer: (I can't comment to ask some side questions so I will stick to making some assumptions and establishing a base answer).
Your question reminded me of the typical question in the bottom right hand corner of the page. Would it be a good fit for you? I'd say yes if it also included FAQ's and other of the help guides you've mentioned as well it's probably something the user will like having close by when needed.
In my UX workshop (a while back) we did an exercise very much in line with your question. The challenge was to visit an airline company website, view the flights available and then try to ask a question or view some help guides. "seasoned" users would likely just google "airline name"+"support" or "help" or "costumer service" and get the phone number or something. But for the rest the instinct seems to be to check the bottom of the page and look for information there.
So what do you think fits with the design of your app? An omnipresent button generally works better on bigger screens. Take this very page for instance, this text is centered and, if your screen is big enough (or you're not on mobile) you should see huge whitespace to the left and right... although they should generally be kept that way to create a sense of space I would find you could easily get away with a little "help" question ma
Comment: Would you suggest it to be floating on the bottom or in the footer? My worry is that if it's stuck in the footer, unless the users scrolls down, it won't be present whereas if it's in the header, it'll be fairly obvious. With that said, I'm not sure whether it should be on *every* page and therefore entice users to use it rather than self-serving
Comment: that really depends on your design of the page. As for it being only on the first page or some page or all it depends on your site map... does it have a big site map or simple pages that work SPA'ish like? If your header isn't too crowded it might work. I would say it's safe to assume that if a user needs help he/she will look at the bottom in the footer.
Answer: Without knowing how a FAQ page is designed I'd still suggest adding a live chat button inside the page.
The reason behind having the button inside the FAQ are:

To lessen the strain on the service from users who are too lazy to first search.
To keep as clean of a design as possible in the search (keep the search page intuitive). This also lessens the sense of intrusion that a button / form could incise in a user.

You can add the live-chat button to the contact form too, so that users can get chatting when navigation from your contact page.
Overall I simply believe it's a better design choice both from a managerial point of view and design point of view to focus on the functionality of your search-form in the 'main page' and allow a user to find a live chat window when having navigated to a FAQ.
Simply display something like "Did you not find what you were looking for? Ask an adviser in our live chat" as the text on a button / in a form might be as intuitive and would definitely be less intrusive.
Sky does something similar where they show a little prompt in your top-right window (floats with you as you scroll) when you are looking at their FAQ and adviser is available.
Here is a horrible mock-up of their display I made in paint:
Comment: I understand that idea too, but I think it's important to really consider the implications that might have on the quality of the service (assuming you have a lot of users). I'm sure as hell going to be clicking on that chat rather than search around a forum if I get the chance. Mainly because it makes my experience a lot easier.
Comment: Thanks - I am thinking along these lines but there seems to be a strong call to have it present in the footer as an option. Might have to go through some A/B testing to see which yields the best results.
Comment: What you could do, as a sort of middle ground is to do a bit of case-study by checking how many of the users will default to using the service and how many of them will still be searching. So basically make a test-run by adding it in the default footer, then change it a few days later to be in the FAQ-page. That way you might see what the user is most incited to do and as such implement it in a fashion that most would benefit your system.
Comment: I agree with the "put the button on the contact page" thing. If you make vieweable everywhere then people will imediately use that instead of actually looking for the answer themselves, which may not be what you want and will cause more clutter in the live chat. If it's in the contact (or the help page) it will serve more as a last ressort, leaving the user to search the FAQ's or foruns as a quicker way to get his answer.
Answer:
should the "Web Chat" option be available on each and every page (...) based on the fact we want them to find the information themselves first?

Let the "Web Chat" option show on every page.
When clicked, check if the user has actually made any search at all.

If they have, proceed to Web Chat.
If they haven't:

Show a very simple "What's your question?" / "What do you want to talk about?" dialog.
Make a search for them, using their input.

If 0 results, proceed to Web Chat.
If x > 0 results, show e.g. the top 5 results with something along the lines of "We've found this pages related to your question. Not what you're looking for? Click here for a live chat session."

EDIT: just noticed you already had an accepted answer! I hope I helped anyway :)
Comment: I'll see if we can get that logic into the system but I feel people will just go through to chat if they selected it
Comment: Yes, some people will refuse to interact with your page and they will abuse your chat line. But you can't avoid that -- that's just how some people is. With my proposed solution you at least get a chance to _educate_ the rest of them in searching first (as long as your search engine results are any good), while taking some load off your Web Chat team every time one of the non-abusive users finds a fitting response in that last-resort results page.


How to show multiple images in one div which have same date

Question: When Multiple images are uploaded at a time..
I want to access all those images which are of same date..
$aa  = "SELECT imgdate  FROM db WHERE pid=1";

foreach ($aa as $value) {

 $dd ="SELECT images FROM db WHERE imgdate=$value";

}

All the images must be shown with same date..
thanks..
Comment: What happens when you run that query? You have not provide all of the code you are using. What you posted simply put the contents of the query into a variable.
Comment: Please show us example code. What have you tried already? This is to less information to help you.
Comment: this is what i have tried..
Comment: Hi, I would recommend that you read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and update your question accordingly. In it's current state, it's impossible for anyone to give you a proper answer since we have no idea what the expected result should look like, what you've tried (more than a single query) and what result you're currently getting.
Comment: only thing I see that could be wrong in your sql, is that the db name would need ` db` to make sure its the correct one it gets, else your sql is correct
Comment: i gets results in array..
Comment: of course if there is more than one with that pid
Answer: To select all images uploaded today, run this query:
$dd = ("SELECT images FROM db WHERE date_column = '2018-08-23'");

Replace date_column with your date column name.
I am assuming your date format is 'Y-m-d', replace if yours is different.
Whenever you want to select items that share the same attribute e.g name, id, date etc, simply specify the attribute name and the attribute value in your query.
So, if I want to select images that have the same title, I would simply do:
$dd = ("SELECT images FROM db WHERE title_column = 'Cool Images'");

Your own query works but you will get images that have the same pid.
Comment: A nice, clear and easy to read solution. To make this answer better, maybe explain what you have done and why it will now work.
Comment: @LewisBrowne Select images from database where date_column equals to the given date. The whole query is just a few English words.
Comment: @kry We both understand what it means but its for the people that may not understand it.
Comment: @LewisBrowne ... Thanks mate... I've made some edit, I hope that addresses your request.


Rails - sending multiple http requests to a another server

Question: 1000 users make a request to my Rails server at exactly the same time. For each user, I need to make 50 http requests to other servers, each taking 1 second to respond. How do I go about coding my application so that I can respond to the users as quickly as possible?
(Note: the app hasn't launched and the numbers are hypothetical.)
Comment: WTF. why do you need to make 50 http request PER USER?!
Comment: Ah, I was worried this would happen...! The question is to help me design the application.  If there is a way of responding to all of these users very quickly, then I don't need to worry about how many requests I make per user (and 50 would not be unreasonable for some users if there is no reason to cap it). What would you suggest as a cap then and why? And how would you then answer the question?
Comment: see the answer i wrote :)
Comment: I've edited my question slightly.  I appreciate your answer, but I cannot seem to ask the question in such a way that I get the answer I want.  I would expect the answer to talk about threading and possibly processes, whether I should use threading at a User level or Application level, etc. For example, if the optimum number of threads for a single user is 10, is it still the optimum number of threads per user when multiple users connect to the site?  If not, why not, and how do I optimise?  I want to really understand this.
Answer: I think you need to implement a Job queuing system with ActiveJob and for example Sidekiq.
So your workers can make these 50 http requests.
You'll have to tell the user to be patient while your server is making these requests. This way, the user get's instantly a message which says that there's something going on, you could then notify the user if the jobs have finished.


How to center text inside column?

Question:

AMAZING DANCE

Lorem ipsum dolor sit amet consectetur adipisicing elit.
 Corrupti perferendis cumque a provident? Ipsam, architecto?

        READ MORE

So I am trying to center the text inside vertically and horizontally and also I wanna remove the spacing. What am I doing wrong?
It looks like this:
Answer: mx-auto utility class is shortcut for margin: 0 auto which by design centers content only horizontally. Simplest way to center content is by using d-flex with combination of justify-content-center and align-items-center. Since flex displays its ascendants as inline, you have to additionally wrap them in an another container:

test

AMAZING DANCE

            Lorem ipsum dolor sit amet consectetur adipisicing elit.

            Corrupti perferendis cumque a provident? Ipsam, architecto?

          READ MORE

h-100 is there only to strech container to all available height.
Comment: i did this and its centered but the text and buttons are just side by side, i want to put them below each other and also can you tell me how to fix that whitespacing near image, thanks
Comment: I edited the answer. Please check it out if it meets your conditions. Spacing around image is probably a result of a margin but you will have to inspect it yourself from where does it comes from.

How to center text inside column?


How do I use my MIDI drums in Guitar Hero World Tour for PC?

Question: I've got my electronic Fame MIDI drum connected to my PC. It supports MIDI. Now I want to use this in Guitar Hero World Tour.
GHWT does not seem to recognise my drum controller. I downloaded the drum tuning kit, and this recognises the drums and is able to send a test signal, but no luck with the actual tuning because none of the pads light up when drumming.
How do I use my MIDI drums in Guitar Hero World Tour for PC?
Answer: Guitar Hero World Tour only supports game controllers, not midi controllers. You can circumvent this by using GlovePIE.


Galaxy Nexus does not appear in device chooser dialog

Question: everyone, I would like to connect my galaxy nexus to the eclipse, which allows me to use the real device for debugging my program, however, my galaxy nexus does not appear even I have clicked on the usb debugging option in the developer mode. Can anyone give a hand to me, thank you!
Answer: Which operating system are you using?
If on Windows:

Have you installed the ADB and FastBoot? Does your device show up if you do adb devices?
If not, follow the instructions here or here.
Reconnection your device, open a console window and type: adb devices. If your device is listed in the output, Eclipse will also pick it up.
For Samsung provided firmware and drivers, check here.

If on Linux:

Follow this tutorial. You don't necessarily have to unlock the bootloader. As long as your device shows up in adb devices after adding the device identification lines in udev, followed by a udev restart with sudo service udev restart, all should be good.

Here is another tutorial that claims to install ADB automatically on both Windows, Linux and Mac. I haven't tried it myself. So it might be a good idea to peep inside the Knives-&-Forks scripts before executing them.
Comment: ok, thank you gsbabil, I have not installed this yet, so I try to fix it first.
Comment: I have installed the google USB driver, but the same thing sill happen, Windows still reply that it was unable to install my Galaxy. And I have checked for firmware by Samsung, it seems none of those firmware match my need.
Comment: @user1502740: What you need is to install the USB driver for ADB correctly first. Please follow the steps explained here http://developer.android.com/tools/extras/oem-usb.html depending your Windows version.
Comment: I have followed it and successfully installed it, and open the usb debugging option, but the device still not appear, and using adb devices command shows that no device is attached
Comment: I would like to ask is it because Samsung devices need Samsung USB driver, because currently in the sdk/extras folder, it is google USB driver inside, so it will be fined if I install the Samsung USB driver here http://stackoverflow.com/questions/8371787/eclipse-doesnt-show-my-galaxy-nexus-with-android-4?rq=1 into the extras foler, then the problems will be solver?I have not installed it then, since I am not sure wheter it will affect the existing one
Comment: it is okay now, I think probably it is because Samsung devices need a independent USB driver, so it did not work before, thank you for the help you have given to me!
Answer: Make sure the USB driver is installed.  Instructions can be found here.
Comment: ya, I have read this and follow the guideline, however, at the last step, it replys me "Windows was unable to install your Galaxy"
Answer: You need to install the Galaxy Nexus driver from Samsung
Galaxy Nexus USB Driver


limit of a recurrent serie

Question: I would like to find to determine the limit for $u_n$ which I determined that it's a decreasing series and that $v_n$ is an increasing one.
let $a >0$  And  $b>0$  .

$u_0=a And v_0=b$

$u_{n+1}=\frac{u_n+v_n}{2}$  and   $v_{n+1}=\frac{2}{\frac{1}{u_n}+\frac{1}{v_n}}$
Comment: Hint 1) $u_{n+1}v_{n+1} = u_nv_n$. 2)  $\lim\limits_{n\to\infty} (u_n - v_n ) = 0$. From this, you can deduce the limit is the GM.
Answer: Expanding
 achille hui's comment.
$\begin{array}\\
u_{n+1}
&=\dfrac{u_n+v_n}{2},\\
v_{n+1}
&=\dfrac{2}{\frac{1}{u_n}+\frac{1}{v_n}}\\
&=\dfrac{2u_nv_n}{u_n+v_n}\\
&=\dfrac{2u_nv_n}{2u_{n+1}}\\
u_{n+1}v_{n+1}
&=u_nv_n\\
v_{n+1}
&=\dfrac{u_nv_n}{u_{n+1}}\\
u_1, v_1
&=a, b\\
u_1v_1
&=ab\\
&=u_nv_n\\
v_n
&=\dfrac{ab}{u_n}\\
u_{n+1}-v_{n+1}
&=\dfrac{u_n+v_n}{2}-\dfrac{ab}{u_{n+1}}\\
&=\dfrac{u_n+v_n}{2}-\dfrac{2ab}{u_{n}+v_n}\\
&=\dfrac{(u_n+v_n)^2-4ab}{2(u_{n}+v_n)}\\
&=\dfrac{(u_n-v_n)^2}{2(u_{n}+v_n)}\\
&=\dfrac{u_n-v_n}{2}\dfrac{u_n-v_n}{u_{n}+v_n}\\
|u_{n+1}-v_{n+1}|
&=|\dfrac{u_n-v_n}{2}||\dfrac{u_n-v_n}{u_{n}+v_n}|\\
&<|\dfrac{u_n-v_n}{2}|\\
&\to 0\\
\end{array}
$
Therefore
$u_n, v_n
\to \sqrt{ab}
$.
Comment: Got it , all what I need was digging deeper to get the limit.
$Thanks $

limit of a recurrent serie


Why do some of my blueprints stop working?

Question: Every once in a while, some of the blueprints in my UE4 project will stop working. When I try to open them, I get this screen:
Image
I have found no way to fix this except remaking the blueprint from scratch. Is this a bug or am I doing something wrong?
Answer: I'm not sure why this problem happens, but it might be just a Mac problem.
The solution is clicking
Window -> Class Defaults -> Open Full Blueprint Editor.
(On the top menu bar)
Hope this helped. I got the answer from Epic Game's Forums
Comment: Thanks! I'm not on Mac but it still works.


Download files modified after given time with sftp in bash

Question: I am writing a bash script that will get files from one directory of remote host.
Here, I want to get files that were modified after given time.
sftp userme@remote_host_addr:/somedirectoryonremoteserver
> mget

Here, how can I pass the timing to sftp command to get only files whose modified time is greater than given time.
Answer: It's rather difficult to implement this using the OpenSSH sftp client.
You would have to:

list the directory using ls -l command;
parse the results (in shell or other script) to find names and times;
filter the files you want;
generate another sftp script to download (get) the files you found.

A way easier and more reliable would be to give up on the command-line sftp. Instead, use your favorite scripting language (Python, Perl, PHP) and its native SFTP implementation.
For an example, see:
Download files from SFTP server that are older than 5 days using Python

Or use a more capable SFTP client.
Comment: I achieved it using rsync (only modified files will copy) since it was difficult to implement using sftp


How to customize the Spinner dropdown view

Question: Is it  possible to customize the spinner drop-down view . Default spinner drop-down view has adapter view . I want change that view to have my own text view or some thing like this.
Comment: see this I hope this help u http://mrbool.com/how-to-customize-spinner-in-android/28286
Comment: Are you using CustomAdapter or ArrayAdapter?
Comment: You actually put your customization in the adapter.  It has methods getView and getDropDownView and getDropDownView which return a view.  In these methods you create and init your text view and return it.
Answer: Add this inner class in your class and modify it as you please.
public class MyAdapter extends ArrayAdapter<String>{

        public MyAdapter(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }

        @Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.xml.row, parent, false);
            TextView label=(TextView)row.findViewById(R.id.company);
            label.setText(strings[position]);

            TextView sub=(TextView)row.findViewById(R.id.sub);
            sub.setText(subs[position]);

            ImageView icon=(ImageView)row.findViewById(R.id.image);
            icon.setImageResource(arr_images[position]);

            return row;
            }
        }

And add this adapter to your spinner:
    Spinner mySpinner = (Spinner)findViewById(R.id.expandableImagesList);
    mySpinner.setAdapter(new MyAdapter(NewEventActivity.this, R.xml.row, strings));

And also create a new xml and add all the things you want your spinner to contain:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/icon"/>
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textStyle="bold"
         android:id="@+id/company"
         android:text="CoderzHeaven"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:text="Heaven of all working codes"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>

This is my code so you have to change it for your needs
Answer: You can customize the drop-down view by overriding getDropDownView method from your ArrayAdapter.
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
     ...
}

Comment: @waqasalam Can you post any example code to understand ,how it is  working?
Answer: You can do
arrayAdapter.setDropDownViewResource(R.layout.your_layout);

where your_layout is your XML containing only a TextView


C# BotFramework Prompt.Confirm displays too many attempts exception

Question: I was recently developing a chatbot using Microsoft's botframework.  I am using prompt.confirm to take user's yes/no input but it shows too many attempts exception when I write basic yes/no. I don't want my bot to display too many attempts exception instead I want to handle it internally. Here's my code.
[LuisIntent("None")]
public async Task NoneIntent(IDialogContext context, LuisResult result)
{
    try
    {
        PromptDialog.Confirm(context, NextQuestionAsync, QuestionPrompt, attempts: 1, promptStyle: PromptStyle.Auto);
    }
    catch (Exception ex)
    {
        await context.PostAsync("Something really bad happened.");
    }
}

public async Task NextQuestionAsync(IDialogContext context, IAwaitable<bool> result)
{
    try
    {
        if (await result)
        {
            await context.PostAsync($"Ok, alarm 0 disabled.");
            //context.Wait(NoneIntent);
        }
        else
        {
            await context.PostAsync("You Said No");
        }
    }
    catch (Exception e)
    {

    }
}

Comment: https://github.com/Microsoft/BotBuilder/issues/1757
Answer: You can just override the TooManyAttempts message by passing your own string in the PromptOptions constructor, which is later used here to display the message.
Also, have in mind that in the case of the TooManyAttempts exception, the way to handle it is in the try/catch of the ResumeAfter method (in this case your NextQuestionAsync method), surrounding the await and not in the caller method.
Answer: I resolved this issue by overriding the PromptOptions constructor, Thanks to ezequiel. I used PromptDialog.Choice to achieve it however I could also have done it with confirm. Here's what I did
    List<string> questions = new List<string>();
    questions.Add("Yes"); // Added yes option to prompt
    questions.Add("No"); // Added no option to prompt
    string QuestionPrompt = "Are you sure?";
    PromptOptions<string> options = new PromptOptions<string>(QuestionPrompt, "", "", questions, 1); // Overrided the PromptOptions Constructor.
   PromptDialog.Choice<string>(context, NextQuestionAsync, options);

Comment: PromptConfirm is better for yes/no question. This is kind of a duplicate of my answer. And you are not overriding the constructor; that's a wrong statement.
Comment: Sure... same pattern you did in other questions. Nevermind


How to make a unit test for a method that is catching Exception.class?

Question: I am unit testing a class which is as below :
class ClassUnderTest {
    public SomeOtherClass var;
    public String methodUnderTest(){
        try {
            //call to some other method that throws CustomException
            String localvariable = var.someOtherMethod() //throws CustomException
            // generic operations on localvariable which can throw Exception
        } catch (CustomException e) {
            s.o.p(e);
        } catch (Exception e) {
            s.o.p(e);
        }

    }
}

The problem arises when I have to test the methodUnderTest for catching Exception.class. I can not mock SomeOtherClass to throw Exception as Exception is a checked exception and someOtherMethod throws only CustomException.
How can I make a test case for this scenario ?
Comment: See: http://stackoverflow.com/questions/3762047/throw-checked-exceptions-from-mocks-with-mockito

Your API is saying that the only checked exception that someOtherMethod will throw is `CustomException`. But then trying to throw a different checked Exception from the body.

If you want to catch runtime exceptions (unchecked), then configure your mock to throw a `new RuntimeException()`, or add another checked Exception type (`Exception`) to the method signature.
Comment: But those things donot throw checked exceptions, only runtime exceptions.  You cannot test errors in code like that, unless you can feed it bad inputs (like making it divide by zero, or giving it a `null` reference).
Comment: someOtherMethod throws CustomException. But the methodUnderTest does some generic operations after invoking someOtherMethod. It is here that the methodUnderTest is susceptible to an Exception like NPE or IndexOOB. I want to create a test for such scenario. If such a exception is raised, it is being caught.
Comment: Thanks @john16384

I am a noob to Unit testing. Hence I am seeking to know as much as I can.
Would it be a good practise to make a test case with bad inputs ? One obvious advantage that I get from such test case is that my coverage increases. But I don't want to increase the coverage, just for the sake of increasing it. Do these type of cases add quality to the TestClass ?
Comment: To be honest, it is bad practice to catch exceptions you are not planning to handle (logging is not handling them).  Things like a NPE or Division by zero, you should just let bubble up to a very high level (like the request level or user action level), and then handle them all there (by logging them and/or informing the user of a fatal error).  If you catch those exceptions, what are you going to return as result?  Something that makes sense or some garbage value that causes problems later on?
Answer: You donot show the signature of someOtherMethod, but if it doesn't declare any checked exceptions then it cannot throw any checked exceptions, so why test for them.
Just throw a RuntimeException to test the 2nd catch block instead.
Comment: someOtherMethod throws CustomException. But the methodUnderTest does some generic operations after invoking someOtherMethod. It is here that the methodUnderTest is susceptible to an Exception like NPE or IndexOOB. I want to create a test for such scenario. If such a exception is raised, it is being caught.
Comment: NPE is a RuntimeException which isn't checked.
Answer: The other exceptions you listed in your comment:

But the methodUnderTest does some generic operations after invoking someOtherMethod. It is here that the methodUnderTest is susceptible to an Exception like NPE or IndexOOB

Both NullPointerException and IndexOutOfBoundsexceptions are cases of the unchecked Exception type RuntimeException. You can throw an unchecked exception from your mock by instructing your mock to throw a new RuntimeException() (Depending on what mocking framework you're using, the usage will be different).
If you end up doing this, you should also modify your catch to catch RuntimeExceptions instead of Exceptions to be more clear about the intent of your try/catch block.


make vector of PlainTextDocuments

Question: I have this closure, which is meant to parse one PlainTextDocument into several child PlainTextDocuments while transferring and augmenting the metadata:
segment_doc <- function(doc) {
    txt = paste0(doc, collapse=' ')
    au <- meta(doc, tag='Author');
    desc <- meta(doc, tag='description');
    ori <- meta(doc, tag='origin');
    locmeta <- attr(doc,'LocalMetaData');

    function(df){
        dfrows <- nrow(df);
        v<-rep(NA,dfrows);
        for(i in 1:dfrows) {
            a <- df[i,'after'];
            b <- df[i, 'before'];
            m <- df[i, 'meta'];

            sec <-PlainTextDocument(mkmeta(b, a, txt), author= au, description=desc, origin=ori, heading = m, localmetadata= locmeta)
            #verified using debug that sec is a 'PlainTextDocument' with the expected text and metadata
            v[i]=sec;

        }
        v #should be a vector of PlainTextDocuments, BUT it is vector of character vectors. WHY??

    }
}

which I can use as follows:
# mycorpus is a Corpus object containing PlainTextDocuments
# sections is a data.frame with 3 columns of type character named 'before', 'after' and 'meta' and 6 rows

sectioner <- segment_doc(mycorpus[[1]]);
ptv <- sectioner(sections); #expect a vector of 6 PlainTextDocuments

class(ptv);
[1] "character"
length(ptv);
[1] 6

Questions

Why is sec transformed from a PlainTextDocument object to a character vector when placed in a vector?
How can I make sectioner return a Corpus object? (a vector of PlainTextDocuments would also be fine).

I've read the documentation on tm. Yes, all of it. This shouldn't be so hard. Is there a different approach I should be using?
Comment: The reason why you get a character vector returned is, that you initialize `v` as a atomic vector which cannot carry complex objects. Instead, the objects which are put in the vector are coerced to a common atomic data type (here a character). You could initialize `v` as list with `v <- vector( length = dfrows, mode= 'list' )`.
Comment: @Beasterfield: that helps a lot. Put it as an answer and I'll accept it.
Answer: The reason why sectioner returns a character vector is because you initialize v as a atomic vector which cannot carry complex objects. Instead, the objects which are put in the vector are coerced to a common atomic data type (here a character). You could initialize v as list with
v <- vector( length = dfrows, mode= 'list' ).

make vector of PlainTextDocuments


Provide extendable Typescript interface in library

Question: I'm building a library with Typescript that should support third-party plugins. The constructor function of the library should accept the options for the core library and for all plugins, since the module will load them in the constructor.
Is it possible to provide a base Options interface that each plugin can extend to add their own properties and types, so that throughout the top-level application (which uses the library and plugins), the Options interface reflects both the core options and those of the plugins?
So with a dependency structure like this:
- user-app
|- my-library
|- my-library-plugin-a
|- my-library-plugin-b

Where my-library defines the following:
export interface Options {
  coreOption : string;
}

And my-library-plugin-a extends it as follows:
export interface PluginAOptions extends Options {
  pluginA : boolean;
}

And my-library-plugin-b extends it as follows:
export interface PluginBOptions extends Options {
  pluginB : Record<string, string>;
}

To the developer of user-app, which has all three modules in its dependencies, the Options interface as exported from my-library should look like this:
interface Options {
  coreOption : string;
  pluginA : boolean;
  pluginB : Record<string, string>;
}

So that's what their autocomplete should show, and what the Typescript compiler should check for.
Is something like this at all possible with Typescript?
Comment: @Li357 The key word in my question is 'third-party'. In other words, I can't extract the types into a shared module, since I'm not the only one who will have types. Other devs should be able to make plugins and publish them to npm as they like.
Comment: Okay, then just export your types from your library so that one can import and extend them.
Comment: My point is that plugin A and plugin B should both extend the type from the core library, and a user of all three modules should see the unified type containing the core and everything plugins A and B added. Just extending the types in the plugins is of course easy to do. But I'm looking for a way to let these extensions 'bubble up' to the top program.
Comment: I've updated my original question in an attempt to make my question clearer.
Answer: You cannot expect to get the whole extended options from the my-library.
This is not about TypeScript, but about how dependency works.
my-library knows nothing about the plugins and it supposed to.
If it somehow can export options added by the plugins, it will be depends on those plugins, making the plugin architecture pointless.
In the user-app, you should simply use the options from plugin-a and plugin-b and combines them.
const theOption: PluginAOptions & PluginBOptions = { ... }

user-app is the one who knows and decided to use plugin-a and plugin-b.
That's why it should and can use the types from those plugins.
Comment: Thanks for your answer! I figured it wouldn't be possible, but I thought I'd ask just in case there was a way to achieve this after all.
Comment: Please note: this answer is outdated, see [my answer](https://stackoverflow.com/a/77011839/2732818).
Answer: This is possible using typescript's declaration merging feature:
my-library:
export interface Options {
  coreOption : string;
}

my-library-plugin-a:
import {Options} from 'my-library';

export module 'my-library' {
    export interface Options {
      pluginA: boolean;
    }
}

my-library-plugin-b:
import {Options} from 'my-library';

export module 'my-library' {
    export interface Options {
      pluginB: Record<string, string>;
    }
}


What is the problem with Websocket and Self-Signed SSL certificate

Question: I have a project runs on intranet, so I didn't buy any SSL certificate or domain name. Instead, I created self-signed certificate. I have two layer one of which is web service/websocket and the other is view. Everything is OK for all https connections, hence all pages, but browser could not make connection with ws or wss links(was tried ports 8443,443,8080). If I write link with localhost instead of my ip, it works perfectly, but then I cannot use it from another device. I created certificete as RSA/2048. My project runs on Ubuntu 18.04. Serverside was written in Java-Spring Boot.
Comment: what is the error shown in the browser console?
Comment: Firefox can not establish connection with this URL. Maybe translation is not true, because my browser is in my language, error is too
Answer: If someone else need an answer, I got it from here. As summary, the problem is about Firefox, not about other browsers. Main reason is that Firefox do not accept certificate of wss link, in fact it is also the same certificate for the first connection link start with https. Solution is to go to the link started with wss by chancing wss to https and accept privilege of that link, and everthing works fine :)


rs-base element spawning in aframe

Question: I am trying to build a frame vr world but when i load the website i get in the top left corner a element with the class name: rs-base
the code is:

    <meta charset="utf-8">
    <title>Tracked Controllers — Networked-Aframe</title>
    <meta name="description" content="Tracked Controllers — Networked-Aframe">

    <input
      id="username-overlay"
      style="z-index: 100; bottom: 24px; left: 24px; position:fixed;"
      oninput="document.getElementById('local-avatar').setAttribute('player-info', 'name', this.value)"
    />

      <template id="camera-rig-template">

      </template>

      <template id="head-template">

      </template>

      <template id="left-hand-template">

      </template>

      <template id="right-hand-template">

      </template>

I have commented all the scripts that are already on my system to see if this caused the problem but this didnt solve the problem. I saw the element gets created at the aframe.min.js file but i dont know how to stop it from loading in
Comment: You mean the statistics?
Answer: rs-base is a class used by the stats UI. You can toggle the UI by simply adding / removing the stats attribute to/from the scene (click the button):

const scene = document.querySelector("a-scene");
const btn = document.querySelector("button")
btn.addEventListener("click", evt => {
  if (scene.getAttribute("stats")) {
    scene.removeAttribute("stats")
  } else {
    scene.setAttribute("stats", "")
  }
})

<button style="z-index: 9999; position: fixed; top: 0; left: 0">toggle</button>

rs-base element spawning in aframe


Android - Fragment using NavigationDrawer and onSavedInstanceState

Question: I'm following this to create a navigation drawer.
Inside one of my fragments, I have an EditText.
I want that the text on the EditText doesn't change if I rotate the screen.
I've tried to use Bundle savedInstanceState but it doesn't work.
I reed that I should remove the line android:configChanges from my Manifest, but I don't have that line.
I've tried with the correct answer of this question, but it's still not working for me.
So what should I do? Thanks :)
Answer: If you don't have the android:configChanges line, then Android will handle the screen rotation. Your app will get destroyed and recreated. Before the app is destroyed, Android calls onSavedInstanceState where you have a chance to save data for the recreation. When the app is recreated, the bundle passed to onCreate is not null and contains your saved state.
Try
public void onSavedInstanceState(Bundle bundle) {
    bundle.put("editTextString",et.getText().toString());
    super.onSavedInstanceState(bundle);
}

and in
public void onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null) {
         String savedText = savedInstanceState.get("editTextString");
         et.setText(savedText);
    }
}

Comment: if I try as you say, I get a "The method onSavedInstanceState(Bundle) is undefined for the type Fragment" error. If I change to super.onSaveInstanceState(bundle); it still doesn't work, and I've already tried it before :(


Hide Audio device using codeless kext

Question: I am developing a audio driver to do some custom audio processing using audio reflector driver sample code from Apple. Output from audio reflector driver is passed to real USB audio hardware device using core audio application. Now I want to hide USB audio hardware device from the system preferences so that user is not able to select the USB audio hardware output device as the default output device. Using the "SampleUSBAudioOverrideDriver" codeless kext I am able to change the name of output interface but not hide it. Any idea on how I will be able to hide  USB audio hardware output device.
Thanks in advance.
Vin Pai
Answer: After a lof of R&D on this topic, I found that codeless kext provided in the sample code, SampleUSBAudioOverrideDriver doesn't use the property set to hide the device interface.
Comment: Could share to us which property of  "use the property set to hide the device interface"  ?

Hide Audio device using codeless kext


Wich one do you think is a better solution for the product card of a grocery app

Question: Which of the options do you think to have better usability for the product cards for a grocery app (Shoppers)

The problem: I need to give to shoppers a better visualization of the basic products information in a smooth way for them don't get confused y make their process more easy and fast
Solution: I think is a lot of information for a card so I tried to organize the information in a way that I considered clear and give a better reading
so in A we have in the top left the product name, in the top right the location of the product in-store and in the center of the cards the picture, the order quantity and other information that help to picker the product in a better way like reference, price, and barcode
At the bottom of the card, I have a client comment if the client sends one
In B we had the same information but the difference is that I display the order quantity at the same level that the product name and the location is now in the center
Leave me to know what you think! Thanks for the feedback
Answer: The only way to know is to do A/B testing
I personally prefer A
B would be better if you could somehow distinguish the 3x from the Item Name with a more distinct styling or color.
Right now the quantity of the item is more obvious to me in design A.
Answer:
Why is the location in the store important for an online experience?
You have the product count but I don't see an option to increase or decrease this value
Why is the barcode number needed on what I'm assuming is the quick/list view of products?
Each of these versions, including the original, have positive qualities but none of them currently achieve the right hierarchy
Comment: What do you mean with "right hierarchy"?
Comment: Location is really helpful *if* the app is used by people *in the store* to find products. I do that frequently with Home Depot, for example. It actually bothers me if a web site shows in-store inventory level but doesn't clearly show location.
Answer: I would probably go with A but with the following recommendations:

Increase the colour contrast in the message to make it stand out (e.g. black font)
Move the quantity to the right side of the panel maybe with a grey background as in the original

Last but not least, as mentioned, try to only include the necessary information that the user needs to complete the order (e.g. Location, barcode, etc).
Answer: If I`d like to shop something online, the first Information thats important for me is WHAT. So I would scale the main productname up.
The second information is probably either how much it costs (depends on how much of the current month is already over :) and how much product I would buy.
I am not interested in data like barcodes or locations (that one could be an information to use as a filter for the tiles if it is really relevant to the users goals)
Overall great attempts. Try to use font sizes that differentiate more and try to use not to many. For example use a bold headline with the name of the product. Then a smaller copytext for metadata in the middle of the tile and a larger maybe thinner typeface for the price.
I hope this helps. Good luck!


Re-format MySQL DateTime

Question: I wanted to re-format mysql DateTime data type from 2011-12-08 08:31:23 to Dec 8, 2011 8:31 am while displaying on browser using PHP5 so I used
$create_date=date("M j, Y g:i a", strtotime($f["create_date"]));

and it is live on godaddy server but it is showing morning entries to pm and evening entries to to am..?
Comment: @eureka: I guess the OP wants them to be the correct way round.
Answer: The time difference between Arizona and Pakistan is 12 hours. strtotime uses godaddy's server time when converting to a Unix timestamp.
Use date_default_timezone_set() to set your time zone.

Re-format MySQL DateTime


how to dynamically set imageView height based on its width

Question: Having some imageViews in a list row.
The count of the imageView in the row are different, i.e. could be three or two imageView.
For the width it could be specified using
layout_width="0dp"
layout_weight="1dp"

for every imageView in the row. But the problem is the height, it should be 90% of the width of the imageView if the row has two imageView, and 80% of the width is the row has three imageView.
Is there way to do that in xml?
If not, where is the best place to do calc and set the height without too much overhead on the drawing?
Thanks!
Answer: Not sure if there is a way to do in xml. But this works in code, do it in the adapter::getView(), after get the corresponding imagView, change its height layoutParam but keep the width one.
Point size = new Point();

((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
int screenWidth = size.x;

int columnNumber = (isItThree ? 3 : 2);
double ratio = (isItThree ? 0.8 : 0.9)

int desiredImageHeight = screenWidth/colunmNumber * ratio;

ViewGroup.LayoutParams imglayoutParams = imgView.getLayoutParams();
imglayoutParams.height = desiredImageHeight;
imgView.setLayoutParams(imglayoutParams);

Answer: In order to maintain the ratio between height and width the best practice is:
Defining one of its property with a value in dp and another with wrap content.
In your case:
android:layout_width="20dp"
android:layout_heignt="wrap_content"

By doing this the height should be adjusted according to the ratio of given width.
Comment: not sure how the layout_heignt="wrap_content" will achieve this. In my case the width is dynamic based on the device width (laout:weight=1"dp" for each imageView), and the height will be 90% of the final width.


How do I go about solving this non-linear system of equations of 3 variables?

Question: In a problem on Lagrange multipliers, I need to find the maximum and minimum of,
$$f(x, y) = \frac{1}{3}x^3 +\frac{1}{2}x^2y^2 + \frac{1}{3}y^3$$
subject to the constraint, $$g=x^2+y^2-2=0$$
Doing the method of Lagrange Multipliers as ${\nabla}f = {\lambda}{\nabla}g$ , (instead of finding the lagrangian $L$, and solving for $\frac{{\partial}L}{{\partial}x}, \frac{{\partial}L}{{\partial}y}, \frac{{\partial}L}{{\partial}\lambda}$),
I came to the problem of solving the 3 non-linear equations:
$$x^2+xy^2=\lambda2x$$ $$y^2+x^2y = \lambda2y$$ $$x^2 +y^2-2=0$$Assuming I haven't gone wrong in forming these equations, how am I supposed to proceed from here to find all the constrained critical points? I  have already found $(x,y) = (0,\pm\sqrt2)$ and $(x,y) = (\pm\sqrt2, 0)$, by factoring the first 2 equations etc. I am also aware that $(\pm1,\pm1)$ are solutions to the constraint equation, but there are more solutions that I haven't found.
How do I go about finding all solutions to these ugly non-linear equations?
Comment: Start by considering the case $x=0$, then $y =0$. With those out of the way you can remove the factors $x$ and $y$ in the first two equations and see where that leads.
Comment: Nevermind! Equating x+y^2 = 2*lambda to y+x^2 = 2*lambda gets two cases, x = y and x + y = 1, and Putting these into the constraint equation gets the other solutions :).
Comment: I have that when x = 0, y = ±sqrt(2) and when y = 0, x = ±sqrt(2). Could  you elaborate on what you mean by remove the factors of x and y in the first two equations?
Comment: If you look at the first, all terms have a factor $x$ that can be removed. Doing so simplifies what you're left with.
Comment: I am finding that by factoring, we get x+y^2 = 2lambda ,  and y+x^2 = 2lambda. However, I can't find that this leads anywhere.
Comment: Note that the system of equations reduces to this single relation (circle): $x^{2} + y^{2}= (\sqrt{2})^2$ because from the system, you can prove that $\lambda=1$.
Answer: You have already found all solutions where $x=0$ or $y=0$. So you can cancel a factor of $x$ from the first equation and $y$ from the second equation. You have $x + y^2 = 2\lambda$ and $y+ x^2 = 2\lambda$. So $x+y^2 = y + x^2$, or $x-y + y^2-x^2 = 0$. This factors as $(x-y)(1-x-y)$, so either $x=y$ or $x+y = 1$.

If $x=y$, then the equation of constraint gives $2x^2=2$. So $(1,1)$ and $(-1,-1)$ are solutions.

If $x+y = 1$, then the equation of constraint gives $x^2 + (1-x)^2 = 2$, or $2x^2 - 2x -1 = 0$. This gives the points $\left(\frac{1+\sqrt{3}}{2},\frac{1-\sqrt{3}}{2}\right)$ and $\left(\frac{1-\sqrt{3}}{2},\frac{1+\sqrt{3}}{2}\right)$
Comment: It seems that $(x=0, y=\pm\sqrt{2})$ and  $(x=\pm\sqrt{2}, y = 0)$ are also solutions.
Comment: @Cesareo You are correct. As I wrote in the first sentence, OP already mentioned those and was in search of the rest.
Answer: $x^2+y^2-2=0$
Find extrema:$\ x^3/3+x^2y^2/2+y^3/3$
$\partial/\partial r\implies x^2\cos\theta+xy^2\cos\theta+yx^2\sin\theta+y^2\sin\theta=2r\lambda$
$\implies x^3+2x^2y^2+y^3=2(x^2+y^2)\lambda=4\lambda$
$\partial/ \partial \theta \implies x^2(-r\sin\theta)+xy^2(-r\sin\theta)+yx^2(r\cos\theta)+y^2r\cos\theta=0\lambda$
$-x^2y-xy^3+yx^3+xy^2=0=xy(-x-y^2+x^2+y)$
$=xy( x^2-x+1/4-1/4 -y^2+y -1/4+1/4)=xy( (x-1/2)^2-(y-1/2)^2)$
$=xy(x+y-1)(x-y)=0$
Alternatively:
Change of variables might help. Reduces it to a 1 D problem.
$x^2+y^2-2=0\implies r^2=2\implies r=\sqrt{2}$
$f(r=\sqrt{2},\theta)= (1/3)(2\sqrt{2})\cos^3\theta+(1/2)\sin^22\theta+(1/3)(2\sqrt{2})\sin^3\theta$
$df/d\theta=(2\sqrt{2})(-\sin\theta)\cos^2\theta+2\sin2\theta\cos2\theta+(2\sqrt{2})\cos\theta\sin^2\theta$
$0=\sin2\theta[-\sqrt{2}\cos\theta +2\cos^2\theta-2\sin^2\theta+\sqrt{2}\sin\theta]$
$0=2\sin2\theta[\cos^2\theta-\cos\theta/\sqrt{2}+(1/8)-(1/8)-\sin^2\theta+\sin\theta/\sqrt{2}]$
$0=2\sin2\theta[(\cos\theta-1/\sqrt{8})^2-(\sin\theta-1/\sqrt{8})^2]$
$0=2\sin2\theta(\cos\theta-\sin\theta)(\sin\theta+\cos\theta-1/\sqrt{2})$
$0=2\sin2\theta(\cos \theta - \sin \theta)(\sqrt{2}\sin(\theta+\pi/4)-\sqrt{2}/2)$
$2\theta=0\implies \theta \in \{0, \pi/2, \pi, 3\pi/2\}\implies (x,y) \in \{(\sqrt{2},0), (0,\sqrt{2}),(0,-\sqrt{2}), (-\sqrt{2},0)\}$
$(\cos\theta-\sin\theta)=0\implies \theta \in \{ \pi/4, 5\pi/4\}\implies (x,y)\in \{(1,1),(-1,-1)\}$
$(\sqrt{2}\sin(\theta+\pi/4)-\sqrt{2}/2)=0\implies \theta \in \{-\pi/12, 7\pi/12\}\implies (x,y)\in \{(\sqrt{1+\sqrt{3}/2},-\sqrt{1-\sqrt{3}/2}),(-\sqrt{1-\sqrt{3}/2},\sqrt{1+\sqrt{3}/2})\} $
Then test the 8 candidates.


sklearn TfidfVectorizer : Generate Custom NGrams by not removing stopword in them

Question: Following is my code:
sklearn_tfidf = TfidfVectorizer(ngram_range= (3,3),stop_words=stopwordslist, norm='l2',min_df=0, use_idf=True, smooth_idf=False, sublinear_tf=True)
sklearn_representation = sklearn_tfidf.fit_transform(documents)

It generates tri gram by removing all the stopwords.
What I want it to allow those TRIGRAM what have stopword in their middle ( not in start and end)
Is there processor needs to be written for this.
Need suggestions.
Answer: Yes, you need to supply your own analyzer function which will convert the documents to the features as per your requirements.
According to the documentation:

analyzer : string, {'word', 'char', 'char_wb'} or callable
....
....
If a callable is passed it is used to extract the sequence of
features out of the raw, unprocessed input.

In that custom callable you need to take care of first splitting the sentence into different parts, removing special chars like comma, braces, symbols etc, convert them to lower case, then convert them to n_grams.
The default implementation works on a single sentences in the following order:

Decoding:  the sentence according to given encoding (default 'utf-8')
Preprocessing: convert the sentence to lower case
Tokenizing: get single word tokens from the sentence (The default regexp selects tokens of 2 or more alphanumeric characters)
Stop word removal: remove the single word tokens from the above step which are present in stop words
N_gram creation: After stop word removal, the remaining tokens are then arranged in the required n_grams
Remove too rare or too common features: Remove words which have frequency greater than max_df or lower than min_df.

You need to handle all this if you want to pass a custom callable to the analyzer param in the TfidfVectorizer.
OR
You can extend the TfidfVectorizer class and only override the last 2 steps. Something like this:
from sklearn.feature_extraction.text import TfidfVectorizer
class NewTfidfVectorizer(TfidfVectorizer):
    def _word_ngrams(self, tokens, stop_words=None):

        # First get tokens without stop words
        tokens = super(TfidfVectorizer, self)._word_ngrams(tokens, None)
        if stop_words is not None:
            new_tokens=[]
            for token in tokens:
                split_words = token.split(' ')

                # Only check the first and last word for stop words
                if split_words[0] not in stop_words and split_words[-1] not in stop_words:
                    new_tokens.append(token)
            return new_tokens

        return tokens

Then, use it like:
vectorizer = NewTfidfVectorizer(stop_words='english', ngram_range=(3,3))
vectorizer.fit(data)

Comment: @miguelmorin You can find the [source for the default analyzer here](https://github.com/scikit-learn/scikit-learn/blob/364c77e047ca08a95862becf40a04fe9d4cd2c98/sklearn/feature_extraction/text.py#L423). Please have a go at copying and changing that as your requirements and let me know if any issue. You need to look at [def _analyze()](https://github.com/scikit-learn/scikit-learn/blob/364c77e047ca08a95862becf40a04fe9d4cd2c98/sklearn/feature_extraction/text.py#L75) also
Comment: i tried to get tokens without stop word in that line, but it returns without the stop words. i think there is some other function that calls before it. im calling fit_transform
Comment: @ShanKhan Please provide an example of sentences where you think this is happening. I have checked it with sample data and its working as expected. Please mind that the above code will remove trigrams where starting or ending word is stop word.
Comment: Thanks, it worked - actually i was removing stop words in initial cleaning, when i remove that chunk - it worked Perfect!
Comment: I couldn't find an example nor a reference about defining one's own analyzer. Can you please add one?


Why is this if/then statement returning as true?

Question: I have a rather ugly service job that runs through a legacy database and compares it to our production database:
if (vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number) != null)                        {
 var oldDbContractItem = vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number).First();
                            // check to see if there were changes
                            if (oldDbContractItem.DateStamp != vendorContractItem.Date_Stamp)
                            {
                                oldDbContractItem.Update(vendorContractItem);
                            }
                        }

I will get an error on var oldDbContratItem, "Sequence contains no elements", yet I just did a != null check. This must be simple, what's going on?
Answer: If I could teach people just one thing about LINQ it's this: the value of a query expression is an object that represents the query, not the results of the query.  Fundamentally that's your problem; you're treating the query as its results. A query isn't a result any more than a restaurant is a club sandwich. A restaurant is a device which produces club sandwiches; a query is a device that produces results.
Comment: I like this answer more than mine, from a fundamentals POV.
Answer: This is the test against null you are doing:
vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number) != null

That will always be true; That will always return at least an empty sequence... never a null.
You might be meaning to test that its length is greater than 0?
There's an easier way, though, IMO. Call FirstOrDefault() instead of First() and leave out the pre-test completely. Then instead, test if the result of FirstOrDefault() is null.
var oldDbContractItem = vendorContract.Item
  .Where(x => x.ItemNumber == contractItem.Item_Number).FirstOrDefault();
if(oldDbContractItem != null) //would be null if there are no items
{
  // check to see if there were changes
  if (oldDbContractItem.DateStamp != vendorContractItem.Date_Stamp)
  {
    oldDbContractItem.Update(vendorContractItem);
  }
}
}

Answer: Because your query returned a container, it just happened to be empty, the null check is on the return not what the return contains.
try this instead...
if (vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number).Any())
{
  .....
}

Comment: @Andrew: `foreach` would be the way to go if you are dealing with potentially multiple items.  Running the query a second time just to call `Any` is silly (or worse, if the query is against a shared data store, it introduces a race condition).
Comment: Note, in your specific case, @Andrew Barber has the more elegant solution (as you are wanting the first element if it exists anyway), my solution is for just testing the sequence contains something.
Comment: +1 This would be the way to go when, for instance, you would be dealing with (potentially) multiple items in a result sequence, instead of just one.
Answer: Don't run the query twice.  It's inefficient and may introduce a race condition into your code.  Also, your logic is much better supported by either using IEnumerator<T> directly, or with a foreach loop.
Use either:
var result = vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number).GetEnumerator();
if (result.MoveNext) {
    var oldDbContractItem = result.Current;
    // ...
}

or
foreach (var oldDbContractItem in vendorContract.Item.Where(x => x.ItemNumber == contractItem.Item_Number)) {
    // ...
    break;
}

Comment: +1 for noting that the original code was needlessly running the query twice.
Answer: After using a fix from the accepted answer, you can further debug the LINQ situation (if need be) by using the following steps.  LINQ is an exciting technology but takes a while to wraps ones' head around it - a bit of a paradigm shift I would say. Eric's answer hit the nail on the head because he likely helped build the stuff!
Debugging Steps for LINQ

To deal with the issue of no results from the second statement change .First() to .FirstOrDefault()  If nothing is found it will return the default value of the data type - if the data type is a class it will return a null value. Your second statement should then work with a null check too and without error.
Then you can debug your LINQ statement to find out why it's doing what it does.

if using LINQ to SQL, Intellisense in Visual Studio 2010 will show you the SQL generated when you hover over a query variable (not the result of a query). If you need the visualizer for VS 2008 it's here
Similarily if you're using LINQ to Entity Framework, you can get the generated SQL using the visualizer plugin here.

I always take the generated SQL from these tools, paste it directly into a query window and run it there. It will show you the empty set you're getting back and if that's a problem you can further debug it in this manner of visualizing the generated statements.
Comment: This is not actually solving anything. The problem is that his test for an empty sequence is wrong. You're just masking the bug.
Comment: @Yuliy: the accepted answer also suggested `FirstOrDefault` as a step in debugging. It's not masking anything but rather making the process more manageable.
Comment: ....but you're right if you noticed I was focusing on the second code statement more than the first, not about the truth test. I will leave these tool hyper-links here in case they prove useful to somebody debugging a LINQ situation.
Answer: A sequence with no elements is still an object.
Answer: Where can return a non-null value, but still resolve to a sequence containing no elements.  In your failing statement you are using something else, which is Where().First().  That will be null if the sequence from Where is indeed empty.
Answer: There is difference between null and an empty sequence (e.g. something similar to new List<T>()). What you want to do is to use Any() to check whether the sequence contains any elements, or rather replace First() with FirstOrDefault(), which returns null if the sequence contains no element. (If you use that, make sure that null is not a valid value that could be returned by First()).


Vertically center DIV inside LI without px-measure

Question: I am trying to make a list with square bullets in different colors with square size independant of the font size.
I need to use font sizes in em or %.
That's my best try so far: http://jsfiddle.net/3GMjp/29/

        Element 1

        Element 2

        Element 3

css:
ul {
    padding:0;
    margin:0;
}

li {
    font-size: 1.5em;
    list-style-type:none;
    line-height: 2em;
}

.li_box {
        float:left;
        width:10px;
        height:10px;
        vertical-align:middle;
        margin-right:10px;
}

.red{ background-color:red}
.green{ background-color:green}
.blue{ background-color:blue}

Could someone help me to center the boxes without adding px-measures?
Any working solution (would be appreciated)!
Comment: is my answer work for you? See it in fiddle.
Comment: I just recognized i mixed vertical with horizontal! I obviously ment center vertical. Sorry and thank you all for the answers so far. Could you please have another look?
Answer: See I have done modification in the CSS and HTML :
Please see URL : http://jsfiddle.net/3GMjp/33/
HTML code:

            Element 1

CSS changes :
ul {
    padding:0;
    margin:0;
}

li {
    font-size: 1.5em;
    list-style-type:none;
    line-height: 2em;
}

li div {
    display:table;
}
.spn{
    display:table-cell;
}

.li_box {
        display:table-cell;
        float:left;
        width:10px;
        height:10px;
        vertical-align:middle;
        margin-right:10px;
}

.red{ background-color:red}
.green{ background-color:green}
.blue{ background-color:blue}

Answer: I've updated your fiddle here.
If you float an element, it will become a block element, and thus vertical align won't work. The span with the text, unless floated as well, will wrap to the next line.
Inline block seems to work just fine:
.li_box {
        display: inline-block;
        width:10px;
        height:10px;
        margin-right:10px;
}

Answer: If you're simply looking to center the content of the divs, this should be all you need:
 div { text-align: center; }

Comment: I think he is talking about vertical align not horizontal :-)
Answer: try to use this:
li {
   ...
   text-align:center;
}

Comment: This is horizontal align, op wanted vertical align
Comment: @Scott first time I seen this Q, its title had "Horizontal" word!
Answer: Adding margin top to .li_box will fix your issue.
.li_box {
...
margin-top: 1%;
}

Comment: Thanks for your answer but it does not :( It's still not centered vertically.


Shell Scripting Function question

Question: I have this code snippet I am working on for a small project I am doing:
echo "Please enter SUID: ";
read $uid

uid_Assoc(){
        arg1=$1
        echo $1;
}

uid_Assoc

Now to start, I would like this to prompt for a string and read the string. From there I would like to pass that string as an argument and echo it out. But I am not sure how to pass the string off as a parameter. When I attempt to do something like:
uid_Assoc($uid)

It throws a syntax error (I figured that would be incorrect anyways). Are there any suggestions on how to do this?
UPDATE: I also tried re-arranging the code a bit to look like this:
function uid_Assoc(){
        arg1=$1
        echo $1;
}
echo "Please enter SUID: ";
read $uid
uid_Assoc $uid

But that didn't seem to work either.
Answer: The read command takes a variable name, so remove the sigil:
read uid

What you are doing, is this: sending the contents of the uid variable as the variable name for the read command. Since this value is currently empty, you have
echo "a prompt: "
read

That is valid bash code. The default variable name for a "bald" read command is REPLY
Given your code, here is a mild rewrite:
function uid_Assoc {
        local arg1=$1
        echo "$arg1";
}

read -p "Please enter SUID: " uid
uid_Assoc "$uid"

Notes:

you don't need both the function keyword and the () syntax, choose one or the other (my opinion only)
localize variables in functions to limit their scope
use the -p option to read
always quote referenced variables (you never know how many spaces the user will type), unless you know why you need to leave a variable unquoted.
Comment: I tried that but did not get an echo of the string in the method. It just shows a blank..
Comment: You tried what, exactly?
Answer: Modify your script as follow:
#!/bin/bash

echo "Please enter SUID: ";
read uid

uid_Assoc () {
        arg1="$1"
        echo "$1"
        echo "$arg1"
}

uid_Assoc "$uid"

You just need to remove the $ prefix before uid in the read call.

Shell Scripting Function question