text:
Q: C Programming: malloc() inside another function I need help with malloc() inside another function.
I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main().
How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

I have written the following code and I get the output as shown below.
SOURCE:
int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");
   return 0;
}

signed char alloc_pixels(unsigned char *ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    ptr = NULL;

    ptr = (unsigned char*)malloc(size);

    if(ptr== NULL)
    {
        status = ERROR;
        free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!");
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));

    return status;
}

PROGRAM OUTPUT:
Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes

A: You need to pass a pointer to a pointer as the parameter to your function.
int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");
   return 0;
}

signed char alloc_pixels(unsigned char **ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    *ptr = NULL;

    *ptr = (unsigned char*)malloc(size);

    if(*ptr== NULL)
    {
        status = ERROR;
        free(*ptr);      /* this line is completely redundant */
        printf("\nERROR: Memory allocation did not complete successfully!");
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr));

    return status;
}

A: If you want your function to modify the pointer itself, you'll need to pass it as a pointer to a pointer. Here's a simplified example:
void allocate_memory(char **ptr, size_t size) {
    void *memory = malloc(size);
    if (memory == NULL) {
        // ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
    }

    *ptr = (char *)memory;
}

int main() {
   char *data;
   allocate_memory(&data, 16);
}

A: You need to pass the pointer by reference, not by copy, the parameter in the function alloc_pixels requires the ampersand & to pass back out the address of the pointer - that is call by reference in C speak.

main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");

}

signed char alloc_pixels(unsigned char **ptr, unsigned int size)
{
    signed char status = NO_ERROR;
    *ptr = NULL;

    *ptr = (unsigned char*)malloc(size);

    if((*ptr) == NULL)
    {
        status = ERROR;
        /* free(ptr);
        printf("\nERROR: Memory allocation did not complete successfully!"); */
    }

    printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr));

    return status;
}

I have commented out the two lines free(ptr) and "ERROR: ..." within the alloc_pixels function as that is confusing. You do not need to free a pointer if the memory allocation failed.
Edit: After looking at the msdn link supplied by OP, a suggestion, the code sample is the same as earlier in my answer.... but...change the format specifier to %u for the size_t type, in the printf(...) call in main().

main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size)==NULL)
     printf("\nPoint2: Memory allocated: %u bytes",_msize(input_image));
   else
     printf("\nPoint3: Memory not allocated");

}

A: As mentioned in the other answers, we need a pointer to the pointer. But why?
We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int, you need to pass it by the int*.
In this question, the value we want to modify is a pointer int* (pointer changed from NULL to the address of the allocated memory), so we need to pass a pointer to the pointer int**.
By doing followed, pInt inside foo(int*) is a copy of the argument. When we allocate memory to the local variable, the one in the main() is intact.
void foo(int* pInt)
{
   pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(pInt);
   return 0;
}

So we need a pointer to pointer,
void foo(int** pInt)
{
   *pInt = malloc(...);
}
int main()
{
   int* pInt;
   foo(&pInt);
   return 0;
}

A: This does not make sense :
if(alloc_pixels(input_image, bmp_image_size)==NULL)

alloc_pixels returns a signed char (ERROR or NO_ERROR) and you compare it to NULL (which is supposed to be used for pointers).
If you want input_image to be changed, you need to pass a pointer to it to alloc_pixels.
alloc_pixels signature would be the following:
signed char alloc_pixels(unsigned char **ptr, unsigned int size)

You would call it like this:
alloc_pixels(&input_image, bmp_image_size);

And the memory allocation
*ptr = malloc(size);

A:
How should I pass a pointer to a
  function and allocate memory for the
  passed pointer from inside the called
  function?

Ask yourself this: if you had to write a function that had to return an int, how would you do it?
You'd either return it directly:
int foo(void)
{
    return 42;
}

or return it through an output parameter by adding a level of indirection (i.e., using an int* instead of int):
void foo(int* out)
{
    assert(out != NULL);
    *out = 42;
}

So when you're returning a pointer type (T*), it's the same thing: you either return the pointer type directly:
T* foo(void)
{
    T* p = malloc(...);
    return p;
}

or you add one level of indirection:
void foo(T** out)
{
    assert(out != NULL);
    *out = malloc(...);
}

A: In your initial code , when you were passing input_image to the function alloc_pixels, compiler was creating a copy of it (i.e. ptr) and storing the value on the stack. You assign the value returned by malloc to ptr. This value is lost once the function returns to main and the stack unwinds. So, the memory is still allocated on heap but the memory location was never stored in (or assigned to )input_image, hence the issue.
You can change the signature of the function alloc_pixels which would be simpler to understand, and you won't require the additional 'status' variable as well.
unsigned char *alloc_pixels(unsigned int size)
{
    unsigned char *ptr = NULL;
    ptr = (unsigned char *)malloc(size);
    if (ptr != NULL)
       printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));
    return ptr;
}

You can call the above function in main :
int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if((input_image = alloc_pixels(bmp_image_size))==NULL)
       printf("\nPoint3: Memory not allocated");
   else
     printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
   return 0;

}

A:
Parameters' assignment will work only if you set the value to its address.

There are 2 points that you should know before you attempt to solve this problem:
1. C Function:  All the parameters you passed to the function will be a copy in the function.
That means every assignment that you've made in the function will not affect the variables outside the function, you're working on the copy actually:
int i = 1;
fun(i);
printf("%d\n", i);
//no matter what kind of changes you've made to i in fun, i's value will be 1

So, if you want to change i in the function, you need to know the difference between the thing and its copy:

The copy shared the value with the thing, but not the address.

And that's their only difference.
So the only way to change i in the function is using the address of i.
For example, there's a new function fun_addr:
void fun_addr(int *i) {
    *i = some_value;
}

In this way, you could change i's value.

*malloc:

The key point in the fun_addr function is, you've passed a address to the function. And you could change the value stored in that address.
What will malloc do?
malloc will allocate a new memory space, and return the pointer pointed to that address back.
Look at this instruction:
int *array = (int*) malloc(sizeof(int) * SIZE);

What you are doing is let array's value equals to the address returned by malloc.
See? This is the same question, permanently assigning value to the parameter passed to the function. At this point, the value is address.

Now, assign the address(returned by malloc) to the address(stores the old address).

So the code should be:
void fun_addr_addr(int **p) {
    *p = (int*) malloc(sizeof(int) * SIZE);
}

This one will work.

A: The only way I could get pointer to a pointer solution to work for a similar problem I was having for this function
    BOOL OpenBitmap2 ( LPCTSTR pszFileName, char** pszBMPFile)

