text:
Q: Why still using richfaces/primefaces with jsf 2.0? During an interview, i had this question :

why still using richfaces or primefaces with jsf 2.0? jsf 2.0 has the ajax capabilities, so what is the advantage of those frameworks vs jsf 2.x ?

A: Primefaces is a framework on top of JSF-2, and provides components with functionality that would take a big effort to implement in "raw" jsf-2. Look for example at lazy-loading functionality of
p:dataTable
As with any framework, as long as your application can be adapted to the functionality/components provided, you will gain speed in the development.
The drawbacks is of course you have to learn the framework and if the components available doesn't fit your use case, you have to fallback to "raw"-jsf or perhaps even servlets.
JSF is a framework on top of Servlets technology.


text:
Q: Function in bash not working My bash: "testing" with a function "query"
#!/bin/bash
MY_USER="root"
MY_PASSWORD="my_password"
MY_BD="my_db"
MY_HOME="/home/express"

function query {
    mysql -e $1 -u $MY_USER --password=$MY_PASSWORD $MY_BD
}

case $1 in
"period")
    mysql -e "SELECT cron_period()" -u $MY_USER --password=$MY_PASSWORD $MY_BD;;
"hold")
    query "SELECT cron_hold()";;
*)
    echo "Others";;
esac

Test:
testing period // Working with complete command
testing hold   // Not working with function query, show commands info of MySQL

The problem is when using the function query, but do not know how to correct it.
Any suggestions please?

A: Try putting double quotes around the $1 in your function.

A: Try like this ie, put $1 in double qoutes:
function query {
    mysql -e "$1" -u $MY_USER --password=$MY_PASSWORD $MY_BD
}

A: Try that:
function query {
    mysql -e ${1} -u $MY_USER --password=$MY_PASSWORD $MY_BD
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upload files via Ajax and api key? I have below code for post request but 422 error is shown:
$.ajax({
    url: 'https://napi.arvancloud.com/vod/2.0/channels/166c3942-4e8d-4ab7-a543-c46e4528bf08/videos',
    headers: {
        'Authorization': authorization,
        'Accept-Language': "en"
    },
    data: new FormData(document.forms[0]),
    contentType: false,
    processData: false,
    type: 'post',
    success: function() {
        alert('Uploaded by jQuery');
    }
})

A:         $.ajax({
                    url: 'https://napi.arvancloud.com/vod/2.0/channels/166c3942-4e8d-4ab7-a543-c46e4528bf08/videos',
                    headers: {
                        'Authorization': authorization,
                        'Accept-Language': "en"
                    },
                    data: new FormData(document.forms[0]),
                    contentType: false,
                    processData: false,
                    type: 'post',
                    success: function () {
                        alert('Uploaded by jQuery');
                    }
                    })

            });
        })


text:
Q: Linux bash command incorrectly handles zeros in output. I'm using Debian 6-64.
When i'm running a command
echo -n `cat /proc/$(ps -o pid --no-header -C x-session-manager | tr -d ' ')/environ 2>/dev/null | tr '\0000' '\n'|grep XA|cut -d '=' -f 2`

to acquire XAUTHORITY for the current user logged in, I expect it to return at the moment my actual xauthority path, which is:
/var/run/gdm3/auth-for-alex-g5t0xM

but what it actually returns is
/var/run/gdm3/auth-for-alex-g5t

the part 0xM is missing.
Apparently it somehow takes 0 as '\0', truncating the output.
What can I do to receive the correct output?

A: tr manual:
\NNN   character with octal value NNN (1 to 3 octal digits)

You've given four digits. Fourth one handled as separate symbol ('0') and gets replaced too.

A: This should work as well and is a little more concise:
tr '\000' '\n' </proc/$(pgrep x-session-manager)/environ | awk -F= '/XAUTHORITY/{print $2}'


text:
Q: Groovy dynamic variables' value I have a groovy script as given below. I have defined a list which contains dynamic variables. The dynamic variables hold different values. how do i print the values of the variables - I don't want to hardcode this.var0. Please help.
someList = []

for (i in 0..2) {
    someList[i] = "var${i}"
}

var0 = "test1"

// print the values of the variables in the list
println this.someList[0]

A: The value from someList[0] has to be interpolated as well. Try:
println this."${someList[0]}"


text:
Q: Casting BSTR as char* in a dll; different results depnding on VBA/C# caller I have a dll function that takes BSTR parameters. These are cast as char* before being used for other things.
When the dll is called from VBA code this works. However, when it is called from C# code, only the first character is pointed to.
Both of these are Excel addIns for pre-2007 and 2007+ versions of Office, which call into a faster C++ AddIn. They call it directly, not through Excel.
The VBA function declaration:
Private Declare Function Test Lib "ExcelAddIn.xll" (ByVal param As String) As String

The C# function declaration:
[DllImport("ExcelAddIn.xll", CharSet=CharSet.Ansi)]
[return:MarshalAs(UnmanagedType.BStr)]
private static extern string Test([MarshalAs(UnmanagedType.BStr)] string param);

When debugging the dll and watching the input BSTR values, they appear to be correct from both; just the C# one only casts the first character.
Charset=CharSet.Unicode makes no difference.
C++ code.
BSTR __stdcall Test(BSTR param)
{
char* Param= "";

if(param!= NULL)
    Param= (char*)param;

    return OtherClass.DoOtherStuff(Param);
}