Was by assigning a temporary pointer to store the address
    char* BMPFile;
    { BMPFile = (char*)GlobalAlloc(GPTR, dwFileSize + 1);   // allocate storage using GlobalAlloc + 1 for null term string

then reassigning it
    {* pszBMPFile = BMPFile; return (0);} // Error = False

Any comment on why using "* pszBMPFile" directly with GlobalAlloc didn't work would be appreciated.
 I answered my own question. I forgot to carry the "*" through with pszBMPFile in the other lines of code. Good lessons from all the contributors. Many thanks.


text:
Q: creating a reference for use in identifiying if a button was clicked How is it possible create a reference for an uibutton to check if it was pressed and do something like make the value for that button true in order to be able to use that value later on. I heard of ivars but i havent seen any documentation on how to use them and im not sure if they would work for my ibaction uibutton...

A: This is really a fundamental question and a full explanation will take along time.
Basically, you need to understand the concept of MVC (Model-View-Controller).  In this case, the "View" will be your UIButton created in Interface Builder.  It needs to have a target/action setup to point to some "Controller".  This will be a custom class you design that performs some action when the UIButton is released.  This controller can also track finger up/down/move/drag and what not.  This Controller will store the fact the button was pressed in a "Model" class.
Here is some more reading:
http://developer.apple.com/iphone/library/documentation/general/conceptual/devpedia-cocoacore/MVC.html
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html
In the simplest cases, this can be done with Core Data and IB without writing any code and simply making connections.

redpajama_set_name: RedPajamaStackExchange


text: Q: Suggest the way to detect file changes in visual studio code I am using run on save visual studio code extension but it runs command on every save command.what i need is to run command only if any file changed


text:
Q: Best way to wait for 3rd-party JS library to finish initializing within Angular 2 service? I'm wrapping a 3rd-party JS library in an Angular service. How can I guarantee that the 3rd-party JS library is loaded/initialized/etc. before using my service?
Can you take a look at the following code and tell me if this is a good coding practice? I'm setting up a promise in the service's constructor (promise that will eventually be fulfilled) and I have the service methods depend on the success of that promise (see getMessages).
@Injectable()
export class GmailService {

  private _readyPromise;

  // Load Gmail API client library.
  // gapi.client.load() returns a promise.
  constructor() {
    this._readyPromise = gapi.client.load('gmail', 'v1');
  }

  private ready():Promise {
    return this._readyPromise;
  }

  // Return Gmail messages for the current user.
  getMessages() {
    return this.ready().then(() => {
      return gapi.client.gmail.users.messages.list({
        'userId': 'me'
      }).then(resp => console.log(resp));
    });
  }
}

In that exemple, I'm using the Gmail API for JavaScript and it turns out that gapi.client.load() already returns a promise, which simplifies the code. In a different scenario I could have created my own promise and fulfilled it manually when a specific condition is met.

A: Your approach seems fine! Another one would be to bootstrap your application after your Gmail API library is loaded:
var app = platform(BROWSER_PROVIDERS)
   .application([BROWSER_APP_PROVIDERS, appProviders]);

gapi.client.load('gmail', 'v1').then(() => {
  return app.bootstrap(AppComponent);
});

This way you will be sure that the library is ready when using it within your application.
Here is a corresponding plunkr describing the global approach: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.


text:
Q: using new with a variable that is assigned a function does not have an assigned __proto__ I just started reading about Javascript and I cant seem to find the asnwer to this question.Suppose I have a function called test and an anonymous function assigned to a variable say temp. I noticed that when I create a new object instance with new using a variable as in example 2 no __proto__ is assigned ? Why is that

function test() {
  this.name = "testerName";
}

var temp = function() {
  this.name = "testeragain";
}

// Example 1:
var d = new test();
console.log(d.__proto__) //prints test{}
console.log(d.__proto__ == test.prototype) //Returns false ? shouldnt this
// Example 2:
var d = new temp();
console.log(d.__proto__) //prints {} ?Why is this?

I am running my file using command node test.js

A:
no __proto__ is assigned ?

Of course it is. In both cases d.__proto__ returns the prototype. The difference is only how console.log chooses to render that value. If you use console.dir instead you should see that those objects are (almost) the same.
Here is an example that demonstrates how the console.log output can differ:
> console.log({constructor: function foo() {}});
foo { constructor: [Function: foo] }

> console.log({constructor: function bar() {}});
bar { constructor: [Function: bar] }

> console.log({constructor: function () {}});
{ constructor: [Function] }

Do you see that the objects are basically the same, except that the functions assigned to constructor have different (or no) names?
console.log simply prefixes the representation of the object with the value of constructor.name.

prints {} ?Why is this?

The console tries to infer the "type" of the object somehow. Since the first function has a name (test) it will use that name as the "type" in the output.
The second function doesn't have a name so it doesn't know what to show.
More concretely
console.log(d.constructor.name)

will log "test" for the first function and an empty string ("") for the second function.
The behavior of console.log is not standardized and the output can differ between browsers JavaScript environments. Functionally wise both examples are identical.


text:
Q: Extract elements of matrix in expression Is it possible to extract elements from matrix in one expression for slicing operators:
([1 2 3; 4 5 6] * [1 2 3]') (1:2)

Without using intermediate variable
tmp=[1 2 3; 4 5 6] * [1 2 3]';

tmp(1:2)


text:
Q: How figure out multiple nested if else condition? I am not getting an efficient way to check below mentioned condition.
What I want to achieve is that-
There are some processes that need to be done if their corresponding boolean is true suggesting to start the process. So I want to check if a particular condition is done only if it should be started.
There are some boolean variables
var shouldStartProcessA
var shouldStartProcessB
var shouldStartProcessC

var isADone
var isBDone
var isCDone

if (shouldStartProcessA && shouldStartProcessB && shouldStartC) {
    if (isADone && isBDone && isCDone) {
        // Every process completed
    }
}

if (shouldStartProcessA && shouldStartProcessB) {
    if (isADone && isBDone) {
        // Every process completed
    }
}

if (shouldStartProcessA && shouldStartC) {
    if (isADone && isCDone) {
        // Every process completed
    }
}

if (shouldStartProcessB && shouldStartC) {
    if (isBDone && isCDone) {
        // Every process completed
    }
}

if (shouldStartProcessA) {
    if (isADone) {
        // Every process completed
    }
}

if (shouldStartProcessB) {
    if (isBDone) {
        // Every process completed
    }
}

if (shouldStartProcessC) {
    if (isCDone) {
        // Every process completed
    }
}

This type of validating condition grows exponentially by introducing every other boolean. I am struggling to find a straightforward implementation to check these conditions.

A: Instead of doing things this way, I'd recommend a data structure that allows you to add tasks and check their state. There are a lot of ways to do that, but the basic idea is you can iterate over all the items and use functions like all to confirm they're all in the appropriate state. That way you don't have to hand-wire everything together
You could use a Map and add tasks to it, initially mapping them to false and setting that to true when they're completed. Or create a Set and add your tasks to that (I'm assuming you want one of each at most), and remove them / move them to a "done" list when they complete. That kind of idea. You could create an enum class to represent your tasks if you want, so each one is its own instance (e.g. Process.A, like having a dedicated, fixed variable) and you can easily use those in your logic

If you really want variables for each process, instead of a data structure, I'd still recommend rolling each pair into a single state, something like this:
enum class State {
    UNUSED, PENDING, DONE
}

var processA = State.UNUSED
var processB = State.PENDING
// etc

// you can easily check them like this:

// create a list of all the variables you want to check - we're using references
// to the properties themselves (with the ::), not the current value!
val allProcesses = listOf(::processA, ::processB)

// now you have that collection, you can easily iterate over them all
// and work out what's what - we need to use get() to get the current values
val allFinished = allProcesses
    .filterNot { it.get() == State.UNUSED } // ignore unused processes
    .all { it.get() == State.DONE } // check ALL the required ones are DONE

You could write that check there as a single all condition, but the point is to show you you can be flexible with it, and build up your logic by filtering out the stuff you're not interested in, if you create a useful set of states

If you really do want to (or have to) stick with the current "pairs of variables" setup, you can do something similar:
// wiring them up again, creating a list of Pairs so we can iterate over them easily
val allProcesses = listOf(
    ::shouldStartProcessA to ::isADone,
    ::shouldStartProcessB to ::isBDone,
    ::shouldStartProcessC to ::isCDone
)

// gotta check 'em all - only returns true if that ALL meet the condition
val allComplete = allProcesses.all { (shouldStart, isDone) ->
    // the get() syntax is awkward, but basically for everything we're checking
    // if it either doesn't need to start, or it does but it's also done
    !shouldStart.get() || (shouldStart.get() && isDone.get())
}

so adding new processes is just a case of adding their variables to the list of pairs, and they get included in the checking

You don't need the property reference stuff (::/.get()) if you create the lists right before you check them, but if you want to define them once in advance (and the property values can change after that) then that's how you'd do it. Otherwise you can just do the normal shouldStartProcessA to isADone etc, which is probably fine for most cases - I'm showing the reference stuff as a more general example for handling this kind of thing

A: I suppose, you should create two lists of Boolean and add variables consequently.
val list1 = listOf(shouldStartProcessA, shouldStartProcessB, shouldStartC)
val list2 = listOf(isADone, isBDone, isCDone)

Then iterate over both lists and check that items in corresponding positions have the same values.
var n = 0
for (i in list1.indices) {
   if (list1[i] == list2[i]) {
       n++
   } else {
       n = 0
       break
   }
}

if (n > 0) {
    // Every process completed
}


text:
Q: Format date as the first/last day of the month I have date strings in "Y-m" format. Day is irrelevant here. Now I need to create another date from these date strings wheere day should be either 1st or the last day of the month. I have tried this code:
$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-d');

The problem here is that it creates dates with the current day of the months. How can I force it to do it for the 1st or last day?
Thanks

A: first day:
$dt = $curDate->format('Y-m-01');

last day:
$dt = $curDate->format('Y-m-t');

t: Number of days in the given month

http://php.net/manual/en/function.date.php

A: You can specify hard code value
$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-1'); //if you want first day
$dt =  $curDate->format('Y-m-t'); //if you want last day


text:
Q: Why are my buttons floating above the containing element? Is it bootstrap related? I suspect it's bootstrap because if I don't include the bootstrap library, the code works fine. Any ideas on what it could be? I've included an example here to demonstrate the effect.

#main-pane {
  position: relative;
  margin-top: 100px;
  margin-bottom: 180px;

}

#lower-bar {
  background-color: #0F6292;
  height: 80px;
  position: relative;

}
.center-it {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);

}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      good dreams pupper

     <input type="button" id='btn-1' value ="Button 1">
     <input type="button" id='btn-2' value ="Button 2">
     <input type="button" id="btn-3" value="Button 3">
     <input type="button" id='btn-4' value ="Button 4">
     <input type="button" id="btn-5" value="Button 5">

A: Replace: transform: translate(-50%,-50%); in your .center-it css by transform: translate(-50%,50%);

#main-pane {
  position: relative;
  margin-top: 100px;
  margin-bottom: 180px;

}

#lower-bar {
  background-color: #0F6292;
  height: 80px;
  position: relative;

}
.center-it {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,50%);

}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      good dreams pupper

     <input type="button" id='btn-1' value ="Button 1">
     <input type="button" id='btn-2' value ="Button 2">
     <input type="button" id="btn-3" value="Button 3">
     <input type="button" id='btn-4' value ="Button 4">
     <input type="button" id="btn-5" value="Button 5">


text:
Q: getting null view inside gridview of buttons of Dialog android I am not able to access the buttons which are in gridview. My gridview is placed on dialog using customAdpater. Please help me!!!
Below is my code
1) In onCreate() method:
    dialog = new Dialog(this);
            dialog.setContentView(R.layout.question_pallet);
            dialog.setTitle("Question Pallet...");
            gridView = (GridView) dialog.findViewById(R.id.grid_view);

            gridView.setAdapter(new ImageAdapter(QuestionBankActivity.this,allQuestions));
Button b = (Button) gridView.findViewWithTag("Hi"); //returning null
Button b = (Button) gridView.getChildAt(0); //returning null

2) question_pallet.xml is like this
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:columnWidth="70dp"
    android:gravity="center"
    android:stretchMode="columnWidth" >

</GridView>

3) ImageAdapter.java for my grdview is
public class ImageAdapter extends BaseAdapter {
private Activity mContext;

List<GATEQuesAnswer> allQuestions;
static Button b[] = new Button[65] ;
int next_counter = 1;

private int pos;
// Constructor
public ImageAdapter(Activity c, List<GATEQuesAnswer> allgeteQuestions){
    mContext = c;
    allQuestions = allgeteQuestions;
}

public ImageAdapter(QuestionBankActivity questionBankActivity) {
    mContext = questionBankActivity;
}

@Override
public int getCount() {
    return 65;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Button button;
    //if (convertView == null) {
        button = new Button(mContext);
        button.setText(Integer.toString(pos++));
        button.setId(position);
        button.setTag("Hi");

    //}
    //else
    //{
        //button = (Button) convertView;
        //Log.i("mytag", b.length+"");
    //}

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            ((QuestionBankActivity)mContext).navigate_to_ques(position+1);

        }
    });
    button.setLayoutParams(new GridView.LayoutParams(70, 70));
    return button;
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

}
I have tried all possiblities like giving unique ids to each button and getting it using gridview.findViewById(),or getChildAt(index) but nothing is working:(
Any help will be appreciated!!!
Thanks in advance!

A: your getView method is all wrong , try it with something like ...
@Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.row, null);

                holder = new ViewHolder();
                holder.button = (Button) convertView
                        .findViewById(R.id.ID_OF_YOUR_BUTTON);
                holder.button.setTag("HI");
                convertView.setTag(holder);

                holder.button.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                              //DO YOUR CODE
                    }
                });

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            return convertView;
        }
    }

private class ViewHolder {
                    Button button;
        }

//EDIT
Also, You can iterate over all children of a GridView(or any other ViewGroup) with getChildAt():
for(int i=0; i<gridView.getChildCount(); i++) {
    Button child = (Button) gridView.getChildAt(i);
    // do stuff with child view
}

row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </Button>

</LinearLayout>


text:
Q: Need for "minimal representation" of a symmetric group I need to construct a representation of a symmetric group $S_n$, in which a character of the conjugacy class $(n)$ (a class of permutations, which are cycles of a maximal possible length $n$) would be different from all other characters. I am looking for a representation of a minimal possible dimensionality. It can be reducible. Characters of other classes can coincide.
Would be grateful for ideas.


text:
Q: MKMapRectContainsRect returns false even if I've set an overlay? I'm a little new to Objective C and iOS programming, I've been exploring MKMapView recently, and I've been able to add annotations successfully.
[self.mapView addAnnotations:annotations]
However,
when I try to add an overlay, I'm running into issues,
I add the overlay and then I need to add setVisibileMapRect.
When I write something like this-
    [self.mapView addOverlay:MyOverlayObject]

    BOOL mapContainsOverlay = MKMapRectContainsRect(self.mapView.visibleMapRect,
                                 [MyOverlayObject boundingMapRect]);

    if (mapContainsOverlay) {
            //This is not getting executed.
      }

     NSLog(@" %hhd", mapContainsOverlay) //Prints 0

Any Idea why mapContainsOverlay is 0?

A: If the map is looking at England, and the overlay is in New Zealand then self.mapView.visibleMapRect does not contain [MyOverlayObject boundingMapRect] and thus MKMapRectContainsRect returns false (which is printed as 0). I don't know what your rects are but I'm guessing that the rect2 doesn't fit "entirely within rect1" as per the spec. e.g. France does not contain Europe.
If you want to ensure that your map is looking at where the overlay you need to set the visible map rect.


text:
Q: JS function replacing inputs last digit with 0? I've got a script which gets a bunch of information from an api and then lists it on my site. I then have a function, newLink(z) which is supposed to get the information from the new elements created and do stuff with it, to simplify it I'm just trying to console.log whatever it says below. Any number that I put into the brackets of the function, in this case 76561198008132325, has the last digit replaced with a 0 for whatever reason, resulting in the console logging '76561198008132320'. I've been scratching my head on this for a good half hour now and I literally can not figure out what is causing this.

    var searchRequest = "https://api.roleplay.co.uk/v1/search/player?name=ant";
    var searchData = "";

    function success(data) {
      for (i = 0; i < data['length']; i++) {

          document.getElementById("searchResults").innerHTML += "
new link
";
      }
    }

function newLink(z) {
    console.log(z);
}

    $.ajax({
      dataType: 'json',
      url: searchRequest,
      data: searchData,
      success: success
    });

A: This is because you are passing the argument to the function as Number. Pass the argument value as string.

var searchRequest = "https://api.roleplay.co.uk/v1/search/player?name=ant";
var searchData = "";

function success(data) {
  for (i = 0; i < data['length']; i++) {
  document.getElementById("searchResults").innerHTML += "
new link
";
  }
}

function newLink(z) {
    console.log(z);
}

$.ajax({
  dataType: 'json',
  url: searchRequest,
  data: searchData,
  success: success
});


text:
Q: Ensure a base64 encoded string never includes a nonalphanumerical character Is there anyway to ensure that a base64 encoded string never includes a non-alphanumerical character?
For example, if I have a long string that I encode, is there something I can prepend or append to it that will ensure that when encoded with base64 will only include letters and numbers in the encoded string? Something like this:
String: 192.168.1.1
Encoded: MTkyLjE2OC4xLjE= <- I want to 'get rid' of the equal sign.
I tried appending } at the end of the string (new string is now 192.168.1.1}), and this worked (new encoded string: MTkyLjE2OC4xLjF9), but is there a method of ensuring every combination works?
Is this possible?

A: It's about the length. The = sign is padding to make the output a multiple of 4 base64 characters. 3 characters translate to 4 base64 characters, so you just need to make your input string a multiple of 3 characters in length somehow. In your case:
192.168.1.1 - 11 characters long, base64 ends with =
192.168.1.1$ - 12 characters long, base64 doesn't end with =

Choose a padding character you can easily remove.
The other alternative is to strip the = from the output, then make sure you append = signs to make a multiple of 4 characters before you try to base64 decode...

A: You can just rtrim() the equals signs away, which is what most people do.
but as for your question: when length of string / 3 is a whole number. So:
$pad = strlen($str) % 3; if($pad) { $str .= str_repeat(' ', $pad); }

but yeah, the parser will add the equals signs back in automatically just like that, to a multiple of 4, when you pass the string back in - so you dont need to keep them.


text:
Q: SQlite3 is there anyway to know the amount of entries that have been added? I was looking into using a database to store a generated link to that database entry that holds more information about the database entry. So you would see a bit of the database, then click on the entry and open a new page that holds more information about that entry.
What I was looking for was something to keep track of the amount of entries that have been entered, even if one of the entries have been removed. I know SQlite3 has count, but I haven't seen anything that would keep track of this. I was thinking in order reach my goal I would have to just set a counter and write it to a file and pull that counter when I am making a new entry, just wondering if anyone know something else I can do instead of reading/writing a file for one number.
Should be noted this is on a server that can be shutdown and restarted, the user must enter in the information that goes into the database and the server will log it for the user. And I don't want to every repeat the same entry number.
I have mainly used PHP, HTML, and Python for the current project I am working on.

A: I looked into this out of curiosity because you can do 'post save' and 'pre save' in most ORM-based webapps.

"A trigger may be specified to fire whenever a DELETE, INSERT, or UPDATE of a particular database table occurs"
https://sqlite.org/lang_createtrigger.html

CREATE TRIGGER aft_insert AFTER INSERT ON emp_details
BEGIN
INSERT INTO emp_log(emp_id,salary,edittime)
         VALUES(NEW.employee_id,NEW.salary,current_date);
END;

A: It seems like the answer I was looking for was built into SQLite3, which is the best kind of answer.Auto Increment in SQlite3 allows for me to do what I was looking for. It will keep track of the amount of entries that have been added meaning I will be able to generate a link from the ROWID that I set to Auto Increment and not have a chance to repeat that it again.


text:
Q: Не отправляет письмо на почту выдаёт ошибку еррор использую phpmailer
всё варианты пробовал! поменял порти, gmail yandex mail ? но не получается в чем проблема?
<?php

require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$name = $_POST['user_name'];
$phone = $_POST['user_phone'];
$email = $_POST['user_email'];

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.mail.ru';                                                                                // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'metrex14@mail.ru'; // Ваш логин от почты с которой будут отправляться письма
$mail->Password = 'xxxxxx'; // Ваш пароль от почты с которой будут отправляться письма
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to / этот порт может отличаться у других провайдеров

$mail->setFrom('metrex14@mail.ru'); // от кого будет уходить письмо?
$mail->addAddress('sheyhan1426@gmail.com');     // Кому будет уходить письмо
//$mail->addAddress('ellen@example.com');               // Name is optional
//$mail->addReplyTo('info@example.com', 'Information');
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Заявка с тестового сайта';
$mail->Body    = '' .$name . ' оставил заявку, его телефон ' .$phone. '
Почта этого пользователя: ' .$email;
$mail->AltBody = '';

if(!$mail->send()) {
    echo 'Error';
} else {
    header('location: thank-you.html');
}
?>

A: Это рабочий код для отправки с яндекса:
PhpMailer-6.0.5
    //PhpMailer-6.0.5
    $mail = new PHPMailer(true);
    try {
        $mail->SMTPDebug = 2;
        $mail->isSMTP();
        $mail->Host = 'smtp.yandex.ru';
        $mail->SMTPAuth = true;
        $mail->Username = 'xxx@yandex.ru';
        $mail->Password = 'xxxxxx';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('xxxxx@yandex.ru', 'Mailer');
        $mail->addAddress('xxxxx@mail.ru', 'Joe User');
        $mail->isHTML(true);
        $mail->Subject = 'Here is the subject';
        $mail->Body    = 'This is the HTML message body in bold!';
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
    }

A: $mail->Host = "ssl://smtp.mail.ru";


text:
Q: Erro 403 disallowed_useragent, ao logar com google no navegador mobile usando angularfire2 Olá, estou utilizando o pacote angularfire2 v4.0.0-rc.2 em um projeto angular4 publicado no firebase.
Integrei os logins do facebook e do google e ambos estão funcionando perfeitamente no navegador do pc e também em um app android nativo.
Ao tentar logar utilizando o navegador do telefone, recebo uma tela de erro:

Encontrei vários posts sobre o google ter avisado que iria bloquear o acesso via webview, porém, isso faz muito tempo e a biblioteca angularfire2 já deveria estar atualizada para isso, provavelmente.
Tentei mudar o método de login via popup para login com redirect mas o resultado foi a mesma tela de erro no navegador do celular.


text:
Q: Retries with locked SQLite databases in Poco 1.5.x From Poco 1.3.4, Poco::Data::SQLite::SessionImpl supported the properties maxRetryAttempts, maxRetrySleep, and minRetrySleep which allowed control over automatic retries if the database was locked. These properties have been eliminated in Poco 1.5.0.
What is the proper way to handle locked database retries using Poco 1.5.x?