A: BSTRs are Unicode strings. As you're seeing, if you try and use a LE Unicode string as ANSI you'll only get the first letter (if it's ASCII, etc.)
ATL / MFC's CComBSTR class might help: you can attach the BSTR you receive and I think it'll handle single-byte conversion for you. It may also be safer to use this if you want Unicode strings internally - I don't think BSTRs are guaranteed to be zero-terminated (they have a length at index -1).[edit] corrected by dkackman below, thanks.
Your best solution really would be to convert OtherClass to use Unicode strings not MBCS, or if it's only used in a COM context you could convert it to use BSTRs even. Your program will then better support internationalisation expanding your markets, etc. However this isn't always a simple conversion.

A: The reason why has to do with the way you are marshalling the data.
The VB declaration contains no annotations on the string parameter and hence it will marshal as a normal char* parameter.  The CLR can do no type verification for pinvoke and essentially puts a char* in a slot which expects a BSTR.  Your code though immediately casts it to a char* and it fixes the marshalling problem.
In the C# example though you explicitly said to marshal the string as a BSTR.  A BSTR is actually a string which uses wchar under the hood.  By doing a simple cast to a char* you are essentially casting a wchar* to a char* which explains why you only see the first character.
The easiest solution is to just have the Test method take a char* parameter and remove the marshalling annotation on the C# version.


text:
Q: jQuery UI tooltips showing at the bottom of the page In my project I am using jQuery UI 1.10.2 to display tooltips for links on the page. However, when I hover over any links, the tooltip displays at the bottom of the page underneath the content area rather than right below the link.
Upon closer examination, I found that when hovering over a tooltip item, the "top" style is not set for the ui-tooltip div for some reason.
$(document).tooltip({
  content: function() {
    return $(this).attr('title');
  }
});

Does anyone have any ideas about why it would be doing this?

A: I have successfully solved this issue. As it turns out, I had been including the jquery.dimensions plugin in my sources, and somehow it was conflicting with my jquery-ui-1.10.2 include and causing the tooltips to display below all of my content. Removing the include for jquery.dimensions solved the problem.
Hopefully this can help someone else who may have the same issue in the future.


text:
Q: python: Getting error while accesing os.environ['HOME'] in Ubuntu at start up I have a script which downloads a file and saves to the Pictures directory.
all is working well and I set that script to run on start up. but Since then I am getting key-error i.e HOME key.
line where I getting error:
filepath=os.environ['HOME']+'//Pictures'

but it works fine when I run that script normally.
why is this happening?

A: It might be related to the fact of user startup, as the $HOME directory is related to a specific user.
You maybe want to add to bashrc some default $HOME, in case the user wasn't initialised yet.


text:
Q: how virtual generic method call is implemented? I'm interesting in how CLR implementes the calls like this:
abstract class A {
    public abstract void Foo<T, U, V>();
}

A a = ...
a.Foo<int, string, decimal>(); // <=== ?

Is this call cause an some kind of hash map lookup by type parameters tokens as the keys and compiled generic method specialization (one for all reference types and the different code for all the value types) as the values?

A: Yes. The code for specific type is generated at the runtime by CLR and keeps a hashtable (or similar) of implementations.
Page 372 of CLR via C#:

When a method that uses generic type
  parameters is JIT-compiled, the CLR
  takes the method's IL, substitutes the
  specified type arguments, and then
  creates native code that is specific
  to that method operating on the
  specified data types. This is exactly
  what you want and is one of the main
  features of generics. However, there
  is a downside to this: the CLR keeps
  generating native code for every
  method/type combination. This is
  referred to as code explosion. This
  can end up increasing the
  application's working set
  substantially, thereby hurting
  performance.
  Fortunately, the CLR has some
  optimizations built into it to reduce
  code explosion. First, if a method is
  called for a particular type argument,
  and later, the method is called again
  using the same type argument, the CLR
  will compile the code for this
  method/type combination just once. So
  if one assembly uses List,
  and a completely different assembly
  (loaded in the same AppDomain) also
  uses List, the CLR will
  compile the methods for List
  just once. This reduces code explosion
  substantially.

A: I didn't find much exact information about this, so much of this answer is based on the excellent paper on .Net generics from 2001 (even before .Net 1.0 came out!), one short note in a follow-up paper and what I gathered from SSCLI v. 2.0 source code (even though I wasn't able to find the exact code for calling virtual generic methods).
Let's start simple: how is a non-generic non-virtual method called? By directly calling the method code, so the compiled code contains direct address. The compiler gets the method address from the method table (see next paragraph). Can it be that simple? Well, almost. The fact that methods are JITed makes it a little more complicated: what is actually called is either code that compiles the method and only then executes it, if it wasn't compiled yet; or it's one instruction that directly calls the compiled code, if it already exists. I'm going to ignore this detail further on.
Now, how is a non-generic virtual method called? Similar to polymorphism in languages like C++, there is a method table accessible from the this pointer (reference). Each derived class has its own method table and its methods there. So, to call a virtual method, get the reference to this (passed in as a parameter), from there, get the reference to the method table, look at the correct entry in it (the entry number is constant for specific function) and call the code the entry points to. Calling methods through interfaces is slightly more complicated, but not interesting for us now.
Now we need to know about code sharing. Code can be shared between two "instances" of the same method, if reference types in type parameters correspond to any other reference types, and value types are exactly the same. So, for example C<string>.M<int>() shares code with C<object>.M<int>(), but not with C<string>.M<byte>(). There is no difference between type type parameters and method type parameters. (The original paper from 2001 mentions that code can be shared also when both parameters are structs with the same layout, but I'm not sure this is true in the actual implementation.)
Let's make an intermediate step on our way to generic methods: non-generic methods in generic types. Because of code sharing, we need to get the type parameters from somewhere (e.g. for calling code like new T[]). For this reason, each instantiation of generic type (e.g. C<string> and C<object>) has its own type handle, which contains the type parameters and also method table. Ordinary methods can access this type handle (technically a structure confusingly called MethodTable, even though it contains more than just the method table) from the this reference. There are two types of methods that can't do that: static methods and methods on value types. For those, the type handle is passed in as a hidden argument.
For non-virtual generic methods, the type handle is not enough and so they get different hidden argument, MethodDesc, that contains the type parameters. Also, the compiler can't store the instantiations in the ordinary method table, because that's static. So it creates a second, different method table for generic methods, which is indexed by type parameters, and gets the method address from there, if it already exists with compatible type parameters, or creates a new entry.
Virtual generic methods are now simple: the compiler doesn't know the concrete type, so it has to use the method table at runtime. And the normal method table can't be used, so it has to look in the special method table for generic methods. Of course, the hidden parameter containing type parameters is still present.
One interesting tidbit learned while researching this: because the JITer is very lazy, the following (completely useless) code works:
object Lift<T>(int count) where T : new()
{
    if (count == 0)
        return new T();

    return Lift<List<T>>(count - 1);
}

The equivalent C++ code causes the compiler to give up with a stack overflow.

A: EDIT
I now came across I now came across https://msdn.microsoft.com/en-us/library/sbh15dya.aspx which clearly states that generics when using reference types are reusing the same code, thus I would accept that as the definitive authority.
ORIGINAL ANSWER
I am seeing here two disagreeing answers, and both have references to their side, so I will try to add my two cents.
First, Clr via C# by Jeffrey Richter published by Microsoft Press is as valid as an msdn blog, especially as the blog is already outdated, (for more books from him take a look at http://www.amazon.com/Jeffrey-Richter/e/B000APH134 one must agree that he is an expert on windows and .net).
Now let me do my own analysis.
Clearly two generic types that contain different reference type arguments cannot share the same code
For example, List<TypeA> and List<TypeB>> cannot share the same code, as this would cause the ability to add an object of TypeA to List<TypeB> via reflection, and the clr is strongly typed on genetics as well, (unlike Java in which only the compiler validates generic, but the underlying JVM has no clue about them).
And this does not apply only to types, but to methods as well, since for example a generic method of type T can create an object of type T (for example nothing prevents it from creating a new List<T>), in which case reusing the same code would cause havoc.
Furthermore the GetType method is not overridable, and it in fact always return the correct generic type, prooving that each type argument has indeed its own code.
(This point is even more important than it looks, as the clr and jit work based on the type object created for that object, by using GetType () which simply means that for each type argument there must be a separate object even for reference types)
Another issue that would result from code reuse, as the is and as operators will no longer work correctly,  and in general all types of casting will have serious problems.
NOW TO ACTUAL TESTING:
I have tested it by having a generic type that contaied a static member, and than created two object with different type parameters, and the static fields were clrearly not shared, clearly prooving that code is not shared even for reference types.
EDIT:
See http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/how-do-c-generics-compare-to-c-templates.aspx on how it is implemented:

Space Use
The use of space is different between C++ and C#.  Because C++
  templates are done at compile time, each use of a different type in a
  template results in a separate chunk of code being created by the
  compiler.
In the C# world, it's somewhat different. The actual implementations
  using a specific type are created at runtime. When the runtime creates
  a type like List, the JIT will see if that has already been
  created. If it has, it merely users that code. If not, it will take
  the IL that the compiler generated and do appropriate replacements
  with the actual type.
That's not quite correct. There is a separate native code path for
  every value type, but since reference types are all reference-sized,
  they can share their implementation.
This means that the C# approach should have a smaller footprint on
  disk, and in memory, so that's an advantage for generics over C++
  templates.
In fact, the C++ linker implements a feature known as "template
  folding", where the linker looks for native code sections that are
  identical, and if it finds them, folds them together. So it's not a
  clear-cut as it would seem to be.

As one can see the CLR "can" reuse the implementation for reference types, as do current c++ compilers, however there is no guarantee on that, and for unsafe code using stackalloc and pointers it is probably not the case, and there might be other situations as well.
However what we do have to know that in CLR type system, they are treated as different types, such as different calls to static constructors, separate static fields, separate type objects, and a object of a type argument T1 should not be able to access a private field of another object with type argument T2 (although for an object of the same type it is indeed possible to access private fields from another object of the same type).


text:
Q: Disable button on a condition from function In my React Native application I have a TouchableOpacity which I would like to be disabled on condition returned from a function:
<TouchableOpacity onPress={() => this.someMethod()} disabled={this.checkIfDisabled}><Text>Click</Text></TouchableOpacity>

and my function which returns a boolean:
checkIfDisabled = () => {
   // ... really long logic
   return true/false;
}

However, when I try to implement this, I get the following error:

How can I disable my button depending on the boolean value returned from my function?

A: React Native expects that you will supply a boolean value for the "disabled" prop. You are currently supplying a function, not a function's boolean return value, for the "disabled" prop. You could use setState within TouchableOpacity's parent component to change a boolean value that you can supply for the TouchableOpacity's "disabled" prop. The change in the parent component's state will cause a re-render of the parent and thus TouchableOpacity.
Think about what kind of behavior/event/state change you would want to dictate a disabling of TouchableOpacity.

A: You can do that:
<Button disabled={checkIsDisabled() ? true : false} />
checkIsDisabled = () => {
isTrue ?
return true
: return false
}

A: Very late to the party but I just found this solution that works perfect:
<Button disabled={!!checkIfDisabled()} />


text:
Q: React render one element per second from array On reactjs how does one print one element per second from an array?
I have tried to replicate and simplify my work. The array comes from redux.
But the final situation doesn't change.
Thanks.

const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"];
class Message extends React.Component {
 renderWord(word,index) {
      return  {word} ;
    }
 renderWords() {
      const words =  arrWords.map((word, index) => {
       return this.renderWord(word, index);
      });
      return words;
    }
    render(){
      return (

{this.renderWords()}

      );
    }
};

ReactDOM.render(<Message  />, document.getElementById('app'));

A: One possible solution is to keep an index that keeps incrementing every second and render that many words

const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"];
class Message extends React.Component {
  state = {
     count: 0
  };
  componentDidMount() {
    this.timerID = setInterval(()=> {
      console.log(this.state);
      this.setState(prevState => ({
         count: (prevState.count + 1)%arrWords.length
      }))
    }, 1000);
  }
  componentWillUnmount() {
     clearInterval(this.timerID);
  }
 renderWord(word,index) {
      return  {word} ;
    }
 renderWords() {
      const words =  arrWords.map((word, index) => {
        if(index <= this.state.count)
         return this.renderWord(word, index);
      });
      return words;
    }
    render(){
      return (

{this.renderWords()}

      );
    }
};

ReactDOM.render(<Message  />, document.getElementById('app'));

A: I think this should work for you. Use the React lifecycle methods to start and end an interval before the component mounts and unmount. Simply increment the index and let React handle the rest.
const arrWords = ["I", "would", "like", "to", "print", "one", "word", "per", "second"];

class Message extends React.Component {
    constructor() {
        super();

        this.state = {
            arr: arrWords,
            index: 0
        }
    }

    componentDidMount() {
        this.timer = setInterval(() => {
            const { index, arr } = this.state;

            // increment index if appropriate or reset to 0
            this.setState({ index: index + 1 >= arr.length ? 0 : index + 1});
        }, 1000);
    }

    // Clean up before unmounting
    componentWillUnmount() {
        clearInterval(this.timer);
    }

    render() {
        const { arr, index} = this.state;
        return
{arr[index]}
;
    }
}

ReactDOM.render(<Message />, document.getElementById("app"));

A: The answers above aren't incorrect but they aren't very fun either.
Use Promise.resolve() to solve this.
not too sure if you mean render one word per second by replacing the previous each time, or one word per second by appending to the end
Replacing previous word

const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"];
class Message extends React.Component {
    state = { word: '', index: 0 };

    renderWord(word,index) {
      return new Promise(( resolve, reject ) => {
        if ( this.wordTimeout ) clearTimeout(this.wordTimeout);
        this.wordTimeout = setTimeout(() =>
          this.setState({ word, index }, resolve),
          1000
        )
      });
    }

    componentDidMount () {
      arrWords.reduce(( promise, word, index ) =>
        promise.then(() => this.renderWord(word, index)),
         Promise.resolve()
      );
    }

    render(){
      return (

           {this.state.word}

      );
    }
};

ReactDOM.render(<Message  />, document.getElementById('app'));

Appending to create sentence

const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"];
class Message extends React.Component {
    state = { index: 0 };

    renderSentence (index) {
      return new Promise(( resolve, reject ) => {
        if ( this.wordTimeout ) clearTimeout(this.wordTimeout);
        this.wordTimeout = setTimeout(() =>
          this.setState({ index }, resolve),
          1000
        )
      });
    }

    componentDidMount () {
      arrWords.reduce(( promise, word, index ) =>
        promise.then(() => this.renderSentence(index)),
         Promise.resolve()
      );
    }

    render(){
      // Plenty of better ways to do this but this will do what you need
      const words = arrWords.slice(0, this.state.index + 1);
      const renderedWords = words.map(word =>
        <span key={`${this.state.index}-${word}`}> {word}
      );
      return (

          {renderedWords}

      );
    }
};

ReactDOM.render(<Message  />, document.getElementById('app'));


text:
Q: Does Google Drive no longer allow JavaScript file referencing from other website? I just noticed that all my javascript files hosted on Google Drive no longer work, which previously officially allowed by Google. All variables and function calls become undefined (as indicated in Chrome console), but all the while, they were working fine. Below is my link reference:
<script charset='utf-8' src='https://googledrive.com/host/0B_kAR1YCVojTQnlmMXA0cWhfNGM' type='text/javascript'/>

The access permission had been set to public all the time and it is still remain as public. In my HTML file, I call the function as shown below:
<script type="text/javascript">setDefaultShow(13, 13);</script>

This had been working fine until recently. May I know what else could it be wrong? Could it be due to that, Google Drive no longer allows javascript file referencing from other website? If the answer is 'Yes', any other alternative to host my javascript files?
Thanks in advance!

A: Try using the direct link generator here https://sites.google.com/site/gdocs2direct/
Step 1: Go to Google Drive and right click the file that you want to share.
Now click on "Share...".
Step 2: On the window that comes up, click "Get shareable link".
Step 3: Make sure the dropdown is set to one of the "Anyone with the link..."
or "Anyone on the internet..." options, then click "Copy link".
Step 4: Now just paste that link into the text box above and create your direct link. Enjoy!

A: I just got off the phone with Google and they're aware of the problem.  They still allow the hosting of javascript files on GoogleDrive, it's just not working for some people and hasn't been for last day and a half.  In the meantime (or probably from now on) I'm using Amazon's Simple Storage Service: http://aws.amazon.com/s3/

A: we managed to work around this issue
it seems related with the MIME type, the loading is failing for JS file with application/x-javascript as mime type (they were fine before)
JS file with mime type text/plain are loading fine.
you can try this code to identify the files with mime problem withing an specific folder
var fid = "your-folder-id-here";
function myFunction() {
  var folder = DriveApp.getFolderById(fid);
  var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName() + " - " + file.getMimeType());
  }
}

A: EDIT:
Google has fixed this issue as of 2/9/2015.  The steps below are no longer required and if used will result in an unexpected MIME type console warning.  However, I'm leaving my original response in case the issue resurfaces.

ORIGINAL ANSWER:
I was able to fix the issue with this method:

*

*gDrive:  download all *.js files to your local drive

*gDrive:  delete all *.js files

*local drive: batch rename all the *.js files to *.txt

*local drive:  upload all *.txt files to gDrive

*local drive:  batch rename all the *.txt files to *.js (i.e. revert step 3)

*gDrive:  individually rename all *.txt files to *.js (major pain)

This method ensures that the MIME type of the file on gDrive is text/plain because you're uploading files with the .txt extension.  When you rename the files to .js on gDrive, the MIME type is preserved.


text:
Q: Show that $MC$ is the bisector of the angle $\widehat{AMN}$ . Let $\alpha $ be a semicircle by diameter $AB $ and $\beta $ a circle tangent to $AB $ in $C$ and tangent to $\alpha $ in $T $.
Let $M\in\alpha $ and $N\in CB $ such that $MN\perp AB $ and $MN$ is tangent to $\beta $.

Show that $MC$ is the bisector of the angle $\widehat{AMN}$ .
I tried to apply the reciprocal bisector theorem and the power of a point.

A: Assuming that the semicircle $\alpha$ is the graph of $f(x)=\sqrt{1-x^2}$ over $[-1,1]$, the center of $\beta$ has to lie on the graph of the parabola $g(x)=\frac{1-x^2}{2}$. Assuming $C=(x,0)$ we have $N=\left(x+\frac{1-x^2}{2},0\right)$. Now you may easily compute the $y$-coordinate of $M$ and check that
$$\frac{AM}{MN}=\frac{AC}{CN}=\frac{2x+2}{1-x^2}=\frac{2}{1-x} $$
holds, proving that $MC$ bisects $\widehat{AMN}$. Analytic geometry is not always the wrong tool.

A: Let $Q$ be a touching point of $MN$ and $\beta$. First show that $Q$, $B$ and $T$ are colinear (observe a homothety at $T$ which takes $\alpha$ to $\beta$ and thus it must take tangent at $B$ to a tangent on $\beta$ so they are parallel and thus $B$ goes to $Q$) and that $A,N,Q,T$ are concyclic. Then by the power of the point of $B$ we have:
$$BC^2 = BQ\cdot BT = BN\cdot BA = BM^2$$
The last equation is POP of $B$ with respect to the circle with diameter $AM$. So $BC =BM$ and should be an easy angle calculation....


text:
Q: How to filter by distinct AND Max in Excel hmmm. Thought this was like a normal forum.   Ok it's not copying my highlight.    I have complex and changing data sets  this is a simple version.  I want to some how filter the following:
state   number  seq OP
KY  831222  1   Apple
KY  831222  2   Apple
KY  831222  3   Apple
KY  845678  2   orange
KY  845678  3   orange
KY  845678  4   orange
KY  845678  2   Banana
KY  845678  3   Banana
KY  845678  4   Banana
PA  4567890 4   Apple
PA  4567890 5   Apple

So that I only see the following:
KY  831222  3   Apple
KY  845678  4   orange
KY  845678  4   Banana
PA  4567890 5   Apple

That is I want to filter/group by the MAX seq for EACH set.   I THiNK if this was seq I'd do it something like this:
Select Distinct State,number,max(seq), OP  From (table created from range)   group by KY,number,OP
BUT how do I do it in EXCEL?  I know there is a seq wizard thing but I can never get it to work right.  Inbedding a sql query in a macro may be doable.
I am a little past beginner with macros. I generally record then figure stuff out later.  So I may not understand terms.
OK This looks fine up here in the copy/paste write area but the "draft area" at the bottom looks like it's squishing things together.  I don't have time to figure out how to format this so it looks like the table I'm seeing.  I just hope this displays correctly.
Thanks for any help
- Sharon
Tried various types of filtering.  Tried a pivot table - it just makes a mess - doesn't even display the data neatly.  Tried the sql wizard but it's clunky.

A: Few steps:

*

*Select your range > Data Tab > Sort

*Add 4 levels of sorting: State - Number - OP - Seq

*Only edit to make: Sort Seq from Large to Small

*Apply

*Keep range selected > Data Tab > Remove Duplicates

*All boxes need to be checked but Seq

*Apply

We need to first sort the range on Seq column largest to smallest since remove duplicates will work bottum-top.