A: Looks like porting this change over to 1.5.x was simply forgotten. A GitHub issue has been created.


text:
Q: Error in MySQL sub query when adding "GROUP BY" I'm using MariaDB, and my subquery below returns results but if I add a the final line, being "GROUP BY linked_item" it returns the error "check the manual that corresponds to your MySQL server version."
Unsure why using GROUP BY is an error.  I need to output one totalsum per unique linked_item from the subquery result - any way to achieve this outcome would be fine.
This code returns the correct two column subquery result
SELECT linked_item, totalsum
FROM
(SELECT a.linked_item, a.total_actual_cost as totalsum FROM pl_detail a
WHERE a.total_actual_cost IS NOT NULL
UNION
SELECT b.linked_item, (b.number_units*b.cost_per_unit) as totalsum
FROM pl_detail b
WHERE b.total_actual_cost IS NULL) t

error when adding this line:
GROUP BY linked_item

A: use SUM (or another aggregate function) in your SELECT
SELECT linked_item, SUM(totalsum) as TotalSum
FROM
(SELECT a.linked_item, a.total_actual_cost as totalsum FROM pl_detail a
WHERE a.total_actual_cost IS NOT NULL
UNION
SELECT b.linked_item, (b.number_units*b.cost_per_unit) as totalsum
FROM pl_detail b
WHERE b.total_actual_cost IS NULL) t
GROUP BY linked_item

All columns need to be either an aggregate function OR in the GROUP BY clause

A: This is a minimized and faster query for your expected result by avoiding sub-queries. Here 3 queries are reduced to 1 query.
SELECT
  a.linked_item,
  SUM(
    CASE
      WHEN a.total_actual_cost IS NOT NULL
      THEN a.total_actual_cost
      WHEN a.total_actual_cost IS NULL
      THEN (a.number_units * a.cost_per_unit)
    END
  ) AS totalsum
FROM
  pl_detail a
GROUP BY a.linked_item


text:
Q: How do I convert Android Studio Project to Maven project? What is the way to export Android studio project to maven?  I know Studio/Gradle is more advanced build environment, but this is something I must do to fit it in with other existing projects. Should I import the Studio project into eclipse? What are the steps. Thanks

A: AFAIK : Till now there is no built in tool in eclipse to convert android studio project in eclipse environment but you can do it manually if needed.
Here are few simple steps to do it manually without less chances of errors and fixing.

Create New Eclipse Project with same package name
Add Library/Reference projects
Copy->Paste whole "res" folder as per eclipse project structure
Copy->Paste Java src packages for classes as per eclipse project
  structure
Copy Stuff's from Manifest.xml file
Setup build.xml configuration as needed anywhere in project like
  versions..

This steps works for me..
Let's discuss for any-other workaround if anyone has..


text:
Q: Tensorflow faster rcnn giving good detection but still detecting false positives with coco objects I have used the tensorflow API to detect the Guinness harp using the process described here - https://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/.
I have mostly good results, whenever the logo is clear in the image it finds it nicely -

However, after retraining from a coco checkpoint, it still detects what I think are coco objects with a very high confidence rating i.e people, magazines. I cannot work out why this is is.
(see below)

I am using the faster_rcnn_inception_v2_coco.config found here - https://github.com/tensorflow/models/blob/master/research/object_detection/samples/configs/faster_rcnn_inception_v2_coco.config
Training for more steps does not seem to help as the total loss averages out. The above screenshots were from 10,000 training steps. I am training on a cpu.
I am augmenting my training images using imgaug, and an example training image can be seen below ( i have included the debug bounding box around the target) -

However, if the training images were the problem, wouldn't the graph have trouble detecting the target altogether?

A: I had a similar issue recently, from what it somewhat looks like a case of underfitting, I tried multiple things to improve on the results.
The thing that worked for me was actually augmenting data using the library imgaug. You can augment the images as well as the bounding boxes using a simple script, try and increase the dataset by say 10/12 fold.
I would also suggest adding some background images, ie. images with no object, it was recommended by a few people in the tensorflow discussion in the issues.
Try and train the dataset again and monitor it using tensorboard. I think you will be able to reduce the number of false positives significantly.


text:
Q: Which package/program provides the Ctrl+Shift+U Unicode input utility? The title pretty much sums it up: where is this nifty functionality baked in, so I can report any bug I may encounter in it?

A: The Ctrl+Shift+U is baked in the GTK+3 code.
More specifically from the GtkIMContext


text:
Q: Calculate the sum of time column in PostgreSql Can anyone suggest me, the easiest way to find summation of time field in POSTGRESQL. i just find a solution for MYSQL but i need the POSTGRESQL version.
MYSQL: https://stackoverflow.com/questions/3054943/calculate-sum-time-with-mysql
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(timespent))) FROM myTable;

Demo Data
id   time
1   1:23:23
2   4:00:23
3   9:23:23

Desired Output
14:47:09

A: What you want, is not possible. But you probably misunderstood the time type: it represents a precise time-point in a day. It doesn't make much sense, to add two (or more) times. f.ex. '14:00' + '14:00' = '28:00' (but there are no 28th hour in a day).
What you probably want, is interval (which represents time intervals; hours, minutes, or even years). sum() supports interval arguments.
If you use intervals, it's just that simple:
SELECT sum(interval_col) FROM my_table;

Although, if you stick to the time type (but you have no reason to do that), you can cast it to interval to calculate with it:
SELECT sum(time_col::interval) FROM my_table;

But again, the result will be interval, because time values cannot exceed the 24th hour in a day.
Note: PostgreSQL will even do the cast for you, so sum(time_col) should work too, but the result is interval in this case too.

A: I tried this solution on sql fieddle:
link
Table creation:
CREATE TABLE time_table (
 id integer, time time
);

Insert data:
INSERT INTO time_table (id,time) VALUES
  (1,'1:23:23'),
  (2,'4:00:23'),
  (3,'9:23:23')

query the data:
SELECT
  sum(s.time)
FROM
  time_table s;

A: If you need to calculate sum of some field, according another field, you can do this:
select
    keyfield,
    sum(time_col::interval) totaltime
    FROM myTable
    GROUP by keyfield

Output example:
keyfield; totaltime
"Gabriel"; "10:00:00"
"John";    "36:00:00"
"Joseph";  "180:00:00"
Data type of totaltime is interval.


text:
Q: (IONIC) MomentJS locale not working after build I'm usign IONIC Framework and using Moment.js for dates.
When i'm setting all string in french using:
moment.locale('fr');

It works well on "serve" mode of ionic. But when i build the app for Android or Ios, all dates are en English.
Any idea?
Thank you!

A: Solved, i just included
moment/min/moment-with-locales.min.js

in place of
moment/moment.js
moment/locale/fr.js


text:
Q: opencv for windows XP I'm working with opencv in my last study's project. I have python 2.7 x86 and opencv 3.4 already installed.
I developed my python project in windows 8 64 bit and I converted my application from .py to .exe through Pyinstaller and it's working fine .
But when I move my application to the industrial machine which is windows xp pack 3 32bit and i try to import cv2 I get the following error :

ImportError: DLL load failed: The specified module could not be found.

Note that I have tried to install Microsoft visual c++ 2015 and didn't solve the problem and I try everything said about this problem on stackoverflow and didn't work with me .
Can anyone help me here ?

A: You should copy opencv.dll to directory contains .exe.

A: The latest supported version opencv for WindowsXP and with Python v3.4 support is '3.2.0.8'
You can still install it by following command:
pip install opencv-python==3.2.0.8


text:
Q: How to calculate png size based on dimension and bit depth I'm trying to generate white png (jpg, gif as well) files using imagemagick. I have to calculate image's dimension based on size(kb) and bit depth(1).
I'm using this command on my windows machine:
magick -size "width" x "height" canvas:black white.png

I'm getting the following results
1 x 1 = 258 bytes;
2 x 2 = 260;
9 x 9 = 262;
17 x 17 = 263;
33 x 33 = 264;
40 x 40 = 263;
41 x 41 = 265;
65 x 65 = 267;
66 x 66 = 268;

What I understood from the results above is that minimal size is 256 + 1 (width) + 1 (height). So 1 x 1 file's size would be 258, 2 x 2 = 260. Results that goes next to these two seems not logical for me, why 33x33 is bigger than 40x40?
I have read png specification but couldn't figure out the formula how to calculate png (or other formats) size?


text:
Q: Inf and sup methods in Sage In an exercice using Sage, I would need a method that returns the sup/inf of an interval, in such a way as to be able to use that value futher down in the code. Someting like $\mathtt{inf}([x>3])$ returns $3$ $-$ which looks ridiculous stated that way, but the interval would be given using the solve method on previously defined functions. Is there any (simple) way to do that?
Thanks


text:
Q: iMessages no longer working after Yosemite upgrade I just updated my MacBook Pro (Early 2011) to OS X Yosemite, now iMessages is no longer working. I turned it off/on on both my computer and my iPhone, reset my Keychain, and a bunch of other stuff. Nothing worked.
How can I fix this ?

A: After an hour long call with Apple, I was finally told to reset my default Keychain, and after a reboot, that worked. We diagnosed this as the issue because every time I rebooted, iCloud/FaceTime/Messages would ask for my password again, even though it had supposedly saved it.
This also came right after I had just reset the default Keychain to solve not being able to connect to my wireless network.

A: You'll just have to wait till iOS 8.1


text:
Q: SQL count of 90 day gaps between records Say I have a Payment table.  I need to know the number of times the gap between payments is greater than 90 days grouped by personID.  Payment frequency varies.  There is no expected number of payments.  There could 0 or hundreds of payments in a 90 day period.  If there was no payment for a year, that would count as 1. If there was a payment every month, the count would be 0.  If there were 4 payments the first month, then a 90 day gap, then 2 more payments, then another 90 day gap, the count would be 2.
CREATE TABLE Payments
(
    ID int PRIMARY KEY,
    PersonID int FOREIGN KEY REFERENCES Persons(ID),
    CreateDate datetime
)

A: If you have SQL Server 2014, you can use the LAG or LEAD function to peek at other rows, making this easy:
Select PersonId, Sum(InfrequentPayment) InfrequentPayments
from
(
    select PersonId
    , case
        when dateadd(day,@period,paymentdate) < coalesce(lead(PaymentDate) over (partition by personid order by PaymentDate),getutcdate())
        then 1
        else 0
      end InfrequentPayment
    from @Payment
) x
Group by PersonId

Demo: http://sqlfiddle.com/#!6/9eecb7d/491
Explanation:
The outer SQL is fairly trivial; we take the results of the inner SQL, group by PersonId, and count/sum the number of times they've paid payment judged as Infrequent.
The inner SQL is also simple; we're selecting every record, making a note of the person and whether that payment (or rather the delay after that payment) was judged infrequent.
The case statement determines what constitutes an infrequent payment.
Here we say that if the record's paymentdate plus 90 days is still earlier than the next payment (or current date if it's the last payment, so there's no next payment) then it's infrequent (1); otherwise it's not (0).
The coalesce is simply there to handle the last record for a person; i.e. so that if there is no next payment the current date is used (thus capturing anyone who's last payment was over 90 days before today).
Now for the "clever" bit: lead(PaymentDate) over (partition by personid order by PaymentDate).
LEAD is a new SQL function which lets you look at the record after the current one (LAG is to see the previous record).
If you're familiar with row_number() or rank() you may already understand what's going on here.
To determine the record after the current one we don't look at the current query though; rather we specify an order by clause just for this function; that's what's in the brackets after the over keyword.
We also want to only compare each person's payment dates with other payments made by them; not by any customer.  To achieve that we use the partition by clause.
I hope that makes sense / meets your requirement.  Please say if anything's unclear and I'll try to improve my explanation.

EDIT
For older versions of SQL, the same effect can be achieved by use or ROW_NUMBER and a LEFT OUTER JOIN; i.e.
;with cte (PersonId, PaymentDate, SequenceNo) as
(
    select PersonId
    , PaymentDate
    , ROW_NUMBER() over (partition by PersonId order by PaymentDate)
    from @Payment
)
select a.PersonId
, sum(case when dateadd(day,@period,a.paymentdate) < coalesce(b.paymentdate,getutcdate()) then 1 else 0 end) InfrequentPayments
from cte a
left outer join cte b
on b.PersonId = a.PersonId
and b.SequenceNo = a.SequenceNo + 1
Group by a.PersonId

Another method which should work on most databases (though less efficient)
select PersonId
, sum(InfrequentPayment) InfrequentPayments
from
(
    select PersonId
    , case when dateadd(day,@period,paymentdate) < coalesce((
        select min(PaymentDate)
        from @Payment b
        where b.personid = a.personid
        and b.paymentdate > a.paymentdate
    ),getutcdate()) then 1 else 0 end InfrequentPayment
    from @Payment a
) x
Group by PersonId

A: Generic query for this problem given a timestamp field would be something like this:
SELECT p1.personID, COUNT(*)
FROM payments p1
JOIN payments p2 ON
  p1.timestamp < p2.timestamp
  AND p1.personID = p2.personID
  AND NOT EXISTS (-- exclude combinations of p1 and p2 where p exists between them
   SELECT * FROM payments p
   WHERE p.personID = p1.personID
   AND p.timestamp > p1.timestamp
   AND p.timestamp < p2.timestamp)
WHERE
  DATEDIFF(p2.timestamp, p1.timestamp) >= 90
GROUP BY p1.personID


text:
Q: Prestashop - Header links I have a Prestashop installation and am trying to add pages to it. I want the pages to show up with the HOME and CONTACT links and not in the information block. I take it I need to edit code, but where? Do I hard code the pages? Or can I create the page with the CMS in tools and just add a link in the headerlinks for that page?

A: AH, I found it. For any who may also be looking for this, you can edit this directly like this:
Find the 'modules/blockpermanantlinks/ directory and edit the blockpermanentlinks-header.tpl file. You will need to set up target pages manually too. I just pointed to information CMS pages I made earlier.

A: @Stefan, in PS 1.4, you need to let Smarty Force a Compile in order to see changes you make while testing or changing the elements/appearance of a page.
Go to Preferences > Performance, and change to Force Compile: Yes, w/ Cache: No, while you are testing changes. When you are done, change those two settings back to Force Compile: No and Cache: Yes.


text:
Q: How to pass property value in SqlDataSource selectCommand where conditon? I have a property in my page2.aspx.cs page
public int? Id
{
        get
        {
            if (ViewState[Page1.Id] != null)
                return Convert.ToInt32(ViewState[Page1.Id]);
            else return null;
        }
        set
        {
            ViewState[Id] = value;
        }
    }

and I am using asp: data sourse:
<asp:SqlDataSource ID="SqlDataSourceGridView" runat="server"
   ProviderName="System.Data.SqlClient"
   SelectCommand="SELECT [Name],[Address] FROM [Table_Emp] where Id = need to pass property value >"
   OnSelecting="SqlDataSourceGridView_Selecting">
</asp:SqlDataSource>

I want to pass Id in my where condition. how is it possible.
Please some one help me.

A: Here, take a look
 <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
   SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

   InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName);
                  SELECT @EmpID = SCOPE_IDENTITY()"
   UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName
                    WHERE EmployeeID=@EmployeeID"
   DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID"

   ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
   OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
   RunAt="server">

   <SelectParameters>
     <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
   </SelectParameters>

   <InsertParameters>
     <asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
   </InsertParameters>

 </asp:sqlDataSource>

A: 1) insert placeholder with parameter name like @Id to you select-query
2) Add parameter specification of your Id parameter to <SelectParameter> section of SqlDataSource
<asp:SqlDataSource ID="SqlDataSourceGridView" runat="server"
     ProviderName="System.Data.SqlClient"
     SelectCommand="SELECT [Name],[Address] FROM [Table_Emp] where Id = @Id"
     OnSelecting="SqlDataSourceGridView_Selecting">

    <SelectParameters>
         <asp:Parameter Name="Id" Type="Int32" />
    </SelectParameters>

</asp:SqlDataSource>

3) in Selecting event method put parameter value to the command
protected void SqlDataSourceGridView_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["@Id"].Value = (int)(Id ?? 0); // nullable ind is not applicable here
}

A: You have to use  Node under SQLDataSource.
Have a look here : MSDN Reference or Tutorial
<asp:SqlDataSource ID="SqlDataSourceGridView" runat="server"
   ProviderName="System.Data.SqlClient"
   SelectCommand="SELECT [Name],[Address] FROM [Table_Emp] where Id = need to pass property value >"
   OnSelecting="SqlDataSourceGridView_Selecting">

   <SelectParameters>
     <asp:Parameter Name="ParameterName" />
   </SelectParameters>

</asp:SqlDataSource>

OT : you have an error on property Id. you set ViewState[Id] but you try to retrieve
Viewstate[Page.id]

A: You can set this from code behind. Just define a select parameter in your sql datasource like
    <asp:SqlDataSource ID="SqlDataSourceGridView" runat="server"
   ProviderName="System.Data.SqlClient"
   SelectCommand="SELECT [Name],[Address] FROM [Table_Emp] where Id =@id"
   OnSelecting="SqlDataSourceGridView_Selecting">
  <SelectParameters>
        <asp:Parameter Name="@id" Type="Int32" />
    </SelectParameters>

Then in your code behind you can set the parameter manually like
SqlDataSourceGridView.SelectParameters["@id"].DefaultValue = yourValue;
Gridview1.DataBind();


text:
Q: Python regex to extract tokens I am trying to find all the tokens which look either like abc_rty or abc_45 or abc09_23k or abc09-K34 or 4535. The tokens shouldn't start with _ or - or numbers.
I am not making any progress and have even lost the progress that I did. This is what I have now:
r'(?<!0-9)[(a-zA-Z)+]_(?=a-zA-Z0-9)|(?<!0-9)[(a-zA-Z)+]-(?=a-zA-Z0-9)\w+'

To make the question more clear here is an example:
If i have a string as follows:
    D923-44 43 uou 08*) %%5 89ANB -iopu9 _M89 _97N hi_hello

Then it shall accept
    D923-44 and 43 and uou and hi_hello

It should ignore
    08*) %%5 89ANB -iopu9 _M89 _97N

I might have missed some cases but i think the text would be enough. Apologies if its not

A: This appears to work as desired:
regex = re.compile(r"""
    (?<!\S)   # Assert there is no non-whitespace before the current character
    (?:       # Start of non-capturing group:
     [^\W\d_] # Match either a letter
     [\w-]*   # followed by any number of the allowed characters
    |         # or
     \d+      # match a string of digits.
    )         # End of group
    (?!\S)    # Assert there is no non-whitespace after the current character""",
    re.VERBOSE)

See it on regex101.com.

A: ^(\d+|[A-Za-z][\w_-]*)$

Edit live on Debuggex
split the line with a space delimiter then run this REGEX through the line to filter.

*

*^ is the start of the line

*\d means digits [0-9]

*+ means one or more

*| means OR

*[A-Za-z] first character must be a letter

*[\w_-]* There can be any alphanumeric _ + character after it or nothing at all.

*$ means the end of the line

The flow of the REGEX is shown in the chart I provided, which somewhat explains how it's happening.
However, ill explain basically it checks to see if it's all digits OR it starts with a letter(upper/lower) then after that letter it checks for any alphanumeric _ + character until the end of the line.