text:
Q: Call same function in jquery after modal shows up I'm using bootstrap modals to show the contents in my divs when a text is clicked (surrounded by <span>).
I call it by $(#div_to_show").modal() whenever you click the text inside a span tag. modal() is part of the bootstrap modal javascript.
My span uses the class someClass. I use
function update()
{
    ('.someClass').click(function() {
        var atr = $(this).attr("atr");

        $.get("../Folder/getFile?atr="atr, function(data) {
            json=JSON.parse(data);

            if(typeof(json.error) == "undefined") {
                var foobar = json.foo.replace(/_/g, '"');
                bar("#div_to_show", foobar);
                $("#div_to_show").modal();
            }
        });

        return false;
    });
}

I could add update(); after $(#div_to_show").modal(); but that causes it to go in an infinite loop even though the modal showed up and the span is not being clicked.
My question is how can I call the function update() whenever you click the text which is wrapped around span?

A: Try this:
$('.someClass').on('click', function() {
    update();
});

function update()
{
    $("#div_to_show").modal();
}


text:
Q: Perl ole selection property iterating I searched answer but did not find answer, so it brings me to register at stackowerflow. I am trying to write simple perl script using win32 ole which will iterate over all M$ word paragraphs (any text that ends with a hard return) and print only those paragraphs that matches the specified condition. The problem is that I need to access font size property. It seems to me that this property is set only once in first paragraph and later is not updated. Please see following code:
#!/usr/bin/perl
use strict;
use warnings;
use Win32::OLE::Const 'Microsoft Word';
#$Win32::OLE::CP = CP_UTF8;
binmode STDOUT, 'encoding(utf8)';

# OPEN FILE SPECIFIED AS FIRST ARGUMENT
my $fname=$ARGV[0];
my $fnameFullPath = `cygpath.exe -wa $fname`;
$fnameFullPath =~ s/\\/\\\\/g;
$fnameFullPath =~ s/\s*$//;
unless (-e $fnameFullPath) { print "Error: File did not exists\n"; exit 1;}

# STARTING OLE
my $Word = Win32::OLE->GetActiveObject('Word.Application')
    || Win32::OLE->new('Word.Application','Quit')
    or die Win32::OLE->LastError();

$Word->{'Visible'} = 0;
my $doc = $Word->Documents->Open($fnameFullPath);
my $paragraphs = $doc->Paragraphs() ;
my $enumerate = new Win32::OLE::Enum($paragraphs);

# PROCESSING PARAGRAPHS
while(defined(my $paragraph = $enumerate->Next())) {

    my $text = $paragraph->{Range}->{Text};
    my $sel = $Word->Selection;
    my $font = $sel->Font;

    if ($font->{Size} == 18){
        print "Text: ", $text, "\n";
        print "Font Bold: ", $font->{Bold}, "\n";
        print "Font Italic: ", $font->{Italic}, "\n";
        print "Font Name: ", $font->{Name}, "\n";
        print "Font Size: ", $font->{Size}, "\n";
        print "=========\n";
    }
}

# CLOSING OLE
$Word->ActiveDocument->Close ;
$Word->Quit;

Here is output what I obtained:
Text: This is a doc file containing different fonts and size, document also contain header and footer (Font: TNR, Size: 18)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========
Text: This is a Perl example (Font TNR, Size: 12)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========
Text: This is a Python example(Font: Courier New, Size: 10)
Font Bold: 0
Font Italic: 0
Font Name: Times New Roman
Font Size: 18
=========

As you can see in output everywhere is Font Size 18 even if in original document are different sizes (Also font name is not updated). This brings me to assumption that $font is set only once in 1st paragraph which is processed. Thus the following condition
if ($font->{Size} == 18)

is only evaluated in 1st processed paragraph. This also supports fact that if I change condition to following (Match 2nd paragraph):
if ($font->{Size} == 12)

the output is nothing. Because first paragraph is 18 not 12 and thus the condition is false, $font is not updated any more so it wont never be true. What I am doing wrong ?
Many thanks

A: Check out the #Insert this code in the snippet it will work fine now.
# PROCESSING PARAGRAPHS

while(defined(my $paragraph = $enumerate->Next())) {

    #Insert this code
    $paragraph->{Range}->Select();
    sleep(1);
    #-------------

    my $text = $paragraph->{Range}->{Text};
    my $sel = $Word->Selection;
    my $font = $sel->Font;

    if ($font->{Size} == 18){
        print "Text: ", $text, "\n";
        print "Font Bold: ", $font->{Bold}, "\n";
        print "Font Italic: ", $font->{Italic}, "\n";
        print "Font Name: ", $font->{Name}, "\n";
        print "Font Size: ", $font->{Size}, "\n";
        print "=========\n";
    }
}


text:
Q: InvalidArgumentError: input_1_1:0 is both fed and fetched I am using the visualize_activation function in keras-vis:
from vis.visualization import visualize_activation, visualize_cam
from vis.utils import utils
from keras import activations

from matplotlib import pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (18, 6)

# Utility to search for layer index by name.
# Alternatively we can specify this as -1 since it corresponds to the last
# layer.
layer_idx = utils.find_layer_idx(my_model, 're_lu_3')

patches = np.expand_dims(patches,axis=3)

# This is the output node we want to maximize.
filter_idx = None
img = visualize_activation(my_model, layer_idx, filter_indices=filter_idx,
seed_input=patches[0])
plt.imshow(img[..., 0])

However, this throws the error: InvalidArgumentError: input_1_1:0 is both fed and fetched.
How to resolve this? I tried creating a copy of my_model using tf.identity, but that didn't work.

A: keras-vis on pip seems broken, try installing directly on the GitHub master branch:
pip uninstall vis
pip install git+https://github.com/raghakot/keras-vis.git -U

Using the version on pip, both the MNIST and ResNet example outputs the error: InvalidArgumentError: input_1_1:0 is both fed and fetched.. After updating, they both works well.


text:
Q: What status can a record of bolt cms have? When setting a record in the bolt-cms, there are multiple options for the status. What are they all, and what do they do? The documentation is not very clear what they are and what they are used for.

A: The current status of this record can be either: published, depublished, held, draft or timed.

*

*published: a record has been published.

*depublished: this content should not be accessible, but still not deleted. Available since Bolt 4.

*held: this content should not be accessible, but still not deleted.

*draft: when a record is not ready to be published yet because it is unfinished. This is the default status for any contenttype that does not have a default_status setting.

*timed: used in combination with the Publication date field to publish a record in the future, or to have a record be published for a certain duration.

See also: https://docs.bolt.cm/4.0/contenttypes/intro#the-structure-of-a-record and https://docs.bolt.cm/4.0/howto/resource-contenttype#default-publishing-status


text:
Q: What caused my servo to burn out? I'm working on a servo project. I connected 12 servos to a single Adafruit servo shield and plugged in a 5V 10 amp (http://www.adafruit.com/product/658) switching power supply to the shield. Instantly, the motors became very hot and one of the motor became unresponsive.
What could be the reason for this? The only rational reason would be that a large amount of current went through the motors but physically how could this happen? I thought V = IR, since voltage at 5 V, then current should have been divided evenly across the motors so it would have been very small?

A: (EDIT: This answered OP's original title question, which was "What happens if you use a load that exceeds the maximum regulated current output from your power supply?")
As for the power supply overload question, it depends on the power supply. Some behaviours include:

*

*latching the output off

*reducing the output voltage while keeping the output current constant

*hiccupping (switching the output off and on)

*going into thermal shutdown with autorecovery

*blowing a fuse

*blowing up

It will all depend on the power supply itself and the nature of the overload.


text:
Q: Moving object a given distance to the direction its facing c# If I have an object and I know its (x, y, z, yaw, pitch, roll). How can I move it distance D in the same direction its facing? (it has to move the same direction it is facing) then get the new point.
Any help will be appreciated


text:
Q: Endpoints datastore - query with and without ancestors Similar to the keys_with_ancestors.html example I need to query a model by it's parent.
But in addition on a different API request I need to query the same model without the parent restriction.
The use case is that I have Tasks associated with Users, I need one API call listing the tasks of a given user and one listing all tasks.
User need to be parent of Task to allow transactions.
If I follow the keys_with_ancestors example I can't manage to to create the 'list all tasks' api - since the query building is done on the Task object and looks for the parent from the request.
I can give up the parent and have a user_email property in the task and just have it as an optional query parameter - but this seems a bad solution.
Any better idea?


text:
Q: Asp.net core - Two-factor authentication login process I could apply two-factor authentication for user in my asp.net core app, but in the login phase, I have a problem with this logic:

*

*if a user disables 2FA feature -> Directly login.

*if a user enables 2FA feature -> Show 2FA input field.

I know that it's impossible to check whether users disable or enable 2FA before logging in. Then how to check this after a user enters correct username and password but still unauthorized if user enables 2FA?


text:
Q: How to reposition UITextField up without a Scroll View I have the following issue:
I have a parent view. Inside this is a scroll view with different text fields and labels. When a text field is being edited, I reposition the text field to the top of the screen so that the keyboard does not hide the textfields.
One of the text fields has a table view below it which is used a dropdown. when text is entered, it shows various results dynamically. This table view is also added to the scrollview. This is not a recommended and also does not work. So how can I achieve this whitout using scrollview?

A: As @hackerinheels has mentioned above, use this method to reposition elements, so that the keyboard does not obstruct your text fields.
Avoid using scrollview for repositioning, as adding tableview inside scrollview is problematic.
Xcode/iOS5: Move UIView up, when keyboard appears


text:
Q: How to generate downloading link using custom option ID for various products that are available on website for Magento? I want to fetch the custom option ID for the Magento Product to generate the different downloadable link in Magento.
I have three custom options in the One product.
option 1: free
option 2: paid
option 3: both
If I select option 1 then it will allow me to download free version of the module.
If I select option 2 then it will allow me to download paid version of the module.
so on..
Thus,  I want to add different download link for different options, which on click will proceed for the checkout according to the specific custom option selected.

A: I've implemented something similar to this (see here)

<select name="options[22]">
    <option value="57">SA Postal (Free)</option>
    <option value="56">Registered Mail (+ R22 pm)</option>
    <option value="53">Door to Door (+ R30 pm)</option>
</select>

Now go to the admin panel (back end) and select catalog -> Manage product. Select the product you are making the custom links for. Go to Custom Options. You will find that if you 'inspect element' or view the page's source code:

<input type="hidden" name="product[options][22][values][53][option_type_id]" value="53">

You will see that you just have to match these values. options[22] is which option and 53 is the value for 'Delivery Type' and 'Door to Door' in this case.
Just look at a product page to see how the form on a product page looks (catalog/product/view) and take a look at the product options while you're at it.


text:
Q: why my application android crash when I add GDPR EU consent? I added the GDPR code to my app , but that crash it .
this is my the function :
private void loadGPDR() {

        ConsentInformation consentInformation = ConsentInformation.getInstance(this);
        String[] publisherIds = {"yyyyyyyyyyyyyy"};
        consentInformation.requestConsentInfoUpdate(publisherIds, new ConsentInfoUpdateListener() {
            @Override
            public void onConsentInfoUpdated(ConsentStatus consentStatus) {
                // User's consent status successfully updated.
            }

            @Override
            public void onFailedToUpdateConsentInfo(String errorDescription) {
                // User's consent status failed to update.
            }
        });
        URL privacyUrl = null;
        try {
            // TODO: Replace with your app's privacy policy URL.
            privacyUrl = new URL("https://sites.google.com/view/yyyyyyyyyy");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            // Handle error.
        }
        form = new ConsentForm.Builder(this, privacyUrl)
                .withListener(new ConsentFormListener() {
                    @Override
                    public void onConsentFormLoaded() {
                        // Consent form loaded successfully.
                        form.show();
                    }

                    @Override
                    public void onConsentFormOpened() {
                        // Consent form was displayed.
                    }

                    @Override
                    public void onConsentFormClosed(
                            ConsentStatus consentStatus, Boolean userPrefersAdFree) {
                        // Consent form was closed.
                    }

                    @Override
                    public void onConsentFormError(String errorDescription) {
                        // Consent form error.
                    }
                })
                .withPersonalizedAdsOption()
                .withNonPersonalizedAdsOption()
                .withAdFreeOption()
                .build();
        form.load();
    }

Error:
Process: com.code.myapplication, PID: 28444
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.code.myapplication/com.code.myapplication.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x2040003
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
        at android.app.ActivityThread.access$900(ActivityThread.java:154)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5294)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:114)
     Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2040003
        at android.content.res.Resources.getText(Resources.java:321)
        at android.content.res.XResources.getText(XResources.java:837)
        at android.content.res.Resources.getString(Resources.java:407)
        at com.android.org.chromium.content.browser.ContentViewCore.setContainerView(ContentViewCore.java:684)
        at com.android.org.chromium.content.browser.ContentViewCore.initialize(ContentViewCore.java:608)
        at com.android.org.chromium.android_webview.AwContents.createAndInitializeContentViewCore(AwContents.java:631)
        at com.android.org.chromium.android_webview.AwContents.setNewAwContents(AwContents.java:780)
        at com.android.org.chromium.android_webview.AwContents.<init>(AwContents.java:619)
        at com.android.org.chromium.android_webview.AwContents.<init>(AwContents.java:556)
        at com.android.webview.chromium.WebViewChromium.initForReal(WebViewChromium.java:311)
        at com.android.webview.chromium.WebViewChromium.access$100(WebViewChromium.java:96)
        at com.android.webview.chromium.WebViewChromium$1.run(WebViewChromium.java:263)
        at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue.drainQueue(WebViewChromium.java:123)
        at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue$1.run(WebViewChromium.java:110)
        at com.android.org.chromium.base.ThreadUtils.runOnUiThread(ThreadUtils.java:144)
        at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue.addTask(WebViewChromium.java:107)
        at com.android.webview.chromium.WebViewChromium.init(WebViewChromium.java:260)
        at android.webkit.WebView.<init>(WebView.java:554)
        at android.webkit.WebView.<init>(WebView.java:489)
        at android.webkit.WebView.<init>(WebView.java:472)
        at android.webkit.WebView.<init>(WebView.java:459)
        at android.webkit.WebView.<init>(WebView.java:449)
        at com.google.ads.consent.ConsentForm.<init>(ConsentForm.java:80)
        at com.google.ads.consent.ConsentForm.<init>(ConsentForm.java:46)
        at com.google.ads.consent.ConsentForm$Builder.build(ConsentForm.java:210)
        at com.code.myapplication.MainActivity.loadGPDR(MainActivity.java:70)
        at com.code.myapplication.MainActivity.onCreate(MainActivity.java:18)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)