text:
Q: Is there a fix for Skyrim's bug for Glory of the Dead? I recently got Skyrim Complete edition, the one with all the add-ons. I have it installed on my hard drive for Xbox 360. I have many quests open, but the one I can't do is the Companions mission - Glory of the Dead.
I started the mission before, to kill the witches at the coven and get the heads. I have all the witches' heads with me. I got back to Whiterun and saw Kodlak was dead. I then proceeded to the Silver Hand fort and wiped them all out. I then fast travelled back to Whiterun, where Vilkas said that the funeral will start and I must go to the Skyforge. I then proceeded up to the Skyforge, where Aela starts talking. They light Kodlak's body on fire, and that's it. Nothing. There was something said about the Underforge, but the quest marker did not point there. It still says "Attend Kodlak's funeral".
Now every time I go to Whiterun, the Skyforge has all the people there (the Jarl and steward, some villagers, and the companions) but they all just stand there. Vilkas, Farkas, and Aela are all there. But the person not there is Eorlund Gray-Mane. I know he is needed because you must give him the fragments of Wuurstal.
I have done more quests after this bug, even built a house by Lakeview. But every time I go to Whiterun the people just stand there, the pyre burning and nothing happens. I have gone to the stables and entered on foot. I have uninstalled the game and run it from the disc. I have waited till evening and morning. I have slept. Waited there. Gone about my business. Even went back to the witches coven and the Silver Hand places. I just killed one lonely Silver Hand guy outside the fort, but nothing changed when I got to Whiterun.
Please has anybody solved this glitch for the Xbox 360? I want this mission done, so I can talk to those just standing there and continue the game because I read that the Jarl is needed in order to progress the main quest-line

A: NOTE
I have just written out this entire answer then learned it may be possible to get your save up and running in Skyrim for PC where it could be debugged properly. I'm unsure how likely this is to work in reality but I would be more than happy to point you to an article that explains how to extract your save and I'd be happy to attempt to examine it on PC for you. Never-the-less it's a long shot so here's my original answer.

I just wanted to provide a concrete answer here of what I think you're already aware of; without a save from just prior to returning to Whiterun there's nothing to be done.
I've spent a while looking for this bug but cannot find it, and I never experienced it myself on PC - it's likely XB360 only.
Going forward always bear in mind that the Creation Engine - upon which Skyrim is built - is prone to such bugs. In a more linear game this bug would probably have been found by the developers but due to the complexity of in-game story branches in Skyrim (and all TES titles) it's almost impossible to test for all eventualities.
I know it's frustrating but going forward there are things that you can do:

*

*Save, save and save some more. I tend to have three or four saves per play through, on top of the standard auto saves. Make the saves at regular intervals and before making big decisions.

*Did I mention save? When saving if you overwrite a previous save only do so if you're happy that there were no problems since then. For example if you made a save right after destroying the silver hand and before returning to Whiterun then went to save again at the Skyforge I would NOT overwrite as I know that save may not have the buggy event that caused Euorland to disappear which means you may be able to do something differently to skip the bug.

*Check the quest journal and markers. Even if you role play a realistic play through without using UI like a compass and markers if you think something may be amiss check the journal; has a/the quest appeared/disappeared? Has an objective updated? Are there any quest markers on the map (almost every quest objective has a marker)? If not this is a sign there's something wrong - make a new save and don't overwrite any previous saves and try to confirm there is a bug. If so, revert your save and try something different, perhaps Google the bug - if someone else has seen it there's likely already a solution if you have a pre-bug save.

*Don't rush. The Creation Engine is old and running on old tech like the XB360 can make it run unexpectedly slow in the background. As such try not to rush it as it could skip certain stages of processes. For example if you complete a quest and expect a reward that didn't appear straight away, wait for it - even for a few minutes, this does happen. If not a quick reload of a save from before you turned in the quest will likely solve it. The worst thing to do here is start new quests or run off to another cell (city, house, save etc.) - this could make the game forget what it was doing.

*Don't do too much at once. Try to keep the number of quests in your journal to a minimum, especially related ones. The more quests you have active the more chance there is of conflicts. If you're unsure check for the quest over on the UESP Skyrim Quests page and look for bugs (bottom of the page) - there may be a spoiler or two but it's worth it if it keeps the game working.

I know that's an awful lot to do when you expect the game to just work but the shear size and complexity is the main cause of your problems. The main thing is Saving before you do something that could have a bug. I'm unsure how many saves the XB360 can hold but I would use as many as possible and only overwrite when you're certain that there has been a save since then without any problems in it.
Best of luck with your adventures - I really am sorry that we're unable to help rescue this save.

A: I might have a delayed answer but its a working one.
I had the same issue and this youtube video addressed it.


text:
Q: How to restrict specail character Grave accent (backtick) in text box using angular js i wants to validate text box which allows special character like []^_,atoz,1 to 10 characters.am using ng-pattern="/^[a-zA-Z0-9]*$/" it allows to enter but it doesnot enable submit button.But the problem is we should not allow user to enter special characters especially  Grave accent (`):
<input type="text" ng-pattern="/^[a-zA-Z0-9]*$/">

and also am using following validation:
<input type="text" restrict="^[^a-zA-Z0-9]*$/">

kindly help me.thanks in advance.

A: You can use Directive
directive('noSpecialChar', function() {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, element, attrs, modelCtrl) {
                    modelCtrl.$parsers.push(function (inputValue) {

                            if (inputValue == null)
                                return ''
                            var cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
                            if (cleanInputValue != inputValue) {
                                modelCtrl.$setViewValue(cleanInputValue);
                                modelCtrl.$render();
                            }
                            return cleanInputValue;

                    });
                }
            }
        })

HTML
<input type='text' no-Special-Char />


text:
Q: warning: ISO C++ forbids variable length array I have a function that takes a pointer to a floating point array. Based on other conditions, I know that pointer is actually pointing to a 2x2 OR 3x3 matrix. (in fact the memory was initially allocated as such, e.g. float M[2][2] ) The important thing is I want to make this determination in the function body, not as the function argument.
void calcMatrix( int face, float * matrixReturnAsArray )
{
    // Here, I would much rather work in natural matrix notation
    if( is2x2 )
    {
        // ### cast matrixReturnAsArray to somethingAsMatrix[2][2]
        somethingAsMatrix[0][1] = 2.002;
        // etc..
    }
    else if(is3x3)
    { //etc...
    }

}

float (somethingAsMatrix)[2] = (float ()[2]) matrixReturnAsArray;

this works fine.
here if i want mention value in subscript as a variable which will change based on some conditions.
If i do this, it showing warning: ISO C++ forbids variable length array. From this how can i dynamically create something?

A: Array in C++ must have a size defined at compile-time.
If you want variable length array, use std::vector instead.
In your case, I would use template for Matrix Size and have different implementation for different matrix size (unless I misunderstood your intentions).
template<int SIZE>
    struct Matrix {
    std::array<std::array<float, SIZE>,SIZE> m;
    std::array<float,SIZE>& operator[](int a) {
        if(a>=SIZE) {
            throw std::out_of_range("Out of range exception");
        }
        return m[a];
    }
};

template<int SIZE>
void calcMatrix(Matrix<SIZE>& matrixReturnAsArray );

template<>
void calcMatrix<2>(Matrix<2>& matrixReturnAsArray )
{
     // Code for 2x2 Matrix
    std::cout << "<2>" << std::endl;
    std::cout << matrixReturnAsArray[1][1] << std::endl;
}

template<>
void calcMatrix<3>(Matrix<3>& matrixReturnAsArray )
{
     // Code for 3x3 matrix
        std::cout << "<3>" << std::endl;
        std::cout << matrixReturnAsArray[2][2] << std::endl;
}

int main() {
   std::array<float,2> a={1,2};
   Matrix<2> m2;
   m2.m = {a,a};
   std::array<float,3> b={1,2,3};
   Matrix<3> m3;
   m3.m = {b,b,b};
   calcMatrix(m3);
   calcMatrix(m2);
}

Since I did not defined the generic template, using any other value than 2 or 3 for size will result in an error at compile time.
Edit :
Used reference to std::array instead of pointer after @Caleth's suggestion
Edit 2:
Added operator [] for easy access and exception for safety

A: You can pass an array by reference.
void calcMatrix(float (&matrix)[2][2])   // Only binds to 2*2 matrix
{
}
void calcMatrix(float (&matrix)[3][3])   // Only binds to 3*3 matrix
{
}

int main()
{
   float a[2][2] ={{1,2} , {3,4}};
   calcMatrix(a);

   float b[3][3] ={{1,2,3} , {4,5,6}, {7,8,9}};
   calcMatrix(b);
}

If you want a function that works for varying sizes you can templatize it:
template<int S>
void calcMatrix(float (&matrix)[S][S])   // Only binds to S*S matrix
{
}

A: The following shows how to do the casts.
#include <stdio.h>

typedef float t2[2][2];
typedef float t3[3][3];

static void test(int is2, void * p)
{
    if(is2)
    {
        t2 *a = (t2 *)p;
        (*a)[1][1] = 1.23;
    }
    else
    {
        (*((t3*)p))[1][1] = 2.34;
    }
}

int main()
{
    printf("Hello World\n");
    t2 test2 = {{1,2},{3,4}};
    t3 test3 = {{1,2,3},{4,5,6},{7,8,9}};

    test(1,(void *)test2);
    printf("%g\n",test2[1][1]);

    test(0,(void *)test3);
    printf("%g\n",test3[1][1]);

    return 0;
}


text:
Q: custom google form email notification I am using the below app script to generate a random id in the header UID in the google form response sheet and then by default the script is mailing the UID to the form user who is submitting the form.
I want the script to generate the random uid but instead of sending the UID value in the email it should let me specify another header where I am tweaking the random UID.
any help will be highly appreciated.
const sheetName = "Responses"; // replace this sheet name with yours
    const uidHeader = "_UID"; // column name of UID in response sheet
    const uidPrefix = "UID-"; // UID prefeix
    const uidDigitLength = 5; // digit length of UID

    function _onFormSubmit(e) {
      const { rowStart } = e.range
      var url = SpreadsheetApp.getActive().getFormUrl();
      var form = FormApp.openByUrl(url);
      var response = form.getResponses().pop();
      var url = form.getPublishedUrl();
      const editUrl = response.getEditResponseUrl()
      var responseId = response.getId();
      // for sequential id
      //var uid = createUid(responseId);

      // for random id
      var uid = createRandomUid(responseId);
      writeUidToSheet(uid, rowStart);

      var title = "Thanks for your submission";
    //  var lastItem = response.getItemResponses().pop();
      var email = response.getRespondentEmail();
      if (email){
        var subject = form.getTitle();
        var htmlBody = "

" +
                       "" +
                        "
" +
                         title + "
" +
                         "
UID
" +
                         "
" +
                           "
UID
" +
                           "
" + uid +"
" +
                         "
" +
                         "
Submit another response
" +
                         "
Edit your response
" +
                         "
Thanks,
Ashton Fei
" +
                         "

";
        var options = {
          htmlBody: htmlBody
        };
        GmailApp.sendEmail(email, subject, "", options);
      }
    }
      // Write uid to the responses sheet
    function writeUidToSheet(uid, rowStart){
      var ws = SpreadsheetApp.getActive().getSheetByName(sheetName);
      var dataRange = ws.getDataRange();
      var values = dataRange.getValues();
      var headers = values[0];
      var indexUid;

      // Locate the index of header UID
      for(var c = 0; c < headers.length; c ++){
        if(headers[c] === uidHeader){
          indexUid = c;
          break;
        }
      }

      // Insert a new column in B if UID column is not found
      if (indexUid === undefined){
        ws.insertColumnsAfter(1, 1);
        indexUid = 1;
        ws.getRange("B1").setValue(uidHeader);
        dataRange = ws.getDataRange();
        values = dataRange.getValues();
      }

      // Check UID's in the sheet row by row
      var isNewUid = true;
      for (var r = 1; r < values.length; r ++){
        var currentUid = values[r][indexUid];
        if (currentUid === uid){
          isNewUid = false;
          break;
        }
      }

      if (isNewUid){
        ws.getRange(rowStart, indexUid + 1).setValue(uid)
      }
    }

    // Create a UID in document properties
    function createUid(responseId){
      var docProperties = PropertiesService.getDocumentProperties();
      var key = "uid";
      var id = 1;
      if (docProperties.getProperty(responseId)){
        var uid = docProperties.getProperty(responseId);
      }else{
        if(docProperties.getProperty(key)){
          id = parseInt(docProperties.getProperty(key));
        }

        var uid = (Math.pow(10, uidDigitLength) + id).toString().substring(1, uidDigitLength+1);
        uid = uidPrefix + uid;

        docProperties.setProperty(key, id + 1);
        docProperties.setProperty(responseId, uid);
      }
      return uid;
    }

    // function a random uid in document properties
    function createRandomUid(responseId){
      var docProperties = PropertiesService.getDocumentProperties();
      var key = "randomUids";
      var ids = [];
      if (docProperties.getProperty(responseId)){
        var uid = docProperties.getProperty(responseId);
      }else{
        if(docProperties.getProperty(key)){
          ids = JSON.parse(docProperties.getProperty(key));
        }

        do{
          var randomNumber = Math.pow(10, uidDigitLength) + Math.floor(Math.random() * Math.pow(10, uidDigitLength));
          var uid = randomNumber.toString().substring(1, uidDigitLength + 1);
          uid = uidPrefix + uid;
        }while (ids.indexOf(uid) !== -1)

        ids.push(uid)
        docProperties.setProperty(key, JSON.stringify(ids));
        docProperties.setProperty(responseId, uid);
      }
      return uid;
    }

    // Remove all properties from the document properties object, so the uid can be reset
    function resetForm(){
      var ui = SpreadsheetApp.getUi();
      var prompt = "This action will delete all responses in the form";
      if (ui.alert("Confirmation",prompt, ui.ButtonSet.OK_CANCEL) === ui.Button.OK){
        PropertiesService.getDocumentProperties().deleteAllProperties();
        const url = SpreadsheetApp.getActive().getFormUrl();
        const form = FormApp.openByUrl(url)
        form.deleteAllResponses();
        var msg = 'All responses have been deleted and UID has been reset. You need to manually remove the old data in sheet "' + sheetName + '".';
        SpreadsheetApp.getActive().toast(msg, "Google Apps Script", 15);
      }
    }

    function onOpen(){
      var ui = SpreadsheetApp.getUi();
      ui.createMenu("Scripts")
        .addItem("Reset form", "resetForm")
        .addToUi();
    }


text:
Q: How would i make users be able to input minutes to change the countdown time? I would like to be able to make users choose how many minutes the timer should countdown for, what should I change/add to this script? BTW I have no prior experience in Javascript and I'm learning right now, so please keep that in mind! Any help is MUCH appreciated. This is a timer that should count down minutes, this is the design I have done in html and css:

I want the users to enter a "work time" and a "break time" so that the timer counts down the work time and when thats done it automatically counts down the break time and repeat. As i said earlier this is my first "js project" so any help is much needed and appreciated!

var countDownDate = new Date("Oct 16, 2021 20:37:25").getTime();

var x = setInterval(function() {

  var now = new Date().getTime();

  var distance = countDownDate - now;

  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";

  }
}, 1000);
</script>

Here is the HTML form to select minutes:

<form action="."> <input type="number" value="1" class="TaskTime"/>Work Minutes</> <input type="number" value="1" class="BreakTime"/>Break Minutes</> <button type="submit" class="submitt">Save</button>

A: As mentioned by @testing-22, it depends on html code but I think you need something like this:

    00:00

    <button onclick="start()">Start!</button>
    <button onclick="stop()">Stop!</button>
    <button onclick="reset()">Reset!</button>

    <input type="text" id="txtWorkMinutes" value="2" />

    Work Minutes

    <input type="text" id="txtBreakMinutes" value="1" />

    Break Minutes

    <button onclick="save()">Save</button>

To show the timer by pad, you can have a look at Is there a JavaScript function that can pad a string to get to a determined length?


text:
Q: Legends overlapping the plots in Rstudio I am trying to plot an image and then overlay a legend on its top. The legend is covering the plot and I am not able to adjust it using different parameters like cex, lty, etc.
plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
 col=(cov16_2ms04h$binom_q<0.001)+1,
 ylab="Haplotype B Count", xlab="Haplotype A Count")
abline(0,1,col="grey")
legend("topleft",c("No significant imbalance","Significant imbalance"),pch=c(10,10),col=c(1,2), cex = 0.5)

is giving me plot as:

But, I want something like:

Thanks,

A: have you tried enlarge the size of the plot before overlying a legend? I tried you legend code, the legend was perfect on the plot.

A: The problem is with R-studio because the size of the output plot is determined by the costumized size of the pane.
To plot the results directly to a pdf or a png file the following can be done.
# plotting directly on pdf or png - select the required one
pdf("my_plot.pdf", height=6, width=6)
png("my_plot.png", width = 4, height = 4,
    units = 'in', res = 300)

plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
     col=(cov16_2ms04h$binom_q<0.001)+1,
     ylab="Haplotype B Count", xlab="Haplotype A Count")

abline(0,1,col="grey") # draw abline

legend("topleft",c("No significant imbalance","Significant imbalance"),
   pch=c(1,1),col=c(1,2), cex = 0.75)  # add legend

dev.off() # close the plot

The output then comes as:

Thanks,


text:
Q: Detecting iPhone/iPod Touch Accessories Is it possible to detect if the iPod Touch/iPhone has any headphones or other accessories connected to it?
I'm building an app that requires a microphone, and need to know if the "iSomething" has one connected or not, either via the dock connection, or using the headphone port, such as with the inline headphone/microphone accessory from Apple.

A: Or you could use:
if (![[AVAudioSession sharedInstance] inputIsAvailable]) {
    // your code here for no audio input available
}

A: In IOS 6 inputIsAvailable is deprecated. In the future we need to use inputAvailable:
BOOL audioHWAvailable = audioSession.inputAvailable;

A: Finally found it - After initializing the Audio Session object, - AudioSessionInitialize() - you can make a call to AudioSessionGetProperty, and get the value of kAudioSessionProperty_AudioInputAvailable.
AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 propertySize, micConnected;
    AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &propertySize, &micConnected);
    [self updateMicStatus:micConnected]; // user-created method

According to the docs for Audio Session Services, this should be used rather than using the device model (iPhone vs. iPod Touch) to determine if an audio input is available to use. You can also set up a callback function to monitor changes to this property via AudioSessionAddPropertyListener().
Not sure yet if this property also applies to devices connected via the Dock connector, but it appears to work for the headphone jack.

A: To determine if the device has a built in microphone you can just go by [UIDevice currentDevice].model to see if it's an iPhone or a 2nd generation iPod Touch.  As far as a third-party microphone plugged into the dock connector, this is not possible in the current 2.2.1 SDK, but it may be in a later version :)

A: Here is the solution, you may like it or it is helpful to you.
Before using below method please write this two line also
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

- (void)isHeadsetPluggedIn {

    UInt32 routeSize = sizeof (CFStringRef);
    CFStringRef route;

    AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                              &routeSize,
                                              &route);

    //NSLog(@"Error >>>>>>>>>> :%@", error);
    /* Known values of route:
     * "Headset"
     * "Headphone"
     * "Speaker"
     * "SpeakerAndMicrophone"
     * "HeadphonesAndMicrophone"
     * "HeadsetInOut"
     * "ReceiverAndMicrophone"
     * "Lineout"
     */

    NSString* routeStr = (NSString*)route;

    NSRange headsetRange = [routeStr rangeOfString : @"Headset"];
    NSRange receiverRange = [routeStr rangeOfString : @"Receiver"];

    if(headsetRange.location != NSNotFound) {
        // Don't change the route if the headset is plugged in.
        NSLog(@"headphone is plugged in ");
    }
    else if (receiverRange.location != NSNotFound) {
        // Change to play on the speaker
        NSLog(@"play on the speaker");

    }
    else {
        NSLog(@"Unknown audio route.");

    }
}


text:
Q: Struts 2 make dynamic parameter I am using Struts 2 and JavaScript. I want to edit a parameter value or add parameter to URL with JavaScript to make dynamic parameter. I can not set value for param why this not have id. Any other form of do?
var urle = document.getElementsByName("vari");
    urle.value = 5;

<s:url var="urlex" action="actionDo"><s:param name="vari" value=""/></s:url>

A: Struts tags are JSP tags that compiled and executed on server, JavaScript is executed on client browser. You can't access the server from javascript code without making ajax request. But you don't need too. Use
var url = '<s:url var="urlex" action="actionDo">' +'?vari=' + val;

A:

You have to set jsonObject when this action class has been called. So according to set parameter it will set parameter dynamic.


text:
Q: Why is Dirac Lagrangian in Curved Spacetime Weyl Invariant? Are there any references on the Weyl invariance of the Dirac Lagragian in general spacetime?

A: The (massless) Dirac Lagrangian is Weyl invariant on-shell. Please see the following review article by Forger and Romer. In this article, a theorem (5.1) was formulated stating that actions have stress energy tensors of vanishing trace iff they are locally Weyl invariant on shell.


text:
Q: NSTableView: How to resize text in cells correctly I need to increase the font size in an NSTableView (view based mode) to allow for better readability in some kind of a presentation of my app.
Changing the font works fine within - (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row:
    NSTableCellView *cellView = [tableView makeViewWithIdentifier:identifier owner:self];
    [cellView.textField setFont:self.tableFont];
    cellView.textField.stringValue = rowData[row];
    [cellView.textField setNeedsDisplay:YES];

I also update the rowHeight with - (CGFloat) tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row, this also works:
- (CGFloat) tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    if (self.tableFont) {
        NSLog(@"Setting row height to %.1f", [self.tableFont pointSize]+8);
        return [self.tableFont pointSize] + 8;
    }
    return [NSFont systemFontSize] + 8;
}

(There are probably way more elegant ways to determine the correct height)
Now, here is my issue:
I do see the font being changed. I also see the rowHeight being changed (nicely visible as I use alternate row colouring). But the text within the cells seems to be clipped to its old height (probably 17 pixels), so with larger font sizes I only see the top of the writing, then some white space, and then again the the upper part of the next row.
For me it looks like some view clips the NSTableViewCell to its old height... I already played with setting the frames and bounds to different values, but this didn't change anything:
    NSRect rect = [cellView.textField frame];
    rect.origin.y = 1;
    rect.size.height = [self.tableFont pointSize] + 6;
    [[cellView.textField cell] setFrame:rect];
    [cellView.textField setFrame:rect];
    [cellView.textField setBounds:rect];
    [cellView.textField setNeedsDisplay:YES];
    [cellView setFrame:rect];
    [cellView setBounds:rect];
    [cellView setNeedsDisplay:YES];

I am kind of lost here... I guess I am missing something simple, but I have no idea where to look...
Thanks,
Jan

A: You have to make sure your constraints are set so your NSTextField can grow automatically when the autolayout pass is hit—there shouldn't be ANY constraint on the height of the NSTextField, because it'll have an intrinsic height that's based on the fontSize.
Also, in view-based mode, there is also a misfeature where the cellView's 'textField' and 'imageView' outlets are treated specially: in NSTableCellView will actually sets the frame DIRECTLY on its textField and imageView in its -viewWillDraw, ignoring horizontal constraints and breaking their own rules on layout. (This is filed as Radars 11713245 & 15359487).
Here's the code I use to work around this misfeature in my custom NSTableCellView class for 10.8 and 10.9. Note in my case I only needed to reset the x offsets of the fields:
#pragma mark NSView

- (void)viewWillDraw;
{
    const NSRect imageViewFrame = self.imageView.frame, textFieldFrame = self.textField.frame;

    [super viewWillDraw]; // NSTableCellView in  source list-mode outline view will apply custom metrics and positioning here by calling -_doStandardRowSizeStyleLayout, which manually calls setFrame: on the textField and imageView, screwing up our autolayout...

    // ...so put the x offsets back the way we really wanted them, dammit (Radar 11713245, 15359487)
    if (imageViewFrame.origin.x != self.imageView.frame.origin.x)
        [self.imageView setFrameOrigin:(NSPoint){imageViewFrame.origin.x, self.imageView.frame.origin.y}];

    if (textFieldFrame.origin.x != self.textField.frame.origin.x)
        [self.textField setFrameOrigin:(NSPoint){textFieldFrame.origin.x, self.textField.frame.origin.y}];
    if (textFieldFrame.size.width != self.textField.frame.size.width)
        [self.textField setFrameSize:(NSSize){textFieldFrame.size.width, self.textField.frame.size.height}];
}


text:
Q: Accessing elements in the shadow DOM Is it possible to find elements inside the Shadow DOM with python-selenium?
Example use case:
I have this input with type="date":

<input type="date">

And I'd like to click the date picker button on the right and choose a date from the calendar.
If you would inspect the element in Chrome Developer Tools and expand the shadow-root node of the date input, you would see the button is appearing as:

Screenshot demonstrating how it looks in Chrome:

Finding the "picker" button by id results into NoSuchElementException:
>>> date_input = driver.find_element_by_name('bday')
>>> date_input.find_element_by_id('picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element

I've also tried to use ::shadow and /deep/ locators as suggested here:
>>> driver.find_element_by_css_selector('input[name=bday]::shadow #picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element
>>>
>>> driver.find_element_by_css_selector('input[name=bday] /deep/ #picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element

Note that I can change the date in the input by sending keys to it:
driver.find_element_by_name('bday').send_keys('01/11/2014')

But, I want to set the date specifically by choosing it from a calendar.

A: The accepted answer has a drawback, many times the shadow host elements are hidden withing shadow trees that's why the best way to do it is to use the selenium selectors to find the shadow host elements and inject the script just to take the shadow root:
def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

#the accepted answer code then becomes
outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()

To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:

import selenium
from selenium import webdriver
driver = webdriver.Chrome()

def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)

root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)

root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)

search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()

Doing the same using the accepted answer approach has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:
search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()

A: There's no way to access the shadow root of native HTML 5 elements.
Not useful in this case, but with Chrome it's possible to access a custom created shadow root:

var root = document.querySelector("#test_button").createShadowRoot();
root.innerHTML = "<button id='inner_button'>Button in button</button"
<button id="test_button"></button>

The root can then be accessed this way:
 var element = document.querySelector("#test_button").shadowRoot;

If you want to automate a click on the inner button with selenium python (chromedriver version 2.14+):
 >>> outer = driver.execute_script('return document.querySelector("#test_button").shadowRoot')
 >>> inner = outer.find_element_by_id("inner_button")
 >>> inner.click()

Update 9 Jun 2015
This is the link to the current Shadow DOM W3C Editor's draft on github:
http://w3c.github.io/webcomponents/spec/shadow/
If you're interested in browsing the blink source code, this is a good starting point.


text:
Q: Inject reference to async service - drawbacks If in my GWT UI component I am using @Inject for reference of my CoolServiceAsync interface - will that create separate instance of the "implementation" of that service from GWT bindings? Or it is singleton and same instance of JavaScript object will be shared among all components?

A: You must probably specify what you use for IoC in GWT. I assume you use google-gin. Unless you specify a binding as singleton, it will be created with help of GWT.create(), because of the deferred binding. GWT.create() always returns new instance.


text:
Q: Unity how to check what object triggered a trigger I am in the middle of creating a simple 3d platformer in unity and i'm trying to make it so if you are in a certain radius and you hit the "f" key the enemy will disappear. the way i'm checking to make sure the enemy is close enough to be attacked is to have trigger sphere and when its triggered and you press "f" the enemy will be removed. i'm currently trying to see what collided with the trigger but i cant figure it out. here is my current code
using UnityEngine;

public class PlayerCombat : MonoBehaviour
{
 public GameObject Enemy1;
 public GameObject Enemy2;
 public GameObject Enemy3;
 public GameObject Enemy4;

    // Update is called once per frame
void OnTriggerEnter (Trigger triggerInfo)
    {
        if (triggerInfo.collider.tag == "Enemy" & Input.GetKey("f"))
        {
            if (triggerInfo.collider.name == Enemy)
            {
                Enemy1.SetActive(false);
            }
        }
    }
}

A: First, I'm pretty sure OnTriggerEnter takes a Collider as its parameter, no? https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
You can get the name of the collided object like so
    //Upon collision with another GameObject,
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log($"collided with {other.gameObject.name}");

        //you can check for specific components too
        MyComponent myComponent = other.GetComponent<MyComponent>();
        if (myComponent != null) {
            // do something if it has that component on it!
        }

    }

A: The signature is and has always been OnTriggerEnter(Collider) otherwise that message method will not be recognized by Unity and not get called at all!
And then you already have the according Collider ... what else do you need?
public class PlayerCombat : MonoBehaviour
{
    // There is no need to know the enemy references beforehand at all
    // you will get all required references from the Collider parameter of OnTriggerEnter itself

    // I personally would however expose these two settings to the Inspector to be more flexible
    // this way you can adjust these two settings within Unity without having to touch your code
    public string listenToTag = "Enemy";
    public KeyCode listenToKey = KeyCode.F;

    // The signature has to be this otherwise the message method is never invoked at all
    private void OnTriggerEnter (Collider other)
    {
        // Rather use "CompareTag" instead of `==` since the latter will silently fail
        // for typos and nonexistent tags while "CompareTag" shows an error which is good for your debugging
        // And in general you want to use the logical "&&" instead of the bitwise operator "&" for bools
        if (other.CompareTag(listenToTag) && Input.GetKey(listenToKey))
        {
            // simply set the object you collide with inactive
            other.gameObject.SetActive(false);
        }
    }
}

Finally just make sure that all your enemy instances actually have the tag Enemy