A: The comment of Belyamani Said works for me.
Just update the appcompat library:
from:
implementation 'androidx.appcompat:appcompat:1.1.0'

to:
implementation 'androidx.appcompat:appcompat:1.2.0-alpha03'


text:
Q: Mirror programming for uicontrols in xcode I am new to multi-language app.
What I am doing is,
an app with two languages.
English & Arabic
The language of the app depends upon the device language.
(I want to change this too, that app language should be controlled from inside the app. not device dependant but thats next question)
I am having some controls like UIButton,UITextField,UILabel, etc....
When my app is in English I gave these controls frame starting from left corner of device, and when my app is in Arabic I gave them frames starting from Right corner of device. (As arabic is written from Right - to - left)
My Question is,
For this purpose I need to do extra work,
i.e. check device language and then set the frames of control.
on each view I may have "n" number of controls, and giving the frame sizes to all controls for both language doesn't seems good from my view.
Is there anything available in Xcode itself by using which I can do this.
means I need to give frames for default language (i.e. English) and if my device language is change to Arabic then frames of Controls will be automatically Mirrored from Right to left.
Following screens may give some idea.
(I used different frames for all those controls checking device language)
Any help is accepted.
Thanks in advance.
sorry If question is asked already. But I didn't find anything.
If anyone found then link to that is Welcome :)

A: From Supporting Right-to-Left Languages:

Your user interface should be mirrored when displaying right-to-left languages. If you use base internationalization and Auto Layout, most of the user interface will appear mirrored automatically for you. The text direction changes to right-to-left with the exception of phone numbers and country codes which are always left-to-right. Some views and controls in your user interface may not change direction automatically which you can fix programmatically.

They functionality you're looking for is called Auto Layout which was introduced a few years ago by Apple. It will handle lots of things you need, but there's also a lot to do for you. The guide above will guide you through the necessary steps.

Update from iOS 9.0:

iOS 9 brings comprehensive support for right-to-left languages, which makes it easier for you to provide a flipped user interface. For example:

*

*Standard UIKit controls automatically flip in a right-to-left context.

*UIView defines semantic content attributes that let you specify how particular views should appear in a right-to-left context.

*UIImage adds the imageFlippedForRightToLeftLayoutDirection method, which makes it easy to flip an image programmatically when appropriate.
To learn more about providing a flipped user interface, see Supporting Right-to-Left Languages.


text:
Q: Don't allow direct access to files in a certain subdirectory I've tried so many different things in my .htaccess folder and I'm at wits and trying to get this to work.
I have a subdirectory in which contains an .htaccess file. I'd like the files (images, css, js, and the like) in this folder not to be accessed directly. However they need to be accessed/linked to only on the site at www.domain.com/foo/page-name
I've tried the following (not all at once, but separately):
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1 localhost

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/foo/.*$ [NC]
RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|mp4|mov|js)$ http://domain.com/ [NC]

Redirect 301 /topsecret http://www.domain.com/

Does my issue have to do with the .htaccess file being in a subdirectory? This is the only directory I need to limit access to, so I don't see a reason to put it in the root. My knowledge of .htaccess is pretty limited.
I know HTTP REFERER is unsecure but it seems like the best option if I can get it to work.


text:
Q: Replacing multiple parts of a string with params passed into method I have a function called translate that looks something like this:
export const translate = (sentence: string, ...words) => { ... }

It looks into the settings to see what language is selected and then looks up the translated sentences dictionary.
Here is an example sentence: "Each __ provides __ money".
After translating the sentence into the correct language, I want to check to see if there are any __ in the string. That is what the param ...words is for. We would then replace the __ using the param words
Example of me using the function: translate('Each __ provides __ money', 'Person', 'Fifty') would return: Each Person provides Fifty moneybut translated.
Im currently having a problem with how to go about replacing the __.
I was thinking about doing something with .split:
if (sentence.includes('__')) {
  let rebuiltSentence = ''
  const splitSentence = sentence.split('__')

  for (let i = 0; i < splitSentence.length; i++) {
    const part = splitSentence[i]
    rebuiltSentence += part
    rebuiltSentence += words[i]
  }

  return rebuiltSentence
}

But this seems a bit hacky to me. Is there any way I can maybe get the index of each __ then replace it with the correct word index in the words param?

A: You could use String#replace with a regex pattern and a callback that iterates the words array:

const translate = (sentence, ...words) => {
  let i = 0;
  return sentence.replace(/\b__\b/g, () => words[i++]);
};

console.log(translate("Each __ provides __ money", "Person", "Fifty"));

If it should handle the situation when there aren't enough words to fit the blanks:

const translate = (sentence, ...words) => {
  let i = 0;
  return sentence.replace(/\b__\b/g, m =>
    i < words.length ? words[i++] : m
  );
};

console.log(translate("Each __ provides __ money", "Person"));

Or using split, a bit closer to the spirit of your original approach:

const translate = (sentence, ...words) =>
  sentence
    .split(/\b__\b/g)
    .map((e, i) => i === 0 ? e : (words[i-1] || "__") + e)
    .join("")
;

console.log(translate("Each __ provides __ money", "Person", "Fifty"));

A: Take a look at some i18n js libraries. For example, i18next (I chose only this one because I had a chance to work with it, you can also try other libraries). With i18next you can define translations in which selected fragments can be dynamically set, also with the results of other translations. Below is a simple example:

void async function main() {
    await i18next.init({
        lng: 'en',
        resources: {
            en: {
                translation: {
                    'someKey': 'Each {{name}} provides {{number}} money',
                    'fifty': 'Fifty',
                },
            },
            pl: {
                translation: {
                    'someKey': 'Każdy {{name}} zapewnia {{number}} pieniędzy',
                    'fifty': 'pięćdziesiąt',
                },
            },
        },
    });

    console.log(i18next.t('someKey', { name: 'Person', number: i18next.t('fifty') }));

    await i18next.changeLanguage('pl');

    console.log(i18next.t('someKey', { name: 'Person', number: i18next.t('fifty') }));
}();
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>

Of course, you are not forced to define your translations in one place, you can break them into separate files that are then pulled from the server in case of a language change. See the documentation for more information, if you are interested :)


text:
Q: Libgdx: Is there an easy way to center text on each axis on a button? I have been trying to figure out a way to center text on a button, but can't find an easy, multi-purpose way to. I can do it, but it will only work for a certain string, not for any string. i would like to know if there is a way to center any string on a button. My button in this case is 185x50.
I have been able to center this button on the screen, like so:
buttonX = WIDTH / 2 - (screen.getRegionWidth() / 2);
buttonY = HEIGHT / 2 - (screen.getRegionHeight() / 2);

Any help would be much appreciated. :)

A: Updated the answer to libgdx version 1.7.1-SNAPSHOT:
The easiest way to do this, is to use the TextButton class from libgdx. The text from a TextButton is centered by default. This still works!
Updated example:
final BitmapFont font = new BitmapFont();

final String text = "Test";

final GlyphLayout layout = new GlyphLayout(font, text);
// or for non final texts: layout.setText(font, text);

final float fontX = objectX + (objectWidth - layout.width) / 2;
final float fontY = objectY + (objectHeight + layout.height) / 2;

font.draw(batch, layout, fontX, fontY);

Outdated example:
This no longer works!
If you do not want to use it, you can get the font width and height with:
    font.getBounds("Test text");

So you can do something like this:
    String fontText = "";
    fontX = buttonX + buttonWidth/2 - font.getBounds(fontText).width/2;
    fontY = buttonY + buttonHeight/2 + font.getBounds(fontText).height/2;

A: For the newer version of libgdx the function BitMapFont.getBounds() isn't there in api anymore. You can use GlyphLayout to get bounds.For example,
BitmapFont font;
SpriteBatch spriteBatch;
//... Load any font of your choice first
FreeTypeFontGenerator fontGenerator = new FreeTypeFontGenerator(
   Gdx.files.internal("myFont.ttf")
);
FreeTypeFontGenerator.FreeTypeFontParameter freeTypeFontParameter =
      new FreeTypeFontGenerator.FreeTypeFontParameter();
freeTypeFontParameter.size = size;
fontGenerator.generateData(freeTypeFontParameter);
font = fontGenerator.generateFont(freeTypeFontParameter);

//Initialize the spriteBatch as requirement

GlyphLayout glyphLayout = new GlyphLayout();
String item = "Example";
glyphLayout.setText(font,item);
float w = glyphLayout.width;
font.draw(spriteBatch, glyphLayout, (Game.SCREEN_WIDTH - w)/2, y);

A: Try the following:
label.setPosition(Gdx.graphics.getWidth()/2-(label.getPrefWidth()/2),Gdx.graphics.getHeight()-(label.getPrefHeight()/2));


text:
Q: Error with async code design. UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT], I am facing an error with node/express. I am assuming the issue is with my asynchronous code design.
Output:
Success in container
Expected Output:
Success in container..
Success in Uploading...
Error: (node:18364) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Code:
const express = require("express");
const multer = require("multer");
const AuthReq = require("../middleWare/AuthReq");
require("dotenv").config();
const Azure_Storage_Connection_String = process.env.Azure_Connection_String;
const { BlobServiceClient } = require("@azure/storage-blob");

const Router = express.Router();

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

Router.post("/profile", AuthReq, upload.single("profile"), async (req, res) => {
  const file = req.file;

  const blobServiceClient = BlobServiceClient.fromConnectionString(
    Azure_Storage_Connection_String
  );

  const containerName = req.user._id;

  const ContainerClient = blobServiceClient.getContainerClient(containerName);

  try {
    const containerResponse = await ContainerClient.create();
  } catch (err) {
    return res.status(400).send("Error while sending image");
  }

  res.send("Success in container");

  const contentType = file.mimetype;

  const filePath = file.path;

  const blobName = file.filename + contentType;

  const blockBlobClient = ContainerClient.getBlockBlobClient(blobName);

  try {
    const uploadBlobResponse = await blockBlobClient.uploadFile(filePath);
  } catch (err) {
    return res.status(400).send("Error while sending image");
  }

  res.send("Success in Uploading...");
});

module.exports = Router;

A: You cannot use res.send more than once per request, because one request has only one response. I assume that you want to send a "two-part" response, so that the user first sees "Success in container" and then (a few seconds later) "Success in Uploading ...".
Node.js will send the response in two "chunks" if you use
res.write("Success in container");
...
res.end("Success in Uploading...");

(See also the explanation in this answer.)


text:
Q: How do I get WYSIWYG design in Blend/VS without merged ResourceDictionary in every XAML file? I've just removed a big memory issue for me, I used to merge our "Themes" resource dictionary in every xaml file instead of just in the app.cs.xaml.
However, after removing the merging in every file except the App.cs.xaml I've lost the design time styles/templates.
Please note: This only applies to the styles merged into our Themes.xaml (e.g. Color.xaml, Brushes.xaml - we have one for each type of style). Stuff defined directly in Themes.xaml (which we have none of..) works.
I see two solutions,
1) Have the merging commented out in XAML and just un-comment it when I want to work with the designs.
2) Have this in the default ctor of every control: (perhaps only works in Blend)
#if DEBUG
Resources.MergedDictionaries.Add(
                new ResourceDictionary()
                {
                    Source = new System.Uri(@"RD.xml")
                }
                );
#endif

There has to be a better way to get design time editing of pages and controls, anyone know?
Thank you!

A: What I do is add a class that inherits from ResourceDictionary and override the source property to check if IsInDesignMode is true.
If it is I set the source otherwise I leave the source blank (which effectivley prevents the dictionary from being merged at runtime)
public class BlendMergedDictionary : ResourceDictionary
{
    public bool IsInDesignMode
    {
        get
        {
            return (bool)DependencyPropertyDescriptor.FromProperty(
                            DesignerProperties.IsInDesignModeProperty,
                            typeof(DependencyObject)
                            ).Metadata.DefaultValue;
        }
    }

    public new Uri Source
    {
        get { return base.Source; }
        set
        {
            if (!IsInDesignMode)
                return;

            Debug.WriteLine("Setting Source = " + value);
            base.Source = value;
        }
    }
}

Now when I need to reference the dictionary in Blend I merge in the dictionary like this
<ResourceDictionary.MergedDictionaries>
            <BlendHelpers:BlendMergedDictionary Source="Foo.xaml" />
</ResourceDictionary.MergedDictionaries>

You still have to "merge" in the dictionary in every file, but you don't pay the penalty of actually loading the dictionary at runtime. The merge is only there to support design time behavior.

A: Blend 4 supports "design time resources", which Visual Studio 2010 also supports. See http://adamkinney.wordpress.com/2010/05/04/design-time-resources-in-expression-blend-4-rc/.
It's pretty much just a ResourceDictionary that contains whatever MergedDictionaries you like, and shows up in the project file like this (automatically added by Blend):
<Page Include="Properties\DesignTimeResources.xaml" Condition="'$(DesignTime)'=='true' OR ('$(SolutionPath)'!='' AND Exists('$(SolutionPath)') AND '$(BuildingInsideVisualStudio)'!='true' AND '$(BuildingInsideExpressionBlend)'!='true')">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
  <ContainsDesignTimeResources>true</ContainsDesignTimeResources>
</Page>

Works great.

A: Janes question is actually related to this one, i have the same problem. i've created a subclass of ResourceDictionary like Foovanadil suggested, however at design time this throws a "Uri prefix not recodnized" exception
I get this error even if all the sub class does is assign the base.Source property of ResourceDictionary. If i replace my custom ResourceDictionary with the regular one, it works just fine, so im guessing the cider designer does someting special, perhaps replacing ResourceDictionary with something else
I havent tried this in blend but i do get it in VS2010 (sp1 beta)
Can someone confirm that the posted awnser works in vs2010?
-edit-
Its possible that the wpf based designer is tripping up the resource locating logic. I've read elsewhere that pack uris are based on the -executing- assembly, not neccecarily the -local- assembly. i'll report whats i finds
-edit2/solution-
Alright so i managed to get Foovanadil solution to work in VS2010, here is the deal. Turns out i was half right, presumably because the wpf designer in VS2010 is itself written in wpf or to provide a better design experience, ResourceDictionary (or some other class that VS2010 uses instead) behaves diffrently at design time.
It turns out that VS replaces the URI that is entered in the xaml. Attatcing to the VS instance and setting a breakpoint in the setter for Source reveals that the actual value that is getting passed is diffrent from what we expect.
Given the xaml:
<Window.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <local:DesignTimeResourceDictionary Source="myxamlfile.xaml"  />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Window.Resources>

Source is set to
markup://1/file:///c:/PathtoMyapp/MainWindow.xaml#0/myxamlfile.xaml
instead of
/myxamlfile.xaml
This is why we get the exception for invalid uris.
Exactly when and where VS2010 edits URIs this way at design time is not known to me, but it renaming the Source property in DesignTimeResourceDictionary to something else does not solve the problem.
Luckliy there is a workaround. If we change the type of Source from Uri to String, the VS designer does not modify the value. In the setter we then create a Uri and pass it to the base property:
public new String Source {
  get {
    return base.Source.ToString();
  }
  set {
    if( !IsInDesignMode )
      return;
    base.Source = new Uri( value, UriKind.RelativeOrAbsolute );
  }
}

Note also that if you use this approach (or any other that ive found such as using x:class in the resource file and instancing it directly from xaml) will cause styles not to get updated until you build. Using the standard ResourceDictionary will cause the designer to update as soon as you edit the imported resource files (even before you save). This is also an indication that the designer treats ResrouceDictionary diffrently at design time.
Hope someone finds this useful :)

A: Another way of doing it (the way we're going for now): Have a pre-build script comment out the merging in all XAML files.
Makes it harder to debug memory issues etc in DEBUG mode, but can be fully automated and fixes the issues for the final release.

A: The script idea doesn't seem like a good idea to me. You'd have so many "fake" revisions in your source control and my guess is that you'd have to spend a lot of time tweaking it.
I've been hoping that VS2010 and Expression Blend 3 will make big improvements in this area. Anyone try out the betas and know?

A: You can add resource distionary in Resources of App.xaml, that works perfectly for me.
Or may be i m not getting u.


text:
Q: How do you select extreme details for all units and buildings in Rise of Nations? You can usually select an option that will allow you to see special info about buildings and units such as health and what is attacking it. How do I toggle that on and off?

A: After much searching I finally found it. Go under Options/Tools in the main menu. From there under game, click on show advanced details button.


text:
Q: PHP/MYSQL Query if not in second table I have two tables.  I want to draw a sample of the first table except where the person in the first table is also in a second table.  Am having trouble doing this seemingly simple query.
table users
id|name

table catuser
id|userid|catid

I have tried
SELECT u.*,c.userid FROM `users` u
LEFT JOIN `catuser` c
ON (u.id = c.userid AND c.userid <> '197')
WHERE u.id = '1'

and variations to no avail.  Would appreciate any suggestions.

A: How abt. this:
SELECT u.*,c.userid
FROM `users` u
LEFT JOIN `catuser` c
ON u.id = c.userid
WHERE u.id = '1'
AND c.userid <> '197'
AND c.userid is null

A: SELECT * FROM users WHERE id NOT IN (SELECT DISTINCT userid FROM catuser)

A: If you want to query only users that have one or more categories, you can use a WHERE EXISTS query:
SELECT u.* FROM `users` u
WHERE EXISTS (SELECT * FROM catuser WHERE catuser.userid = u.id)

Another possibility is to do a left join, and check whether the join succeeded on checking on null:
SELECT u.*, c.* FROM `users` u
LEFT JOIN catuser c ON u.id = c.userid
WHERE c.id IS NOT NULL

If there is no corresponding row in catuser, all catuser fields will be null. By checking whether c.id is not null, you only include the rows with a category.
Note that the join may return a user multiple time, if he is in multiple categories.


text:
Q: Mongoose save parent model with child model

How to save une ligne de stations? I have 2 shemas models station et. The method that I make doesn't work for me. see the pictures.

A: var LigneSchema = mongoose.Schema({
titre: String,
stations: [{ type: Schema.Types.ObjectId, ref: 'Station' }],

});
var StationSchema = mongoose.Schema({
titre: String,
lieu: String,
depart : boolean ,
arrive : boolean,
lignes: [{ type: Schema.Types.ObjectId, ref: 'Ligne' }]

});
var ligne = new Ligne({titre : req.body.titre, stations: []}) ;
ligne.save(function(err, data) {
    console.log(data);

    if(err) {
        console.log(err);
        res.status(500).send({message: "Une erreur s'est produite lors de la création du bus."});
    } else {

        res.send(data);
    }
});

};


text:
Q: How to get order id of woocommerce in the URL with slash Example url:
https://example.com/checkout/order-pay/24463/?pay_for_order=true&key=wc_order_60e277a2e517f
I want to get to order id 24463

A: Well a regex should do the job, but as you are in a woocommerce environment (tag) and want to get this in php (tag) when you are on this page then there is a much more simpler way to get it.
if(is_wc_endpoint_url( 'order-pay' )) {
   $order_id = get_query_var('order-pay');
}

You should have the id in $order_id.


text:
Q: How to get all unique email recipients python gmail api I want to do a search for all unique email recipients from gmail. But I'm really struggling with API. If I was interacting with a SQL database I would want something like:
SELECT DISTINCT EmailRecipient FROM MyHypotheticalGmailTable;

But I'm not sure how to translate this into a gmail API call.

A: I suggest you start by taking a look at the Gmail API Quickstart with Python here.
Afterwards you may want to take a look at threads.list in order to list all the threads available and then for each one use threads.get. Since there is no direct method of retrieving the unique email recipients, you will have to handle this separately from the API calls and filter the results programmatically.
Reference

*

*Gmail API Python Quickstart;

*Gmail API messages.list;

*Gmail API messages.get.


text:
Q: iCarousel (Coverflow) with table view I got an app with one table. First cell is the coverflow from iCarousel.
When i rotate coverflow and items changed i reload table view:
-(void)carouselDidScroll:(iCarousel *)_carousel{
    if (curCategory != _carousel.currentItemIndex)
    {
        curCategory=(int)_carousel.currentItemIndex;
        NSLog(@"%i",curCategory);
        [table reloadData];
    }
}

But this code drop finger action of rotating. Because first cell with coverflow reload too.
Can i reload table, but dont touch first cell?

A: You can reload just a range of cells using reloadRowsAtIndexPaths:
It might make more sense to make the carousel be the table header view instead of the first cell though.


text:
Q: Problem with Angular dependencies: @types/node: '{' or ';' expected I'm getting an error while executing "ng serve" in my application, it was an Angular 5 application (Angular 2 at the first stage), now I've upgraded it to Angular 8 (Also tried Angular 6 and 7 before).
But after upgrading from Angular 5, I started getting errors while executing "ng serve", the errors usually points to the @types/node, like:

ERROR in ../node_modules/@types/node/assert.d.ts:8:68 - error TS1144: '{' or ';' expected.

or:

node_modules/@types/node/assert.d.ts:56:14 - error TS2300: Duplicate identifier 'assert'.

I've tried upgrading different packages (Found some suggestions about upgrading some of the @types or Typescript versions in a couple of Github posts), using different versions of Angular/Typescript, updating node (Now version 14.16.1), even removing the @types from the DevDependencies, nothing worked so far.
Maybe I have some deprecated packages/functionallities or even code which is affecting the whole application while using Angular versions >5.
 This is my package.json (Without the @types):
"dependencies": {
  "@angular/animations": "8.2.14",
  "@angular/common": "8.2.14",
  "@angular/compiler": "8.2.14",
  "@angular/compiler-cli": "8.2.14",
  "@angular/core": "8.2.14",
  "@angular/forms": "8.2.14",
  "@angular/platform-browser": "8.2.14",
  "@angular/platform-browser-dynamic": "8.2.14",
  "@angular/platform-server": "8.2.14",
  "@angular/router": "8.2.14",
  "@angular/upgrade": "8.2.14",
  "angular2-notifications": "2.0.0",
  "bootstrap": "3.3.7",
  "bootstrap-datepicker": "1.6.4",
  "bootstrap-select": "1.13.18",
  "brace": "0.11.1",
  "core-js": "3.0.1",
  "font-awesome": "4.7.0",
  "jquery": "3.4.1",
  "lodash": "4.17.21",
  "ng2-file-upload": "1.4.0",
  "ng2-table": "1.3.2",
  "reflect-metadata": "0.1.8",
  "rxjs": "6.6.7",
  "rxjs-compat": "6.0.0-rc.0",
  "zone.js": "~0.9.1"

},
"devDependencies": {
  "@angular-devkit/build-angular": "0.803.29",
  "@angular/cli": "8.3.29",
  "@angular/language-service": "8.2.14",
  "angular2-template-loader": "0.6.2",
  "bestzip": "1.1.4",
  "codelyzer": "5.0.1",
  "copy-webpack-plugin": "3.0.1",
  "css-loader": "0.28.0",
  "extract-text-webpack-plugin": "1.0.1",
  "file-loader": "0.11.1",
  "html-loader": "0.4.5",
  "html-webpack-plugin": "2.28.0",
  "jasmine-core": "3.4.0",
  "jasmine-spec-reporter": "4.2.1",
  "karma": "4.1.0",
  "karma-chrome-launcher": "2.2.0",
  "karma-coverage-istanbul-reporter": "1.2.1",
  "karma-jasmine": "1.1.0",
  "karma-jasmine-html-reporter": "0.2.2",
  "null-loader": "0.1.1",
  "protractor": "5.4.2",
  "raw-loader": "3.1.0",
  "rimraf": "2.7.1",
  "style-loader": "0.23.1",
  "to-string-loader": "1.1.6",
  "ts-loader": "5.4.5",
  "ts-node": "8.3.0",
  "tslint": "5.20.0",
  "tslint-loader": "3.5.4",
  "typescript": "3.4.5",
  "url": "0.11.0",
  "url-loader": "1.1.2"
}

Hopefully, someone could have faced a similar situation before and would be able to help me sorting this out, I've seen several posts with issues like this without a clear solution, so this may be helpful for more people,
Thanks!

A: Finally I got the fix, I was just messing with the package.json and testing some new dependencies, and now it works, the @types error is gone (I tried also different versions for all the @types, and these ones are the good ones for my case), this is the final package.json:
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "angular2-notifications": "^9.0.0",
    "bootstrap": "3.3.7",
    "bootstrap-datepicker": "1.6.4",
    "bootstrap-select": "1.11.2",
    "core-js": "^2.5.4",
    "jquery": "^3.6.0",
    "ng2-file-upload": "1.1.4-2",
    "ng2-table": "^1.3.2",
    "popper.js": "^1.16.1",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.10",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/ace": "0.0.35",
    "@types/bootstrap": "3.3.33",
    "@types/bootstrap-datepicker": "0.0.6",
    "@types/bootstrap-select": "1.11.0",
    "@types/core-js": "^2.5.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.5.5",
    "@types/lodash": "^4.14.168",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"


text:
Q: RenderAction ViewBag Empty on the View I am invoking a RenderAction from a View as shown below:
@{ Html.RenderAction("GetOptions", "Product", new {ProductId = Model.ProductId});

   var options = ViewBag.Options;

}

Inside the GetOptions I populate the ViewBag as shown below:
public ActionResult GetOptions(..) {

     // do some other stuff
     ViewBag.Options = new JavaScriptSerializer().Serializer(options);

     return Content(somelongstring);
}

But when I debug inside the var options is always null. What am I doing wrong?


text:
Q: android studio how to set a fragment from navigation activity as startup page Currently im using fragment_empty as startup.
fragment_empty
I want fragment_home as startup-page(when you start up the app), but i don't want fragment_home to be seen on every page.
The fragment_home page :
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welkom op home!"
    android:padding="10dp"
    />

<ImageView
    android:layout_width="236dp"
    android:layout_height="218dp"
    android:src="@mipmap/ic_launcher"
    android:id="@+id/imageView2" />

The fragment_empty page:
<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

My MainActivity (the navigation drawer):
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
        if (id == R.id.nav_home) {
            fragment = new HomeFragment();
        } else if (id == R.id.nav_evenementen) {
            fragment = new EvenementenFragment();
        } else if (id == R.id.nav_contact) {
            fragment = new ContactFragment();
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

App_bar_main page :
<include layout="@layout/fragment_empty" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

A: Use add instead of replace
In your MainActivity onCreate() method add:
HomeFragment fragment = new HomeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.frame_container, fragment).commit();

This will add your fragment's xml to your frame_container. To change Fragments, just use the same method as you already have defined in your code.

A: You can add the above code like this
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

    //Here the Code

HomeFragment fragment = new HomeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.frame_container, fragment).commit();
    }

A: On your MainActivity onCreate() method you can directly call first time HomeFragment like
HomeFragment mHomeFragment = new HomeFragment();

FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, mHomeFragment).commit();


text:
Q: .emacs file evaluation in a new frame When I open a new frame in emacs, none of the settings in my .emacs file are evaluated unless I open the file and evaluate the buffer manually.  Is there a secret that I am missing?  Some bit of magic in my .emacs file that should handle this?

A: To define colors in all emacs frame, one can change the default face:
(set-face-attribute 'default nil :background "black")
(set-face-attribute 'default nil :foreground "gray90")

Or use default-frame-alist:
(setq default-frame-alist
  '((foreground-color . "gray90")
    (background-color . "black")))

I've both in my .emacs, and there could be a reason...


text:
Q: How to read from JSON in protractor test? I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
 "responseHeader":{
      "status":0,
      "QTime":0,
      "params":{
         "q":"object_type_s:USER",
         "indent":"true",
         "wt":"json"
      }
   },
   "response":{
      "numFound":13,
      "start":0,
      "docs":[
         {
            "id":"sanja",
            "groups_id_ss":[
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         },
         {
            "id":"sanjaseconduser",
            "groups_id_ss":[
               "ACM_SUPERVISOR_DEV",
               "CHAIRMAN",
               "ACM_ADMINISTRATOR_DEV",
               "CPC INITIATOR",
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         }
      ]
   }
}

A: As stated you could read response.docs from json. Let's say
var docs = response.docs;

As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
    var groupIdSS = doc.groups_id_ss;
}
});

This way you can read groups_id_ss for desired id.
Hope it helps.

A: Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData =  require('../../response.json');

describe('some function description', function(){
   var groupID = responseData.response.docs[0].groupid_ss[0];
   var groupID = responseData.response.docs[0].groupid_ss[0]

});

Since that is json array, we have to give the index of the array in that.
Hope this would work for you.


text:
Q: zRSSFeed - Selecting RSS feeds from a menu with ticker animation + jQuery Mobile (PhoneGap)? Problem: after selecting a feed from the list and pressing a button to return to the home div jQuery reloads the whole page and only the title (without any feeds) of the new selected webpage is shown.
By default, before choosing this specific option (selecting a feed) on another div page, the title ("Reuters Oddly Enough News") and the feeds are being shown without any problems.

code below

Select a feed from the list below

<select id="menu">
                <option value="http://feeds.reuters.com/reuters/oddlyEnoughNews">Reuters Oddly Enough News</option>
                <option value="http://feeds.bbc.co.uk/iplayer/highlights/tv/list">BBC iPlayer TV Listing</option>
                <option value="http://rss.cnn.com/rss/edition.rss">CNN News</option>
</select>

Selecting RSS feeds from a menu with ticker animation:

A: I have tested the, it works with no problem. Unless I didn't get what you really need.
zRSSFeed w/ Ticker Animation + Jquery Mobile
$('#menu').on('change', function () {
var selected = $(this).val();
  $('#test').rssfeed(selected,{}, function(e)  {
   $(e).find('div.rssBody').vTicker();
 });
});

HTML

Select a feed from the list below

    <select id="menu">
        <option value="#">Choose</option>
        <option value="http://feeds.reuters.com/reuters/oddlyEnoughNews">Reuters Oddly Enough News</option>
        <option value="http://feeds.bbc.co.uk/iplayer/highlights/tv/list">BBC iPlayer TV Listing</option>
        <option value="http://rss.cnn.com/rss/edition.rss">CNN News</option>
    </select>


text:
Q: How to force evaluation of value in Debug.log Using Elm 0.17, I'd sometimes like to see the steps taken during a computation, such as:
let
    names = Debug.log "accounts"
        List.map (\x -> x.name) accounts

    sortedNames = Debug.log "sorted accounts"
        List.sortBy String.toLower names

    options =
        List.map (viewAccountOption selectedName) sortedNames
in
    [ viewEmptyOption ] ++ options

This logs the following:
accounts: <function>
sorted accounts: <function:sortBy>

I understand Elm is lazy, and the thunks will be evaluated when the values are actually needed.
I couldn't find a force or strict function in elm-core Basics, or anywhere else in the package.
Is there a way to force evaluation of a value?

A: You can do that by either using parenthesis:
Debug.log "accounts"
    (List.map (\x -> x.name) accounts)

Or using the <| operator
Debug.log "accounts" <|
    List.map (\x -> x.name) accounts

EDIT:
The reason is that Debug.log was evaluated with List.map (a function) as the second argument and then returned that argument to be composed with the rest of the line. You just needed to hint elm a bit on what was your intended argument precedence


text:
Q: Google Play Service dependencies on android scala project Is there any way to specify dependency for Android Play services on Scala SBT-Android project?
I need to write app that receive Google Cloud Message.
I tried
  libraryDependencies ++= Seq(
    "com.actionbarsherlock" % "library" % "4.0.2" artifacts(Artifact("library", "apklib", "apklib")),
    "com.google.android.gms" % "play-services" % "3.2.65" artifacts(Artifact("play-services", "aar", "aar"))
  )

in Build.scala
But when I tried to build apk, SBT complains
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.google.android.gms#play-services;3.2.65: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency:     com.google.android.gms#play-    services;3.2.65: not found

Thanks in advance.

A: You have to install with the Android SDK tool, the "Google Repository" and maybe also the "Android Support Repository", in case, you use the appcompat library.
Hre is my setting in build.sbt:
libraryDependencies += aarlib("com.google.android.gms" % "play-services" % "4.+")

By the way, the android-sdk-plugin seems to be better maintained nowadays.


text:
Q: Convert folder backups to Git repo I have inherited a project that was not developed using any SCM whatsoever. Instead I have a series of folders that look like:
my-project.201109011234
my-project.201110010908
my-project.201202040454
my-project.201203011123
...and so on...

Each folder is a complete copy of the source code, and the folder is named after the timestamp of when the copy was made. Changes abound between each copy, i.e. files and folders added, removed, renamed and file contents changed.
Is there any sort of tool, where I can feed it a list of folders and it will basically Create a Git repo for me, where each folder becomes a commit? After which I would hope that Git knows exactly what changed between each commit?
Thanks Adam.

A: It sounds to me like a very particular problem to solve (i.e. there probably isn't a tried and tested method to integrate something like that into git).
That said, a solution could easily be devised with a bit of shell/python/xyz scripting. the steps would be these:

*

*make an empty git repo

*make a list of the archives, sorted chronologically

*for each archive:

*

*delete contents of project directory (everything except .git directory)

*unzip archive into project dir

*run "git add -u ." in the directory

*run "git add -f ." in the directory

*extract/generate commit message based on archive name

*commit current state of the project dir

This solution has many limitations (like not performing each commit on the archive date) but depending on what is important to you, you can adapt the script.

A: In addition to whatever utnapistim has replied, you can change the commit and the author date as per your archive dates.
There are two options:
 1. The following option will change the date for all the further commits
GIT_AUTHOR_DATE='[Date]' GIT_COMMITTER_DATE='[Date]' git commit -m "[Message]"

*For individual commits , you can do the following:
git commit --date "[Whatever date you want]"


text:
Q: I need help or an example to get relative error using intg on Scilab I'm doing Fourier analysis in a project on Scilab and using intg function to get definite integrals, but I need to also get the absolute error and most importantly the relative error for every time I use the function.
Now, according to the documentation for this function, there's a way to get the relative and absolute error. But I tried to do it and I couldn't.
I will show you what I did as an example, this is a definite integral from 0 to 1 for y = x^2:
function y=f(x),y=x^2,endfunction
inte = intg(0,1,f);

So the result will be:
inte  =

    0.3333333

But now if I want to get the error using the documentation, this is what happens:
[inte, err] = intg(0,2,f[,ea [,er])/2
                       !--error 3
Waiting for right parenthesis.

Any idea about how to apply the documentation? Or even an example would be useful.
Thanks in advance!

A: If you read documentation, ea and er are absolute error required on the result (having default value: 1.d-14) and relative error required on the result (having default value: 1.d-8) respectively. Now I am unsure whether you really want to override these values or not and in case you want to, kindly declare ea and er first. Thanks!


text:
Q: Angular ng-select value is not getting refreshed unless clicking the ng-select I am trying to set the value of ng-select based on the other field value using form valuechanges.
The value is set but not showing up until i click on the ng-select box. the bindLabel is not getting refreshed.
<ng-select [items]="routes$ | async" bindLabel="combinedRoute" formControlName="route">
    <ng-template ng-typetosearch-tmp>

           Type route...

    </ng-template>
    <ng-template ng-notfound-tmp let-searchTerm="searchTerm">

            No routes found for "{{searchTerm}}"

    </ng-template>
    </ng-select>

component:
deptCtrl.valueChanges.subscribe(data=> {
        let routeCtl = this.form.get('route');
        routeCtl .setValue(data);
  });

Can anyone help how to fix this?
Thanks

A: You can use updateValueAndValidity method, it was like it has the value but change detection is not detecting that.
deptCtrl.valueChanges.subscribe(data=> {
        let routeCtl = this.form.get('route');
        routeCtl .setValue(data);
        this.form.controls["route"].updateValueAndValidity(); // update value and validity.
  });

Another way to do it. Call changeDetection manually.
constructor(cd:ChangeDetectionRef){}

deptCtrl.valueChanges.subscribe(data=> {
        let routeCtl = this.form.get('route');
        routeCtl .setValue(data);
        this.cd.detectChanges(); //Detect changes
  });


text:
Q: Send a session variable from php to client side(HTML) I am completely new to PHP and HTML. I want to send a session variable from PHP to client-side i,e HTML so that I can show which user is currently present.
If I just pass the variable to another php file present at the same location it does happen but I want to exchange the variable from server residing at local host to client at some other location Can any one help me in this
Thanks

A: let suppose you have a form in html
<form method="post" action="any.php">
<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>

now in php you are getting input value
<?php
if isset($_POST["name"]){
$_SESSION["sessionname"] = $_POST["name"];
}
?>

so far you have taken input value from html and have stored in session with the name sessionname now you are going to show it in html again
<h1>welcome user : <?php echo $_SESSION["sessionname"]; ?> </h1>

you will need session_start(); on the very beginning of all php pages otherwise you will lose the scope of session variable.

for more information here is link wschools session


text:
Q: How this non-existing getter method becomes available I'm just getting my self familiarized with the code base of our application and I found this one Java class:
@Setter
@Getter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = SqlTables.PRODUCTS)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Schedule {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @NotBlank(message = "name should not be empty")
  private String name;

  private boolean recurring;

An instance of the above class can be passed as method parameter to other classes e.g.:
private void validateRecurringAttribute(Schedule schedule) {
    if (schedule.isRecurring()) {
      log.error("[ERROR] <validateRecurringAttribute()> Recurring schedule is not yet supported.");
      throw new UnsupportedException("Recurring schedule is not yet supported.");
    }
  }

What I'm wondering is this getter method - isRecurring(), it is not available in the Schedule class but somehow can be called in other classes. How is it done?

A: The getters and setters are generated at compile time by these 2 lombok annotations in the class -
@Setter
@Getter

To know more about Lombok and getter setter -
https://projectlombok.org/features/GetterSetter

A: These Getters and Setters of the class data members are generated by the @Setter and @Getter annotation of Lombok.
Further you can use @Data which implicitly calls
@Getter
@Setter
@RequiredArgsConstructor
@ToString

Basically we are using these annotation of lombok to remove boilerplate code.
Example:
@Data
Class tax{
 private int tax;
}

Now we don't need to explicitly define getter and setters for it like.
private int gettax(){
    return tax;
}
private void settax(int tax){
    this.tax = tax;
}

https://projectlombok.org/features/Data