text:
Q: Converting LPBYTE to char* After 2 hours of google on "Convert LPBYTE to char*" i only found result that relates with "RegQueryValueExW"
No one use "LPBYTE" other than "RegQueryValueExW" function.
My question arise with unicode and ASCII conversion if i use RegQueryValueEx that will give me all ASCII values correct but as multinational point view this will not helping me.
Now,
I have following code ,
char* GetStringRegKey(HKEY hKey, LPCWSTR strValueName, char* strValue, char* strDefaultValue)
{
    strValue = strDefaultValue;
    char szBuffer[512];
    DWORD dwBufferSize = sizeof(szBuffer);
    ULONG nError;
    LPCWSTR TempPassingString;
    char* hostName;
    nError = RegQueryValueExW(hKey, strValueName, 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        strValue = szBuffer;
    }
    USES_CONVERSION;
    return strValue;
}

This will show me szBuffer array like,

Which is correct value.( note "C" aftet pointer value).
But when i assign it to another character array strValue then only "C" is display as value of strValue;
As shown below.

This may be foolish question but i dont understand where i am going wrong.
Please suggest any help, block of code or hint that will convert my whole szBuffer to strValue.


text:
Q: Verify solution of system of first order ODE I am given a solution $v_1$(t)=$-e^{t/2}cost$ for a system of first order ODE and I am asked to verify this solution can solves the linear second order ODE in terms of $y_1$(t)
Here is the matrix ODE
[![enter image description]
After get $y_2$(t), I copy the output of y2[t] and use D to take its derivative`
D[(-2 y1[t] + y1[t] - 2 Derivative[1][y1][t])/(
 2 + 3 Cos[t] Sin[t]), t]

Next, I equate $y_2'$(t) to the second component of the coefficient matrix (second row of the matrix), and finally, i obtained second ODE in terms of $y_1$(t), $y_1'$(t) and $y_1''$(t) (*)
{-(((3 Cos[t]^2 - 3 Sin[t]^2) (-2 y1[t] + 3 Cos[t]^2 y1[t] -
    2 Derivative[1][y1][t]))/(2 + 3 Cos[t] Sin[t])^2) + (-6 Cos[
   t] Sin[t] y1[t] - 2 Derivative[1][y1][t] +
 3 Cos[t]^2 Derivative[1][y1][t] - 2 (Prime])[t]}]

Summary
Sorry if it is hard to follow, it is quite messy to right details but basically i have the matrix ode and i used mathematica to rearrange the equation and then substitution so that finally i get a single second ODE with only $y_1$(t) $y_1'$(t) and $y_1''$(t). Then i plug in the solution i have into this equation and verify that it is 0. But i can't get it and i am not sure if it is due to systax error or any possible mistakes i could get during computing with mathematica.
Is there any syntax errors or any mistakes I have made throughout the process?
Any help please :):). Thank you very much

A: The solution you gives does not satisfy the ODE?
\begin{align*}
\begin{pmatrix}
y_{1}^{\prime}\\
y_{2}^{\prime}
\end{pmatrix}
=
\begin{pmatrix}
a_{11} & a_{12}\\
a_{21} & a_{22}
\end{pmatrix}
\begin{pmatrix}
y_{1}\\
y_{2}
\end{pmatrix}
\end{align*}
Hence
\begin{align*}
y_{1}^{\prime}  & =a_{11}y_{1}+a_{12}y_{2}\\
y_{2}^{\prime}  & =a_{21}y_{1}+a_{22}y_{2}
\end{align*}
But $y_{1}=y$ and $y_{2}=y^{\prime}$, therefore the above becomes
\begin{align*}
y_{1}^{\prime}  & =a_{11}y+a_{12}y^{\prime}\\
y_{2}^{\prime}  & =a_{21}y+a_{22}y^{\prime}
\end{align*}
And also $y_{1}^{\prime}=y^{\prime},y_{2}^{\prime}=y^{\prime\prime}$,
therefore the above becomes
\begin{align*}
y^{\prime}  & =a_{11}y+a_{12}y^{\prime}\\
y^{\prime\prime}  & =a_{21}y+a_{22}y^{\prime}
\end{align*}
Solving for $y^{\prime}$ from first equation above gives $y^{\prime}
=\frac{a_{11}y}{1-a_{12}}$. Substituting this in the second equation gives
\begin{align*}
y^{\prime\prime}=a_{21}y+a_{22}\frac{a_{11}y}{\left(  1-a_{12}\right)  }
\end{align*}
Or
\begin{align*}
y^{\prime\prime}=\left(  a_{21}+a_{22}\frac{a_{11}}{1-a_{12}}\right)  y
\end{align*}
To verify that $v\left(  t\right)  =-e^{\frac{t}{2}}\cos\left(  t\right)  $ is
a solution, plugin into the above and see if it satisfies it.
ClearAll[y,t,v]
a={{-1+3/2Cos[t]^2,1-3/2 Sin[t]Cos[t]},
  {-1-3/2 Sin[t]Cos[t],-1+3/2 Sin[t]^2}};

ode=y''[t]==(a[[2,1]] +a[[2,2]] a[[1,1]] /(1-a[[1,2]]))y[t];
ode=Simplify[ode]

v[t_]:=-Exp[t/2] Cos[t];
ode/.{y[t]->v[t],y''[t]->v''[t]}//Simplify

It does not satisfy it. If it did, we'll get True at the end.
Are you sure -Exp[t/2] Cos[t] is supposed to be a solution?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript usage of delete increases RAM usage and execution time I implemented a benchmark using js-meter and compared the array methods map and forEach on parsing some data. See my script below.
Scenario:
E.g. if we get a huge array from an API and just want to instantiate a Date object based on a given timestamp for each item and want to get rid of some unnecessary properties.
Two things are very strange to me:

*

*Using map() as seen in the script should create a totally new array with new objects. So the memory usage should be the double, but isn't.

*Using delete inside the loop (map, forEach, for) is increasing the memory usage and time spent by ~3 times. Why is using delete so bad here?
Additional Info:
I ran the tests separately (just commented all out except one) on a MacBook Pro with macOS Catalina with Node version 10.15.3
const jm = require('js-meter');

const isPrint = true;
const isKb = true;       // or Mb
const m = new jm({isPrint, isKb});
const printItemIndex = 45;
const arr = [];
const now = Date.now();

//  Create an array with some fake example data.
for(let i = 0; i < 100000; i++) {
    const delay = Math.floor(Math.random() * 10000);
    arr.push({
        index: i,
        delay,
        timestamp: now
  });
}

//  Map the array and turn a timestamp to a Date
//  Result of Benchmark: 33 MB RAM, 58ms
console.log("\n\nTest 1 with .map()");
const result = arr.map(data => {
    return {
        delay: data.delay,
        date: new Date(data.timestamp + data.delay)
    };
});

//  Use forEach and save weak copy to result array
//  Result of Benchmark: 91 MB RAM, 127ms
console.log("\n\nTest 2 with .forEach()");
arr.forEach(data => {
  data.date = new Date(data.timestamp + data.delay)
  delete data.index;
  delete data.timestamp;
});
const result = arr;

//  Map the array and turn a timestamp to a Date
//  Result of Benchmark: 83 MB RAM, 140ms
console.log("\n\nTest 3 with .map() and a delete");
const result = arr.map(data => {
    delete data.index;
    return {
        delay: data.delay,
        date: new Date(data.timestamp + data.delay)
    };
});

//  Use forEach and save weak copy to result array
//  Result of Benchmark: 32 MB RAM, 45ms
console.log("\n\nTest 4 with .forEach() w/o delete");
arr.forEach(data => {
  data.date = new Date(data.timestamp + data.delay);
});
const result = arr;

//  Use forEach and save weak copy to result array
//  Result of Benchmark:  32 MB RAM, 46ms
console.log("\n\nTest 5 with for loop");
for(let i = 0; i < arr.length; i++) {
    arr[i].date = new Date(arr[i].timestamp + arr[i].delay);
}
const result = arr;

//  Use forEach and save weak copy to result array
//  Result of Benchmark: 92 MB RAM, 145ms
console.log("\n\nTest 6 with for loop");
for(let i = 0; i < arr.length; i++) {
    arr[i].date = new Date(arr[i].timestamp + arr[i].delay);
    delete arr[i].index;
    delete arr[i].timestamp;
}
const result = arr;

m.stop();


text:
Q: start pdb in post mortem mode. any trick to avoid typing "c" I'd like to create a small helper (e.g. a shell function), that allows me to call any python script in pdb post mortem mode.
withpdb() {
    cmd="$1" ; shift
    python -m pdb -- "$(which $cmd)" "$@"
}

So if I typed for example
mycmd.py param1 param2

and I encounter errors, that I want to analyze with pydb.
I just go up in my bash history and prefix with withpdb
withpbd mycmd.py param1 param2

Now pdb is started with my script and as soon as I press c and return the script starts.
My question is:
Is there any trick to avoid typing the initial "c" + enter?
If I have to write some wrapper code in python or another alngauge, that's also OK

A: Use the -c option to execute c upon startup. (And since you only have to write the function once, use continue instead of the abbreviation for clarity.)
withpdb() {
  cmd="$1" ; shift
  python -m pdb -c continue -- "$(which $cmd)" "$@"
}


text:
Q: Invalid predicate when filtering CKRecords by the same keys I have a CKRecord type "Follow" which stores the user's ID and the ID of a friend they follow. (Assume that a user can only follow 1 person and the logic around that is handled elsewhere). Screenshot of record definition in CloudKid: http://screencast.com/t/Tb83lyjLV7
I want to query the Follow records to confirm that two users follow each other and are in fact, friends.
These are the base queries. Each works fine on it's own
let followPredicate = NSPredicate(format: "userID == %@ AND followsID == %@", userId, followsID)
let followedPredicate = NSPredicate(format: "followsID == %@ AND userID == %@", userId, followsID)

I want to combine these two predicates and query once, so that if two records come back, it's assumed that the different users follow each other
I've tried to combine them both manually and by using a NSCompoundPredicate:
let friendPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [followPredicate, followedPredicate])
let friendPredicate = NSPredicate(format: "(followsID == %@ AND userID == %@) OR (userID == %@ AND followsID == %@)", userId, followsID, userId, followsID)

I then use the query here:
let friendQuery = CKQuery(recordType: "Follow", predicate: friendPredicate)

In both versions of friendPredicate above, I get an Invalid Predicate Exception.
*** Terminating app due to uncaught exception 'CKException', reason: 'Invalid predicate: (userID == "_1570bb2652d0658c12320bcd658e5898" AND followsID ==
"_fb7ebeb0841f6411099ad094424d66ac") OR (followsID ==
"_1570bb2652d0658c12320bcd658e5898" AND userID ==
"_fb7ebeb0841f6411099ad094424d66ac")
(Error Domain=CKErrorDomain Code=12 "Invalid predicate (userID ==
"_1570bb2652d0658c12320bcd658e5898" AND followsID ==
"_fb7ebeb0841f6411099ad094424d66ac") OR (followsID ==
"_1570bb2652d0658c12320bcd658e5898" AND userID ==
"_fb7ebeb0841f6411099ad094424d66ac")"
UserInfo=0x14e63010 {ck_isComparisonError=false,
NSLocalizedDescription=Invalid predicate (userID ==
"_1570bb2652d0658c12320bcd658e5898" AND followsID ==
"_fb7ebeb0841f6411099ad094424d66ac") OR (followsID ==
"_1570bb2652d0658c12320bcd658e5898" AND userID ==
"_fb7ebeb0841f6411099ad094424d66ac")})'

Am I approaching this wrong or making an invalid assumption?
Any help is much appreciated


text:
Q: I am making a function to print a dynamically allocated object array based on certain criteria in each element While working on an assignment, dealing with making classes, I have gotten a majority of the program written but I have to make two functions that print elements in an array based upon user input But I keep getting errors when trying to pass arguments to the function such as an eo167, I have tried looking but wasn't able to find anything on my problem. I tried just passing the dynamic array to the argument but it keeps saying "argument of type "Employee *" is incompatible with parameter of type "Employee **"
#include <fstream>
#include <iostream>
#include <string>

class Employee {
private:
    int ID;
    string name;
    string depName;
    int salary;

public:
    Employee();

    void setID(int newID) { ID = newID; }
    void setName(string newName) { name = newName; }
    void setDepName(string newDepName) { depName = newDepName; }
    void setSalary(int newSalary) { salary = newSalary; }
    int getID() { return ID; }
    string getName() { return name; }
    string getDepName() { return depName; }
    int getSalary() { return salary; }
    void print(Employee arr[], int n) {
        cout << "Employees" << endl;
        for(int i = 0; i < n; i++) {
            cout << ID << " " << name << " " << depName << " " << salary << endl;
        }
    }
};

using namespace std;

ifstream inFile;

int main() {
    int employees;
    int id;
    int salar;
    string names;
    string dep;

    // for menu choice later
    int num;

    inFile.open("employees.txt");

    inFile >> employees;
    Employee* eArr = new Employee[employees];

    for(int i = 0; i < employees; i++) {
        inFile >> id >> names >> dep >> salar;

        eArr[i].setID(id);
        eArr[i].setName(names);
        eArr[i].setDepName(dep);
        eArr[i].setSalary(salar);
    }

    inFile.close();

    cout << "1) Print Employees" << endl;
    cout << "2) Print by Department" << endl;
    cout << "3) Print by Salary" << endl;
    cout << "4) Exit" << endl;

    cout << "What would you like to do?";
    cin >> num;

    if(num == 1) {
        eArr->print(eArr, employees);
    }

    if(num == 2) {
        printSalary(eArr, employees);
    }

    if(num == 3) {
        printDepartment(eArr, employees);
    }

    return 0;
}

void printSalary(Employee* arr[], int m) {
    int salar2;
    cout << "Salary?";
    cin >> salar2;
    for(int i = 0; i < m; i++) {
        if(arr[i]->getSalary >= salar2) {
            cout << arr[i];
        }
    }
}

void printDepartment(Employee* arr[], int z) {
    string department;
    cout << "department?";
    cin >> department;
    for(int i = 0; i >= z; i++) {
        if(arr[i]->getDepName == department) {
            cout << arr[i];
        }
    }
}


text:
Q: Adding elements to List<> doesn't work I have a List<> declared, which is accessable in the whole class
List<article> data;

Now I'm using a method to fill the List<>:
StreamReader sr = new StreamReader(filePath);

while (!sr.EndOfStream)
{
    string[] Line = sr.ReadLine().Split(';');

    article newArticle = new article();
    newArticle.articleNumber = Line[0];
    newArticle.description = Line[1];
    newArticle.articleId = Line[2];
    try
    {
        data.Add(newArticle);
    }
    catch(NullReferenceException ex)
    {
        // Nothing to do here
    }
}

Each time, the loop repeats, the newArticle-Object contains all his elements, so it is definetely not null.
But it doesn't add to the data-List<>.
What am I missing?

A: In order to add items to the list, you must first initialise it.
Replace:
List<article> data;

with:
List<article> data = new List<article>();


text:
Q: How can I make my discord bot only react on a certain user id? This does not work it will start spamming the message whenever someone says something
bot.on('message', message => {
  if (message.author.id = '655876175616540700') {
    message.reply('test');
  }
});

A: message.author.id = '655876175616540700' does not do what you want. You should make a comparison with message.author.id === '655876175616540700'.
The triple equals operator (===) returns true if operands (both sides) are have the same type AND contain the same value.
The single equal operator (=) is an assignment operator, it will always return true in your if statement.


text:
Q: dynamic dropdown list in python GAE I am using GAE with Python for building an app. I have 2 dropdowns 'applications' and 'versions' in my firstpage( Index.html). I am able to populate the first dropdown dynamically from the database. Based on the selection of the first dropdown, I need to populate the second. I tried with an onchange event and a javascript to capture the selection id in the first dropdown list. but i am not sure how to pass the captured onchangeid to the backend. request.get doesn't seem to work. Appreciate any help.
my main.py looks like
class MainPage(webapp.RequestHandler):
  def get(self):
      proj = db.GqlQuery("SELECT DISTINCT Applicationname FROM Dashboard")

      Appname1 = self.request.get('selvalue.value')
      proj1 = Dashboard.all().filter('Applicationname =',Appname1)

      values = {'appnames' : proj, 'vernums' : proj1}
      self.response.out.write(template.render('index.html',values))

class Dashboard(db.Model):
   Applicationname = db.StringProperty(required=True)
   Version=db.StringProperty(required=True)
   Type=db.StringProperty()
   Pagename=db.StringProperty(required=True)
   Responsetime=db.StringProperty(required=True)

class DisplayHandler(webapp.RequestHandler):
  def post(self):
      Appname=self.request.get('Applicationname')
      Vernum=self.request.get('Version')
      query = Dashboard.all().filter('Applicationname =',Appname).filter('Version =',Vernum)
      values = {'query' : query}
      self.response.out.write(template.render('response.html',values))

def main():
    application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/Display', DisplayHandler)
                                     ],
                                     debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
  main()

my index.html looks like this

<title> My First Web Page </title>
<link rel="stylesheet" type="text/css" href="style.css"> </link>

    <form action="/Display" method="post">

        <select name="Applicationname" id="Applicationname" onchange="myFunction()"  >
            <option value="Select">---Select---</option>
                {% for q in appnames %}
            <option value="{{q.Applicationname}}">{{q.Applicationname}}</option>
                {% endfor %}
</select>

Select the Version number
        <select name="Version" id="Version">
            <option value="Select">---Select---</option>
            {% for r in vernums %}
            <option value="{{q.Version}}">{{r.Version}}</option>
            {% endfor %}
        </select>

    <input type="submit" value="Submit" align="center"/>
    </form>

A: Your MainPage.get() routine looks like it's expecting a query string selvalue.value.  Change your index.html like this:
<select name="Applicationname" id="Applicationname"
 onchange="document.location.href='/?selvalue.value="+this.value+"'"  >

This will cause the page to reload and show the vernums for the specified Applicationname.
This is not the only way to solve this problem, but it is the shortest.

A: please have a look at django-smart-select or this question: customizing admin of django to have dependent select fields

A: I built something to do this a while ago.  Read the bottom of this page for an explanation of what you'd need to do to build this:
https://github.com/dragonx/django-hier-ajax-form/blob/master/README.rst
I found out later that there's an existing project that does the same thing:
https://github.com/digi604/django-smart-selects


text:
Q: Can byte-buddy by used as non-reflective way to collect [field]/[method return] values as an collection or map? I was trying to find usable answer but with no luck. I wonder if it would be possible to use byte-buddy for following:
Let's say we have a POJO with number of values. For some specific kind of processing i am interested only in some. I could mark them with an annotation, like @ConditionalData i could put on getters or fields.
Then I could create and inteface, lets say NVPProvider which would return  map field name - value.
Doing this with reflection is possible but it is not too performant. I Was hoping i could use byte buddy to extend the class by the interface and implement method, but i am not really finding how to construct the Implementation to achieve that.
I have went through implementations of:
net.bytebuddy.implementation.Implementation

and tried to search for some examples around web pages, but I haven't recognized the right way to go with.
public interface NVPProvider {
    Map<String, Object> getDataAsNVP();
}

public <O> Builder<O> instrumentType(Builder<O> builder) {
    builder.implement(NVPProvider.class).method(net.bytebuddy.matcher.ElementMatchers.named("getDataAsNVP")).intercept( ??? );
    return builder.implement(NVPProvider.class);
}

I wonder if there is a way that i would iterate the fields and getters and match the Accessible objects by reflectively getting the annotations, however  based on this i would be able to compose the interface method implementation iterating the matched fields and contributing to the result map, the imaginary generated code would look like:
Map<String, Object> result = new HashMap<>();
Object obj0 = getValue001();
result.put("getValue001", obj0);

Object ob10 = accesibleField1;
result.put("ob10 ", ob10 );

Later i could add annotation attribute for better looking keys.
I have seen examples with
MethodDelegation.to(interceptor)

however, then I do now see how to do it without reflection.
I have idea how to so it with Javassist, where you can actually can compose pieces of code you later compile, but I am not sure how to do it with byte-buddy. I have used byte-budy for extension of POJO by simple getters dynamically defined in config file and it looks nice. Having just one byte-manipulation tool would be cleaner.
Thanks for any advices.

A: This is possible in Byte Buddy but you would have to manufacture a custom method body by implementing your own Implementation or its underlying ByteCodeAppender. You could use ASM directly as such visitors expose their MethodVisitor but a bit easier, you could also use the higher-level constructs offered in the net.bytebuddy.implementation.bytecode package. For a method as you describe it, you would first intantiate the hash map:
List<StackManipulation> m = new ArrayList<>();

// new HashMap<>();
m.add(TypeCreation.of(HashMap.class));
m.add(Duplication.SINGLE);
m.add(MethodInvocation.invoke(new MethodDescription.ForLoadedConstructor(HashMap.class.getConstructor());

Subsequently, a ByteCodeAppender offers a description of the instrumented type from which you can navigate to all fields and methods such as:
FieldDescription field = ...

// map.put(fieldName, fieldValue);
m.add(Duplication.SINGLE);
m.add(new TextConstant(field.getName());
m.add(MethodVariableAccess.loadThis());
m.add(FieldAccess.forField(field).read());
m.add(MethodInvocation.invoke(Map.class.getMethod("put", Object.class, Object.class)));
m.add(Removal.SINGLE);

The above code first duplicates the hash map on the stack to retain it for further access, then adds the field name onto the stack, loads the fields value and then invokes the Map::put method. Finally, it drops the put method's return value.
Finally, you need to return the map by adding MethodReturn.REFERENCE.
You can have a look at other Implementations in Byte Buddy to see how this works in detail and ASM provides a good tutorial into byte code fundamentals to explain the stack metaphor that the byte code patterns need to follow.


text:
Q: Duplicating authentication data between the store and localStorage In many React tutorials I have seen the presence of tokens or some other kind of data in localStorage used to drive authentication state in an app. But if I were to make a header/navbar component that shows a link to "sign in" or "sign out" as appropriate for the user's authentication, it appears that I would have to duplicate that localStorage token as state either in a redux store or in a component in order to prompt a re-render when authentication state changes.  Perhaps this bothers me more than it should, but duplicating that information seems redundant and also might necessitate some kind of dummy action to properly set authentication state if there is a pre-existing token in localStorage when a user first visits the app or refreshes the page.
Is there a better way to handle authentication data in a React app than what I have described here?

A: One option would be to take a look into the library redux-persist. It handles all the saving and restoring of your redux state for you between sessions.

A: I don't keep auth tokens/data in Redux or local state, I use an auth module that just reads/writes localStorage, and conditionally render the navbar:

   ...
   {Auth.isAuthenticated() ? 'Sign Out' : 'Sign In'}

and Auth.js:
class Auth {
    static storeToken(token) {
        localStorage.setItem('token', token)
    }

    static isAuthenticated() {
        return localStorage.getItem('token') !== null
    }

    static removeToken() {
        localStorage.removeItem('token')
    }

    static getToken() {
        return localStorage.getItem('token')
    }
}

export default Auth

This still isn't ideal imo since all my state is not in one place, but I do think it is a little better than duplicating information like you said


text:
Q: SQL Server Temporal Tables: Can I record specific changes? I would like to know if I can create a temporal table on a SQL Server database that keeps specific changes.
For example, I have a database that I would like to record any insert/update/delete that is made by a user via SQL Server Management Studio, but I don't want to record changes that are made by an application that interacts with the database.


text:
Q: Questions about singular value decomposition I'm still having trouble understanding the separation between diagonalization and singular value decomposition. I am working with complex matrices so for an arbitrary matrix, I am able to write it as $A = U\Sigma V^\dagger$
My questions are
1) Under what conditions do we have $U = V$? I believe this corresponds to diagonalization so it must be that $A$ is square and $A$ is normal i.e $A^\dagger A = AA^\dagger$. Is this correct or is there a weaker condition?
2) Under what conditions are $dim(U) = dim(V)$? Is it true if $A$ is square that we can achieve this with $dim(U) = dim(V) = dim(A)$?

A: If $A$ is an $m\times n$ matrix, then also $\Sigma$ is $m\times n$, so $U$ must be $m\times m$ and $V$ is $n\times n$.
So if you want that $U$ and $V$ have the same shape, then $A$ must be square.
You're right in thinking that having $U=V$ implies the (square) matrix $A$ is normal: actually it must be Hermitian. If the SVD is $A=U\Sigma U^\dagger$, then $A^\dagger=U\Sigma^\dagger U^\dagger$; since by definition $\Sigma$ is real, we have $\Sigma=\Sigma^\dagger$, so $A^\dagger=A$.
However, here we see a necessary condition so that a unitary diagonalization of $A$ can be a SVD: the eigenvalues of $A$ must be real and nonnegative, that is, $A$ is positive semidefinite.


text:
Q: Ajax script not functioning correctly after server change I have a website which runs a star rating ajax script, from the follow source.
http://coursesweb.net/php-mysql/rating-stars-script-ajax-php_s2
I have changed hosting for the website from a shared platform to a dedicated server which I control with Plesk. Since the change, the rating script has stopped working. All other aspects of the site are functioning correctly.
The following error is logged in the browser console.

Uncaught SyntaxError: Unexpected identifier at
  XMLHttpRequest.cerere_http.onreadystatechange (ratings.js:12)

Does XMLHttpRequest have to be enabled before this will work?
Can anyone offer advice as to why this may have happened?

A: The update to the server meant that the database connection now uses

localhost:3306

The rating script uses a PDO connection which requires that the hostname and PDO be separated.


text:
Q: Como obter o número de linhas de uma StringList e aplicar? Eu tenho uma StringList dentro de um arquivo mensagens.txt, eu gostaria de contar quantas linhas tem essa StringList contida dentro desse arquivo. Para cada linha da string 1 código sera executado dentro código do plugin.
Se a StringList tiver 10 linhas o código ira executar:
web.setScore(1) para a linha 1
web.setScore(2) para a linha 2.....
web.setScore(10) para a linha 10

O código que eu criei é esse:
public class ScoreBoard implements Listener {

    @EventHandler
    public void pj(PlayerJoinEvent e) {
        for (String list : Main.getMensagens().getStringList("Scoreboard")) {;

        Scoreboard scoreboard = Bukkit.getServer().getScoreboardManager().getNewScoreboard();
        Objective obj = scoreboard.registerNewObjective(Main.getMensagens().getString("Titulo"), "dummy");
        obj.setDisplaySlot(DisplaySlot.SIDEBAR);
          Score web = obj.getScore(list);
          web.setScore(1);

        Player p = e.getPlayer();
        p.setScoreboard(scoreboard);
    }
  }
}

O meu problema é com o web.setScore, eu preciso que ele pegue o número de linhas StringList e execute automaticamente.

A: Transforme em um for e passe ter controle sobre o índice.
public class ScoreBoard implements Listener {
    @EventHandler
    public void pj(PlayerJoinEvent e) {
        /*tipo de retorno do getStringList*/ list = Main.getMensagens().getStringList("Scoreboard");
        for (int i = 0;  i < list.length; i++) {
             Scoreboard scoreboard = Bukkit.getServer().getScoreboardManager().getNewScoreboard();
             Objective obj = scoreboard.registerNewObjective(Main.getMensagens().getString("Titulo"), "dummy");
             obj.setDisplaySlot(DisplaySlot.SIDEBAR);
             Score web = obj.getScore(list.get(i));
             web.setScore(i);
             Player p = e.getPlayer();
             p.setScoreboard(scoreboard);
        }
    }
}

Coloquei no GitHub para referência futura.


text:
Q: Intermittent SQL Server connection problem on Linux I am hosting a .NET Core application in Linux (Ubuntu) with SQL Server. The application uses entity framework to read/write to the database hosted on the same server.
The connection string I am using is Server=localhost,1433;Database=mydb;User=sa;Password=XXXXX
I intermittently get the following error reported in the logs when adding a new record:

A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - Success)

Stack trace:
An exception occurred in the database while saving changes for context type 'API.Infrastructure.AppDbContext'.
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - Success)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
   at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransactionAsync(CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
ClientConnectionId:57d1bc57-9b5a-43bb-8617-2729bb82dfa7

I have seen similar questions on SO but they're mostly for old SQL Server versions and require SSMS.


text:
Q: Adding rows in attribute table together using ArcGIS Pro I am using a parcel map and I have a layer with a ton of polygons and those polygons have different names. I combined all the names into categories in the symbology tab but when I go to the attribute table for that layer the ones I combined are no longer combined like in the symbology. I don't want to merge these polygons because I want to be able to count how many polygons are in the categories but I want the rows in the attribute table combined into the groups I put them in in the symbology.
I am using ArcGIS Pro

A: Firstly, we must remember that each row in the attribute table is associated with a feature on the map, and symbology is a layer property that is followed only until the layer is in the contents pane in ArcGIS Pro.

*

*What you can try is using the "show count" property while applying symbology

*

*Your aim is to get it as a table showing the count, use the summarize option to get a table representing the count of all the categorized features

*

*Count

*

*Finally, as an alternative, if you want a group symbology("not the attributes") follow the Group Unique Values link for a better understanding


text:
Q: How to get OAuth working with DotNetOpenAuth and Evernote? I'm trying to write a C# ASP.NET MVC app using the DotNetOpenAuth library that connects to the Evernote Sandbox using OAuth, but I'm having trouble getting it working. My app is fine up until the callback is invoked but when I try to request the exchange of the temporary credentials in step 10 of this diagram, it fails with a 401 Unauthorized.
My callback looks like this:
    public ActionResult OAuthCallback()
    {
        var webConsumer = CreateWebConsumer();
        var accessTokenResponse = webConsumer.ProcessUserAuthorization();

        if (accessTokenResponse != null)
        {
            AccessToken = accessTokenResponse.AccessToken;
        }

        return RedirectToAction("Index");
    }

The exception occurs on the var accessTokenResponse = webConsumer.ProcessUserAuthorization(); line which is what is attempting the credential exchange.
Fiddler shows the following:
Invoking the callback:
GET http://localhost:22297/Home/OAuthCallback?oauth_token=GiddyUpHorsey.13F82BDC264.687474703A2F2F6C6F63616C686F73743A32323239372F486F6D652F4F4175746843616C6C6261636B.CFB67142944B4EB90148DDAFE2120A71&oauth_verifier=93534C2B04F862E57B30D738C3569242 HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Connection: Keep-Alive
Accept-Language: en-NZ
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Pragma: no-cache
Accept-Encoding: gzip, deflate
Host: localhost:22297
DNT: 1
Cache-Control: no-cache

Requesting the token exchange:
Triggered by webConsumer.ProcessUserAuthorization();.
POST https://sandbox.evernote.com/oauth HTTP/1.1
Content-Type: application/x-www-form-urlencoded; charset=utf-8
User-Agent: DotNetOpenAuth.Core/4.3.0.13117
Host: sandbox.evernote.com
Cache-Control: no-store,no-cache
Pragma: no-cache
Content-Length: 369
Expect: 100-continue

oauth_verifier=93534C2B04F862E57B30D738C3569242&oauth_token=GiddyUpHorsey.13F82BDC264.687474703A2F2F6C6F63616C686F73743A32323239372F486F6D652F4F4175746843616C6C6261636B.CFB67142944B4EB90148DDAFE2120A71&oauth_consumer_key=GiddyUpHorsey&oauth_nonce=cHABo5jv&oauth_signature_method=PLAINTEXT&oauth_signature=4c0dd81215379f75%26&oauth_version=1.0&oauth_timestamp=1372288061

The response:
HTTP/1.1 401 Unauthorized
Set-Cookie: JSESSIONID=4CDCD690AEAD69D952CEE4CBED5AC8DC; Path=/
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en
Date: Wed, 26 Jun 2013 23:07:48 GMT
Server: Evernote/1.0
Content-Length: 1587

.....

            Oops, we encountered an error.

            Sorry, we've encountered an unexpected error.

...

(I stripped out much of the HTML from the response)
Why does it fail with 401 Unauthorized?

A: I am not sure if you ever got this working, but I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple

// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
    "https://sandbox.evernote.com",
    "slyrp-1234", // Not my real id / secret :)
    "7acafe123456badb123");

// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);

// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;

// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);

// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);

// ... Once the user authroizes the app, they get redirected to callBackUrl

// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
    Request.QueryString["oauth_verifier"],
    Session["RequestToken"] as RequestToken);

// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);


text:
Q: Python selenium webdriver click functionality Does anyone know how you can click on a link based on the href using the python webdriver bindings. In waitr-webdriver you can do something like this:
browser.link(:href => "http://www.testsite.com/pageOne.html").click

But I haven't be able to find a similar function in the python webdriver. All there is are
find_element_by_class_name
find_element_by_css_selector
find_element_by_id
find_element_by_link_text
find_element_by_name
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_xpath
These are great methods but the site I am testing has no ID's or Classes in their links. So the only unique thing about the links are the href url.
Any help would be greatly appreciated.

A: Under the covers, watir-webdriver is converting the call to find the link where the href attribute is a given value into a WebDriver find-by-XPath expression. Mimicing this in your own code, the appropriate way to handle this in Python would be:
# assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_xpath(".//a[@href='http://www.testsite.com/pageOne.html']")

Alternatively, you could use CSS selectors (which would be faster on IE) as follows:
# again, assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_css_selector("a[href='http://www.testsite.com/pageOne.html']")


text:
Q: FakeTable with tSQLt remove triggers I have jsut started to use tSQLt and is about to test a trigger. I call the FakeTable procedure and do my test but the trigger is not executed. If don't use FakeTable the trigger is executed. That seems to be really bad and I canät find any info that there is any method to readded them.
Then I thought the triggers are removed by FakeTable but I can recreate them after the call and did the following code in my test:
DECLARE @createTrigger NVARCHAR(MAX);
SELECT @createTrigger = OBJECT_DEFINITION(OBJECT_ID('MoveDataFromAToB'))
EXEC tSQLt.FakeTable 'dbo.A';
EXEC(@createTrigger);

I got the following error: "There is already an object named 'MoveDataFromAToB' in the database.{MoveDataFromAToB,14} (There was also a ROLLBACK ERROR --> The current transaction cannot be committed and cannot be rolled back to a savepoint. Roll back the entire transaction.{Private_RunTest,60})"
Anyone that have any experience with tSQLt and know anyworkaround for this problem?

A: There is an ApplyTrigger method on the tSQLt backlog, but it is not finished yet. For now you should be able to use this code in your test:
DECLARE @createTrigger NVARCHAR(MAX);
SELECT @createTrigger = OBJECT_DEFINITION(OBJECT_ID('MoveDataFromAToB'));
DROP TRIGGER MoveDataFromAToB;
EXEC tSQLt.FakeTable 'dbo.A';
EXEC(@createTrigger);

You need to drop the existing trigger as FakeTable does not drop the original table. It just renames it, which leaves the old trigger intact; hence the name collision you did see.
The rollback that tSQLt executes at the end of every test will put the dropped trigger back in place (unless you are doing something really bad in your code). If you are worried about that use sp_rename instead of drop on the trigger.
I would put all this into a helper stored procedure within the test class and call it from the tests that need it. That way, once we have a better solution implemented in tSQLt you will have to change only one place in your code.

A: Thanks Sebastian for your answer. It really helped me too :)
I made a stored proc for the code you gave. I will use this until the 'ApplyTrigger' function is available:
CREATE PROCEDURE [tSQLt].[FakeTableWithTrigger]
    @TableName NVARCHAR(MAX),
    @TriggerName NVARCHAR(MAX),
    @SchemaName NVARCHAR(MAX) = NULL, --parameter preserved for backward compatibility. Do not use. Will be removed soon.
    @Identity BIT = NULL,
    @ComputedColumns BIT = NULL,
    @Defaults BIT = NULL
AS
BEGIN
   DECLARE @createTrigger NVARCHAR(MAX);
    SELECT @createTrigger = OBJECT_DEFINITION(OBJECT_ID(@TriggerName));
    EXEC('DROP TRIGGER ' + @TriggerName);
    EXEC tSQLt.FakeTable @TableName, @SchemaName, @Identity, @ComputedColumns, @Defaults;
    EXEC(@createTrigger);
END

An example of it's useage in a test is:
exec tSQLt.FakeTableWithTrigger 'dbo.MyTable', 'MyTable_SyncTrigger', @Identity = 1


text:
Q: Customizing GtkFileChooser GTK+ noob question here:
Would it be possible to customize the GtkFileChooserButton or GtkFileChooserDialog to remove the 'Places' section (on the left) and the 'Location' entry box on the top?
What I'm essentially trying to do is to allow the user to select files only from a particular folder (which I set using gtk_file_chooser_set_current_folder ) and disable navigating to other locations on the file system.
This is the standard file chooser dialog :

This is what I need:

A: It doesn't look like that is possible with the standard file chooser dialog. For example, here is a document discussing why such a thing would be useful and how it could be implemented, but the idea never made it to fruition.
What you can do, perhaps, is write your own dialog that implements the GtkFileChooser interface, based on the GtkFileChooserDialog code, but hides the location bar and bookmarks list.

A: You can get a handle on the individual children by finding out where there are with gtkparasite and then accessing them with get_children.
Make sure to use .show() instead of .run() for inspecting the dialog with gtkparasite. If you use .run() the dialog is shown in modal mode so you can't inspect it.
For example I hide the Path and Places widgets with the statements below:
dialog = gtk.FileChooserDialog("Open***", None, gtk.FILE_CHOOSER_ACTION_OPEN,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_show_hidden(True)
dialog.set_default_response(gtk.RESPONSE_OK)
vbox = dialog.get_children()[0].get_children()[0].get_children( [0].get_children()[0]
vbox.get_children()[0].hide()
vbox.get_children()[2].get_children()[0].hide()

Of course this is not an exposed API so it can always break from underlying changes.
Hope it makes sense ...
Tried to post an image but I am a new user ....


text:
Q: What does pwd_leak mean in the Auth0 user login logs I have used Auth0 for authentication and to get token for user. I've then created a test user using the Auth0 dashboard.
When I try to login with my Android app, it logins successfully, but in the logs I got records like Success Login and after that pwd_leak.
Can somebody explain what this pwd_leak stands for?

A: Auth0 provides built-in tools to detect anomalies and stop malicious attempts to access your application. This is known as anomaly detection.
One of it's features is the detection of the usage of credentials that have been leaked publicly. See the Breached Password Detection section for more information, but very simplified is that if user tries to login with identical email/password combination to ones that have been publicly leaked then Auth0 can be configured to notify or block those attempts.
The pwd_leak indication on the logs will likely mean that the associated credentials were part of a public leak. The ';--have i been pwned? application might be of interest because it's also another place that tracks known password leaks and a good way to check if you might have been compromised.


text:
Q: How do I distinguish between a mouse click and space bar click in jquery? I have a jquery-ui dialog box with a cancel button which closes the dialog. In this dialog box there is a page which generates a string, and sends it to a Java back end. This string contains spaces. Jquery is interpreting spaces as a click, causing my popup to close before it should.
How would I make an event for cancel button that only gets fired on a mouse click, and not a space bar?
Code:
 $('<div id="popup">').dialog({
                    autoOpen: false,
                    modal: true,
                    buttons: {
                      "Cancel" : {
                            text: "Cancel",
                            id: "cancelButton",
                            click: function(){
                            $('#popup').html('');
                            $('#popup').dialog('close');
                            }
                        },
                    }
                });
var close = function (event, ui) {
            $('#popup').unbind("dialogclose", close);
                    //reload page
                };
            $('#popup').on("dialogclose", close);

            $('#popup').load("index.html").dialog('open');


text:
Q: Uniqueness of Galois group I'm wondering whether the Galois group is unique in the sense that:
Let $E/K$ be a field extension and let $K = E^G$ for $G = Aut_K(E)$. Is it possible that there exists a proper subgroup $H$ of $G$ such that $K=E^H$?

A: Let $\mathbb{F}_p$ be a finite field with $p$-elements. Consider its algebraic closure $\overline{\mathbb{F}_p}$ and let $\phi:\overline{\mathbb{F}_p}\rightarrow \overline{\mathbb{F}_p}$ be the Frobenius automorphism i.e. $\phi(x) = x^p$. $Gal(\overline{\mathbb{F}_p}/\mathbb{F}_p)$ is a profinite group and hence it cannot be isomorphic to $\mathbb{Z}$. Thus
$$\mathbb{Z} \cong \langle \phi\rangle\subsetneq Gal(\overline{\mathbb{F}_p}/\mathbb{F}_p)$$
On the other hand
$$\overline{\mathbb{F}_p}^{\langle \phi\rangle} =\{x\in \overline{\mathbb{F}_p}\,|\,x^p=\phi(x)=x\} =  \mathbb{F}_p$$
Remark.
The general Galois correspondence gives rise to a bijection between closed subgroups of the Galois groups and intermediate fields. One can also derive from it that every subgroup dense in the Galois group has as its fixed points the base field.
For instance, in the example above the closure of the subgroup generated by $\phi$ is equal to $Gal(\overline{\mathbb{F}_p}/\mathbb{F}_p)$.


text:
Q: How do I fix SelectedItem null in listBox when using Task issue I have a problem with something setting up selectedItem in a listbox to null. But it does it every other time, and I can' figure out why it happens. It only happens when I'm trying to use Task to get some data async. I created a very simple project to show the exact problem, which I find difficult to understand.
So here is my xaml
<Window x:Class="AsyncProblem.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Horizontal">
       <ListBox ItemsSource="{Binding Names}" SelectedItem="{Binding SelectedName}" />
        <Button Click="Button_Click" Content="Reload" Width="50" Height="50" />
    </StackPanel>
</Window>

Here is my viewmodel:
namespace AsyncProblem
{
public class MainWindowViewModel : NotifyPropertyChanged
{
    public MainWindowViewModel()
    {
        Names = new ObservableCollection<string>() { "Name", "Second Name",  "Third Name"};
    }

    private ObservableCollection<string> names;
    public ObservableCollection<string> Names
    {
        get { return names; }
        set
        {
            names = value;
            OnPropertyChanged();
        }
    }

    private string selectedName;
    public string SelectedName
    {
        get { return selectedName; }
        set
        {
            selectedName = value;
            OnPropertyChanged();
        }
    }

    Task loadTask;
    int counter = 0;
    public void LoadNewList()
    {
        counter++;
        loadTask = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
                Names = new ObservableCollection<string>()
                {
                    string.Format("{0} new name", counter),
                    string.Format("{0} second new name", counter),
                    string.Format("{0} third new name", counter)
                };
            });
    }
    public void ReselectSelectedName()
    {
        loadTask.ContinueWith(previousTask => SelectedName = Names.LastOrDefault());
    }
    }
}

And here is the calling code
public partial class MainWindow : Window
{
    private MainWindowViewModel dataContext;
    public MainWindow()
    {
        InitializeComponent();
        dataContext = new MainWindowViewModel();
        DataContext = dataContext;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        dataContext.LoadNewList();
        dataContext.ReselectSelectedName();
    }
}

Now when I run this program and press the button, if gets the new list, but it does not set the selectedName. In fact what happens, the selected name changes to iza, and then somehow the selectedname set is called second time with a value of null. So of coursethe listbox loses its selected item.
Even worse is that, it only happens every second button click, when I try to hit the button again then I get the desired behaviour and again the behaviour gets wrong and so on.
Can anybody explain what happens behind the scene?
Thank you

A: In your LoadNewList method, you're creating a new collection for Names:
Names = new ObservableCollection<string>() { "New Daniel", "New James", "New Colin", "New Bruno", "Iza" };

Doing this is breaking your existing binding.
Trying adding/removing/emptying the collection instead:
Names.Clear();
Names.Add("New Daniel");
...


text:
Q: Unable to open a suspicious folder as an administrator I have a strange folder in my C: drive that is named "db0508036d5f02da1733769e". I've already run it through my anti-virus and malware scans and they have found no threats. Is anyone familiar with these types of folders? If so, what is this folder for?
I've tried opening the contents but it keeps telling me that "You don't currently have permission to access this folder." and "You have been denied permission to access this folder. To gain access to this folder you will need to use the security tab." However, when I am in the security tab and edit the permissions for Administrators or SYSTEM, the permission boxes are grayed out and only "Special permissions" is allowed.
Note: I am the Administrator of the computer and am running on Windows 7.
Here is a screenshot of this:

Here is a view of the contents of the folder:

A: @Rik is correct. The folder is an installation folder left over by Windows Update, likely for a .NET update/upgrade.

The installers for the .NET Framework 3.0 and later use a different self-extracting EXE technology, which is why you have observed different behavior depending on what version of the .NET Framework you are trying to install.  The self-extracting logic for these versions of the .NET Framework does the following:

*

*Find the drive on your system with the largest amount of free disk space

*Create a randomly named folder on that drive

*Extract the contents of the EXE to that folder

*Run the setup EXE from within that folder

*After the setup EXE returns, attempt to delete that folder

  Source

The folder can be deleted, but before you do, reboot your computer to make sure any pending installation from Windows Update is completed first, just in case.
You can also run the free version of CCleaner which will safely delete any temporary .NET and Windows Update files automatically.

A: The only reason I can think of an Admin can't open a folder in Windows is because he's not the owner of the folder. On that same security-tab, click "Advanced", and check who it says the owner is under the Owner-tab.If you're an admin, you can take ownership of the folder and then grant yourself all privileges on the Permissions-tab. Be careful with taking ownership though, this can break stuff, and you can't give ownership back to the original owner, it can only be taken. These look like installation files for an update (like @Rik says). So I'm guessing it's not a problem in this case (correct me if I'm wrong).


text:
Q: How to use .Include() in Entity Framework and EF Core Is it possible to use .Include() in a way which works in both Entity Framework 6 and EF Core?
I currently have command handlers which have access to an IQueryable<> but don't know the source of it, and the source can be changed depending on the context running. For example Entity Framework 6 is used when running the actual application, but EF Core is used for test (using the SQLite In Memory provider)
using System.Data.Entity;

class DemoCommandHandler
{
    public void Handle(IQueryable<Blog> blogsQueryable, DemoCommand command)
    {
        //Need to get the blog and all the posts here
        var blogs = blogsQueryable.Include(b => b.Posts).Single(b => b.Id = command.BlogId);

        //Do stuff with blog and posts
    }
}

The above works fine when using Entity Framework but the .Include() does not work when running EF Core (note the using System.Data.Entity);
If the using statement is changed to using Microsoft.EntityFrameworkCore then it works when running EF Core but not Entity Framework.
Is there a way to make a framework agnostic .Include()? Or at least supporting both EF Core and Entity Framework?

A: You could do so using your own extension method that explicitly calls the appropriate extension method:
public static class EntityFrameworkExtensions
{
    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path)
        where T : class
    {
        #if NETCOREAPP2_0
        return Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include(source, path);
        #else
        return System.Data.Entity.DbExtensions.Include(source, path);
        #endif
    }
}

But this would only work if the target framework is known at compile time.


text:
Q: How to fix error while trying to download pdf Running my PDF download or opening screen about 2 months ago does not work. As soon as I click the 'Create PDF' button, it gives me the following error. I talked to the server I was working with and they told me that there was no mistake caused by us. When I try local, there is no problem;

This program is blocked by group policy. For more information, contact your system administrator

A: the directory you used to create PDF is shortage of creation Rights

go to directory
Right click -> Properties -> go to security Tab -> and give all rights to IIS user


text:
Q: Problem installing ubuntu 12.04 (dual boot) on Mac I'm actually running ubuntu 12.04 on my Macbook by DVD. But when I try to install only 2 settings appear:

*

*Replace Mac OS X with Ubuntu

*Something else

while I was expecting for

*

*Install Ubuntu alongside Mac OS X

how can I fix that?
Thanks.

A: This does not work on the newer iMacs if installing Precise. Please make a backup first.(2011)
First, you will need to install rEFIt. Please download the rEFIt DMG package and install it by mounting and running the installer .mkpg file/directory. Once rEFIt is installed, reboot, and you should see an alternate boot menu.
Boot to Mac OSX.
Open a terminal and run sudo diskutil resizeVolume disk0s2 200G, replacing 200G with the size of the Mac OSX partition you want. Insert the Ubuntu Live CD. If the rEFIt menu doesn't appear, hold the option key while rebooting. Hold C while booting to boot the CD. Press f6 when you see a purple screen with a man and keyboard at the bottom. Use the arrow keys to check nomodeset, press esc and select to Try Ubuntu. Start Gparted and create a 1 GB "swap" partition in the free space, and then an EXT4 partition. Remember the label(which may be something like /dev/sda3 Start the installer.
Choose the "somehing else" option when asked how to partition. Select the partition you made(the EXT4 one) ,and click edity below. Set the mount point to /. On the dropdown, select to install the bootloader to /dev/sda3(The EXT4 partition you made), NOT /dev/sda. Install, and reboot.
If you are unableto boot Ubuntu, select the partition tool on rEFIt, and allow it to "sync" the partitoin table(Press Y). Shutdown, and boot again. (Do not reboot, but shutdown)
Adapted from https://help.ubuntu.com/community/MactelSupportTeam/AppleIntelInstallation#Quick_Steps for interface of newer installers
There are also some chat logs from trying to resolve the problem. A raw dump is below. This is not edited, so it contains a few off-topic things also.

*

*http://paste.ubuntu.com/1100526/

*http://paste.ubuntu.com/1100536/

*http://paste.ubuntu.com/1100538/


text:
Q: ContentControl Wrapping Issue I am trying to create a Custom tooltip Control. This control is inherited from ToolTip class. My Custom Tooltip will have a header and a content area. Content could be normal text or any other content (Image, richtextbox etc). Following is the Template Style that custom tooltip control.
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type customControls:FlyoutHelp}">
                <Border BorderThickness="0" Margin="15" Width="300">
                    <Border.Effect>
                        <DropShadowEffect Opacity="0.7"  />
                    </Border.Effect>
                    <StackPanel  TextBlock.FontFamily="Trebuchet MS" TextBlock.FontSize='12'>
                        <TextBlock Background="{StaticResource DellBlue}" Height="23" Foreground="#FFFFFF" Padding="0,4,0,0"  TextAlignment="Center" Text="{Binding HeaderText, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
                        <Border Background="{StaticResource DellLightGrey}" TextBlock.Foreground="{StaticResource DarkestGrey}" Padding="8">
                            <ContentControl   Content="{Binding HelpContent, RelativeSource={RelativeSource Mode=TemplatedParent}}"   />
                        </Border>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

Now as you can see in my template that I am using ContentControl for showing the content of the tooltip. The problem is when my HelpContent is just plain String, it doesn't wrap that text. I can't replace ContentControl with TextBlock because HelpContent could be some other type too (image, richtextbox etc). Can anyone please provide me what is the best way to fix this problem? I will be really very thankful.

A: Replace ContentControl tag with:
<ContentPresenter Content="{TemplateBinding HelpContent}">
    <ContentPresenter.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </ContentPresenter.Resources>
</ContentPresenter>

[Note: you can leave it as a ContentControl, but ContentPresenter is lighter and follows conventions]

A: Change StackPanel to Grid since it doesn't know the width for it to wrap.
<Grid TextBlock.FontFamily="Trebuchet MS" TextBlock.FontSize='12'>
  <Grid.RowDefinitions>
     <RowDefinitions/>
     <RowDefinitions/>
  <Grid.RowDefinitions/>
  <TextBlock Grid.Row="0" Background="{StaticResource DellBlue}" Height="23" Foreground="#FFFFFF" Padding="0,4,0,0"  TextAlignment="Center" Text="{Binding HeaderText, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
  <Border Grid.Row="1" Background="{StaticResource DellLightGrey}" TextBlock.Foreground="{StaticResource DarkestGrey}" Padding="8">
    <ContentControl   Content="{Binding HelpContent, RelativeSource={RelativeSource Mode=TemplatedParent}}"   />
  </Border>
</Grid>


text:
Q: convert video file into flv formate using jsp in my webpage i want to convert uploaded video file into flv formate using jsp or servlets

A: have a look at http://fmj-sf.net/ for inspiration.

A: Either call out to FFmpeg to do the conversion as a batch file, or use a library such as Xuggler to do the conversion in Java.


text:
Q: Looping through all select elements with JavaScript Prototype library How can I (if it is possible) use the Prototype library to loop through all select elements on a page and access the element? In the documentation I found easily shortcuts for referencing elements with certain ids, class names etc. but no reference for elements with certain tag names.
If this is not possible with Prototype, an example with JQuery or another JS Library would be appreciated.

A: A jQuery example, for variety:
$('select').each(function() {
    var selectedOption = $(this).find('option:selected');
    alert('Value: ' + selectedOption.val() + ' Text: ' + selectedOption.text());
});

That will iterate over all selects in the page, and alert the text and value of the selected option on each select.

A: Check out the first example in this page:
$$('select').each(function() {
    //
});

Essentially, the $$ function expects a CSS selector, and a tag name is a perfectly valid selector.


text:
Q: When I try to install hlint I get errors surrounding old-time-1.1.0.3 I first tried to install Hlint. cabal install hlint but then I got the error:
cabal: Error: some packages failed to install:
cpphs-1.20.2 depends on old-time-1.1.0.3 which failed to install.
haskell-src-exts-1.18.2 depends on old-time-1.1.0.3 which failed to install.
hlint-1.9.37 depends on old-time-1.1.0.3 which failed to install.
old-time-1.1.0.3 failed during the configure step. The exception was:
ExitFailure 77

Then I tried to install ghc-mod since I read that hlint is a dependency of that package(?). Thinking that it might resolve the problem. So i did cabal install ghc-mod which gave me the error.
cabal: Error: some packages failed to install:
cpphs-1.20.2 depends on old-time-1.1.0.3 which failed to install.
ghc-mod-5.6.0.0 depends on old-time-1.1.0.3 which failed to install.
haskell-src-exts-1.17.1 depends on old-time-1.1.0.3 which failed to install.
hlint-1.9.35 depends on old-time-1.1.0.3 which failed to install.
old-time-1.1.0.3 failed during the configure step. The exception was:
ExitFailure 77

So it seems to be the same problem, around my the package old-time-1.1.0.3.

A: The best way to know where it fails is to go through each failed package and install them one after the other.
I had issue with haskell-src-exts in which showed up in hlint and when I tried to cabal install haskell-src-exts it was happythat wasn't properly installed.

A: There are lots of variables that could be at play to explain what's going on, including cabal-install and ghc versions. It would be useful if you included the cabal --version and ghc --version output in your question.
That said: I'd recommend trying out the installation using Stack. Once you have Stack installed (on POSIX systems, usually sufficient to run curl -sSL https://get.haskellstack.org/ | sh), you can install with stack --resolver lts-6.16 --install-ghc --no-system-ghc install hlint.

A: Are you on Windows or Linux? What does ghc --version say? What about ghc-pkg old-time? I recommend trying to run cabal install old-time directly, which should reproduce the error directly.

A: Solution by OP.
Modify your cabal config file (you can verify the location by running "cabal user-config init") to contain the following lines:
extra-prog-path: C:\Program Files\Haskell Platform\8.0.1\msys\usr\bin
extra-lib-dirs: C:\Program Files\Haskell Platform\8.0.1\mingw\lib
extra-include-dirs: C:\Program Files\Haskell Platform\8.0.1\mingw\include


text:
Q: Creating an ICS file that is downloadable in WordPress php I'm trying to create a ICS file in wordpress using php. I'm not sure what I'm missing I am kind of new to using wordpress I feel like this should be working but for some reason I am just getting the error
Failed to launch 'begin:VCALENDARVERSION:2.0PRODID:-//ICalendarCreator//NONSGML//ENBEGIN:VEVENTDTSTART:2022/08/22%208:30%20amDTEND:2022/08/22%204:30%20pmSUMMARY:Flexitec%C2%AE%20PVC%20Pipe%20Joining%20and%20InstallationLOCATION:brisbaneDESCRIPTION:SUMMARY:Flexitec%C2%AE%20PVC%20Pipe%20Joining%20and%20InstallationEND:VEVENTEND:VCALENDAR' because the scheme does not have a registered handler.
All I have found is that it's possible that wordpress does somthing differn't to the headers of the files?
This is my code at the moment:
`<?php //Give the iCal export a filename
    $filename = urlencode( $title.'-ical-' . date('Y-m-d') . '.ics' );
    $eol = "\r\n";
    $uid = get_the_ID();
    $created_date = get_post_time('Ymd\THis\Z', true, $uid );
    $url = get_the_permalink();
$organiser = "PARTEC";

    //Collect output
    ob_start();

    // Set the correct headers for this file
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=".$filename);
    header('Content-type: text/calendar; charset=utf-8');
    header("Pragma: 0");
    header("Expires: 0");?>

    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID:-//<?php echo $title; ?>
    CALSCALE:GREGORIAN
    X-WR-CALNAME:<?php echo $title.$eol;?>
    BEGIN:VEVENT
    CREATED:<?php echo $created_date.$eol;?>
    UID:<?php echo $uid.$eol;?>
    DTEND;VALUE=DATE:<?php echo $newTime2.$eol; ?>
    DTSTART;VALUE=DATE:<?php echo $newTime.$eol; ?>
    DTSTAMP:<?php echo $created_date.$eol; ?>
    LOCATION:<?php echo $acflocation.$eol; ?>
    DESCRIPTION:<?php echo $eol; ?>
    SUMMARY:<?php echo $title.$eol; ?>
    ORGANIZER:<?php echo $organiser.$eol;?>
    URL;VALUE=URI:<?php echo $url.$eol; ?>
    TRANSP:OPAQUE
    BEGIN:VALARM
    ACTION:DISPLAY
    TRIGGER;VALUE=DATE-TIME:<?php echo $created_date.$eol; ?>
    DESCRIPTION:Reminder for <?php echo (get_the_title()); echo $eol; ?>
    END:VALARM
    END:VEVENT
    END:VCALENDAR`

    <?php //Collect output and echo
    $eventsical = ob_get_contents();
    ob_end_clean();

    ?>
                            <a href="<?php echo $eventsical; ?>">iCal Calendar`

Would really appreciate if anyone had any incite.
Thank you!


text:
Q: JQuery, AJAX, PHP Passing large amounts of data results in error I'm trying to pass quite a bit of data from a page using AJAX to a PHP script. This works fine for some small amounts of data, but fails with the following error when there is more data.
"PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini. in Unknown on line 0,"

The JQuery I'm using is:
var data = $flowchart.flowchart('getData');

$.ajax({
    type: "post",
    cache: false,
    data: data,
    url: "test.php?name=" +  encodeURIComponent(name) + "&action=" + action,
    success: function(data) {
        console.log (data)
    }
});

data is effectively a json string of data.
eg:
sites: 0: {fromOperator: "SiteA", fromConnector: "output_1", fromSubConnector: "0", toOperator: "location1", toConnector: "input_1", …} 1: {fromOperator: "SiteA", fromConnector: "output_2", fromSubConnector: "0", toOperator: "location2", toConnector: "input_1", …} 2: {fromOperator: "start", fromConnector: "output_1", fromSubConnector: "0", toOperator: "SiteA", toConnector: "input_1", …}

and is read in PHP simply using:
// Values from data.
$sites = (isset($_POST['sites']) && count($_POST['sites']) > 0) ? $_POST['sites'] : NULL;
$staff = (isset($_POST['staff']) && count($_POST['staff']) > 0) ? $_POST['staff'] : NULL;

How can I pass large amounts of data link this but still reference it in PHP using $_POST['sites'] & $_POST['staff'] etc ?
I thought I'd need to do something with JSON, but I can work out what.
Thanks

A: I've got this working by applying JSON.stringify to data before sending it:
data = encodeURIComponent(JSON.stringify(data))

$.ajax({
    type: "post",
    cache: false,
    data: 'data=' + data,
    url: "test.php?name=" +  encodeURIComponent(name) + "&action=" + action,
    success: function(data) {
        console.log (data)
    }
});

Then in my PHP using:
$js= json_decode($_POST['data'], true);
$staff= (isset($js['sites']) && count($js['sites']) > 0) ? $js['sites'] : NULL;
$staff= (isset($js['staff']) && count($js['staff']) > 0) ? $js['staff'] : NULL;

This seems to work as before but is allowing the larger data.

A: add at the start after php tag hope it works.
ini_set('max_input_vars', 30000);


text:
Q: Exposed domain model in Java microservice architecture I'm aware that copying entity classes and properties into DTOs is considered anti-pattern, so by Exposed domain model pattern the same @Entity can be used as both database entity class, and DTO for service and MVC layer. (see here https://codereview.stackexchange.com/questions/93511/data-transfer-objects-vs-entities-in-java-rest-server-application)
But suppose we have microservice architecture where the same set of properties is used as entity in one project with persistence, and as DTO in another project which uses the first one as a service. What's the proposed pattern in such a situation?
Because the second project doesn't need @Entity related functionality, and if we put that class in shared library, it will be tied unnecessary to JPA specific APIs and libraries. And the alternative is to again use separate DTO classes anti-pattern.

A: When your requirements for a DTO model exactly match your entity model you are either in a very early stage of the project or very lucky that you just have a simple model. If your model is very simple, then DTOs won't give you many immediate benefits.
At some point, the requirements for the DTO model and the entity model will diverge though. Imagine you add some audit aspects, statistics or denormalization to your entity/persistence model. That kind of data is usually never exposed via DTOs directly, so you will need to split the models. It is also often the case that the main driver for DTOs is the fact that you don't need all the data all the time. If you display objects in e.g. a dropdown you only need a label and the object id, so why would you load the whole entity state for such a use case?
The fact that you have annotations on your DTO models shouldn't bother you that much, what is the alternative? An XML-like mapping? Manual object wiring?
If your model is used by third parties directly, you could use a subclassing i.e. keep the main model free of annotations and have annotated subclasses in your project that extend the main model.
Since implementing a DTO approach correctly, I created Blaze-Persistence Entity Views which will not only simplify the way you define DTOs, but it will also improve the performance of your queries.
If you are interested, I even have an example for an external model that uses entity view subclasses to keep the main model clean.

A: Thank you for the answers, but emphasize in the question is on microservice (MS) architecture and reusing defined entity POJOs from one MS in another as POJOs. From what I've read on microservices it's closely related to another question - should MSs share any common functionality and classes at all, or be completely independent? It seems there is no definite agreement on it, and also no definite answer, or widely accepted pattern, to this.
From my recent experience here is what I adopted, and it works well so far.
Have common functionality across MSs - yes, in form of a commons project added as dependency to all MSs, with its dependencies set as optional. Share entity classes (expose them in commons) - no.
The main reason is that entity classes are closely related to data store for particular MS. And as the established rule is that MSs shouldn't share data stores, then it makes sense not to share entity classes for those data stores. It helps MSs to be more independent, and freedom to manage their data store in their own way. It means some more typing to add additional DTO classes and conversion between them, but it's a trade-off worth taking to retain MS independence. Reasons Christian Beikov and  Maksim Gumerov mentioned apply as well.
What we do share (put in commons) are some common functionality and helper classes (for cloud, discovery, error handling, rest and json configuration...), and pure DTOs, where T is transfer between MSs (rest entities or message payloads).


text:
Q: detecting only vertical lines in binary image I am processing some binary images where I would like to find the boundary lines of the binary images. So, as an example, here is an input image:

What I do is use edge detection and line detecting hough transform to get the borders from the image. So what i do is:
edges = cv2.Canny(img, 100, 200)
lines = cv2.HoughLinesP(edges, rho=1.0, theta=np.pi/180, threshold=2)

Now drawing these lines result in the following image:

However, what I want to do is etect only the vertical lines i.e. lines going "upwards" in the image. I think I have to manipulate the hough transform parameters but am unable to find the combination that returns only the vertical lines.


text:
Q: Android Button setOnClickListener call function to change button image I have an app with multiple buttons and the image will change depending on different requirements and variables. But, I cannot get the image button change to work within the function. The setOnClickListner will setup the function call and within the function will change the image within the button.
How do I change the image in the button?
MainActivity.kt
package com.example.sandpit9

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    imageButton1.setOnClickListener() { changeimageelement1(R.drawable.button) }
    imageButton2.setOnClickListener() { changeimageelement2(R.drawable.button) }

}
}

private fun changeimageelement1(imageButtonX: Int) {

imageButton1.setImageResource(R.drawable.greenbutton)

}

MainActivity.xml
<?xml version="1.0" encoding="utf-8">
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<ImageButton
        android:layout_width="174dp"
        android:layout_height="154dp" app:srcCompat="@drawable/download"
        android:id="@+id/imageButton1"
        app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp" android:layout_marginRight="8dp"
        app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp" android:layout_marginTop="8dp" app:layout_constraintTop_toTopOf="parent"
        android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent"/> .
 </android.support.constraint.ConstraintLayout>

A: ClickListener method should besetOnClickListener not  setOnClickListener
A sample code:
 button.setOnClickListener{
    counter++
    textView.text = "Click counter : $counter"
 }

Check this tutorial

A: you should not use the () after setOnClickListener, just use
button.setOnClickLisener{
  //your actions go here
}


text:
Q: Get Database Credentials from within the themes file I have a freelancer working on a program for me.
I gave him access to the theme folder via FTP. He uploaded phpMiniAdmin to that folder and, somehow, obtained the database credentials, which he then used to sign in.
How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server?

A: All he needed to do is to put this PHP code in any template file and run it:
var_dump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST);

One line and it will print all the DB credentials.
As you can see - no vulnerabilities are needed.
All PHP code has access to these credentials. And it has to - otherwise it wouldn't be able to access DB...

A: If they can upload files then they can upload a php file that can read the database credentials from wp-config.php. Having upload access to the server can let you do almost anything. Don't give that access to people you don't trust. There's no vulnerability here, you just gave them the keys.


text:
Q: Not breakable list across pages?
Possible Duplicate:
How to make a list of unbreakable items?
How to prevent pagebreak in description environment

My short list is split across two pages. Two bullets are on the end of one page, while the next two are on following page. That is, "A,B" on one page, "C,D" on the next:
\begin{itemize}
\item A
\item B
\item C
\item D
\end{itemize}

How do I force the list (itemize or enumerate) to not break across pages?

A: Here is an example, using \vbox, which you can also replace with a minipage, using \begin{minipage} and \end{minipage}. The reason for me posting this particular example is to demonstrate that this might not be a typographically sound way of handling such problems. Modify the bottom on top of the example without the vbox and you can see the problems. Keeping the list contents together will either create underfull pages or overfull pages. Typographically is acceptable to break lists across pages.
\documentclass{article}
\usepackage[bottom=2.9in]{geometry}
\usepackage{lipsum}
\begin{document}
\lipsum[1-5]
\vbox{%
\begin{itemize}
\item A
\item B
\item C
\item D
\end{itemize}}

\end{document}


text:
Q: Expectation of two successive martingales Consider a martingale $(M_n)_{n \geq 0}$ adapted to the filtration $\{\mathcal{F}_n\}_{n \geq 0}$. I want to prove that:
\begin{align}
\mathbb{E}[M_nM_{n+1}] = \mathbb{E}[M_n^2].
\end{align}
Therefore,
\begin{align}
\mathbb{E}[M_nM_{n+1}] &= \mathbb{E}[M_nM_{n+1} \mid \mathcal{F}_0] \\
&= \mathbb{E}\big[ \mathbb{E}[M_{n+1} \mid \mathcal{F}_n] \cdot M_{n+1} \mid \mathcal{F}_0 \big] \\
&\text{$= \mathbb{E}[ M_{n+1} \cdot M_{n+1} \mid \mathcal{F}_0 ]\qquad$ since $\mathcal{F}_0 \subseteq \mathcal{F}_n^*$} \\
&= \mathbb{E}[ M_{n+1} \cdot M_{n+1}] \\
&= \mathbb{E}[ M_{n+1}^2].
\end{align}
*If $\mathcal{A} \subseteq \mathcal{B}$, then
\begin{align}
\mathbb{E}\big[ \mathbb{E}[X \mid \mathcal{A} ] \mid \mathcal{B} \big] = \mathbb{E}\big[ \mathbb{E}[X \mid \mathcal{B} ] \mid \mathcal{A} \big] =  \mathbb{E}[X \mid \mathcal{A} ].
\end{align}
What happened? Why is this solution not correct?

A: The identity

$\mathbb{E}(\mathbb{E}(M_{n+1} \mid \mathcal{F}_n) \cdot M_{n+1} \mid \mathcal{F}_0) = \mathbb{E}(M_{n+1} M_{n+1} \mid \mathcal{F}_0)$

does not hold true. You cannot apply $(\ast)$ to justify this identity because the term at the left-hand side is not of the form
$$\mathbb{E}(\mathbb{E}(X \mid \mathcal{A}) \mid \mathcal{B})$$
but of the (more general) form
$$\mathbb{E}(\mathbb{E}(X \mid \mathcal{A}) \cdot Y \mid \mathcal{B}).$$

Hint: Write
$$\mathbb{E}(M_n \cdot M_{n+1}) = \mathbb{E}(\mathbb{E}(M_{n+1} \cdot M_n \mid \mathcal{F}_n))$$
and use the pull out property.

A: I believe it is your third equality. The property (*) that you are trying to use may no longer be valid as you are multiplying $\mathbb{E}[M_{n+1} | F_n]$ by $M_{n+1}$. Have you checked the proof to see if it could be modified to account for the addition of such a term?


text:
Q: Submit in-app purchase to itunesconnect always rejected, because it is too old productutil I'm working on an application with in-app purchase feature.
When using xcode 5.0.1 I managed to submit content (non-consumable) to itunesconnect.
After I updated to xcode 5.1, I still can submit to itunesconnect without any error (passes validation) but I always get emails from itunesconnect@apple.com:

Dear developers,
We have discovered one or more issues with your recent delivery for "app-name". To process your delivery, the following issues must be corrected:
      The archive for In-App Purchase '*product_identifier*' is invalid. Productutil version 236 or later is required for In-App Purchase content delivery.
      Once these issues have been corrected, you can redeliver your package.
regards,
     The App Store team

I've been looking productutil, but always find a dead end.
Is there anyone who has experienced this?
Where "productutil" is if you have downloaded?
Thank You

A: I believe this may be an error on Apple's server end. I've run into the same situation last night (4/9/14) and this morning. I've been running Xcode 5.1 for a while now and have uploaded other IAP content packages with no problems over the past few months.
/usr/libexec/productutil doesn't appear to have a way to check the version, at least no way that I can find. I've even tried installing the latest Xcode GM seed (5.1.1) but that didn't help.
I've submitted an inquiry to Apple support. I'll report back if I get an answer.

A: Productutil is part of the standard install for xCode located at :
usr/libexec/productutil
It's needed to build your app package. I think the best thing would probably be to completely reinstall xCode as I'm guessing you are using an older version or you've somehow retained an older version of the productutil file.


text:
Q: How to get a non-shuffled train_test_split in sklearn If I want a random train/test split, I use the sklearn helper function:
In [1]: from sklearn.model_selection import train_test_split
   ...: train_test_split([1,2,3,4,5,6])
   ...:
Out[1]: [[1, 6, 4, 2], [5, 3]]

What is the most concise way to get a non-shuffled train/test split, i.e.
[[1,2,3,4], [5,6]]

EDIT Currently I am using
train, test = data[:int(len(data) * 0.75)], data[int(len(data) * 0.75):]

but hoping for something a little nicer. I have opened an issue on sklearn
https://github.com/scikit-learn/scikit-learn/issues/8844
EDIT 2: My PR has been merged, in scikit-learn version 0.19, you can pass the parameter shuffle=False to train_test_split to obtain a non-shuffled split.

A: All you need to do is to set the shuffle parameter to False and stratify parameter to None:
    In [49]: train_test_split([1,2,3,4,5,6],shuffle = False, stratify = None)
    Out[49]: [[1, 2, 3, 4], [5, 6]]

A: Use numpy.split:
import numpy as np
data = np.array([1,2,3,4,5,6])

np.split(data, [4])           # modify the index here to specify where to split the array
# [array([1, 2, 3, 4]), array([5, 6])]

In case you want to split by a percentage, you can calculate the split index from the shape of data:
data = np.array([1,2,3,4,5,6])
p = 0.6

idx = int(p * data.shape[0]) + 1      # since the percentage may end up to be a fractional
                                      # number, modify this as you need, usually shouldn't
                                      # affect much if data is large
np.split(data, [idx])
# [array([1, 2, 3, 4]), array([5, 6])]

A: I'm not adding much to Psidom's answer except an easy to copy paste function:
def non_shuffling_train_test_split(X, y, test_size=0.2):
    i = int((1 - test_size) * X.shape[0]) + 1
    X_train, X_test = np.split(X, [i])
    y_train, y_test = np.split(y, [i])
    return X_train, X_test, y_train, y_test

Update:
At some point this feature became built in, so now you can do:
from sklearn.model_selection import train_test_split
train_test_split(X, y, test_size=0.2, shuffle=False)


text:
Q: Access individual data in a collection passing to Notification method I have queried a list of users based on a filter to send out notifications and i want to use this collection method to send out the notification.
Collection method
As in the documentation i pass the users collection to the notification and my post data
Notification::send($users, new PostAlert($post));

I believe, this collection method is firing notifications in a loop. One-by-one.If it is, how do i access a user's details inside the notification ? i can only access $post details for now
Notification::send($users, new PostAlert($users, $post));

Doing the above passes the collection and i cannot access a single user detail inside the notification.
I know that i can set the firing on a loop, but i believe it is not the cleanest way
foreach($users as $user)
{
   Notification::send(new PostAlert($user, $post));
}

It would be very helpful if you could help me how would i access a single model passing from collection.

A: It is pretty easy, Try it,
You will find a variable called $notifiable
// PostAlert
...
// toMail() or toArray()
public function toMail($notifiable)
{
    dd($notifiable,"the user laravel is sending to.");
    return (new MailMessage)
                ->line('The introduction to the notification.')
                ->action('Notification Action', url('/'))
                ->line('Thank you for using our application!');
}
...

Happy Codding.


text:
Q: Running php as a sub process I need to call a PHP script from within python. I found this thread on StackOverflow:
Execute php code in Python
So I use this exact method to call my php script. However, I get the following error:
php is not recognised as an internal or external command

First I figured it was because php wasn't in my PATH environment variable, so added it and it worked in my command line, but my Python script kept returning the same error. I also tried adding php to my PYTHONPATH, with the same result. I finally even tried to put the php file in the folder where the php executable is located, but this also didn't work.
What do I need to change in order for this to work?
EDIT
My operating system is Windows 7. This is the code I'm using:
proc = subprocess.Popen("php C:/xampp/htdocs/test/test.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()

I didn't try to run my python script from my command line, which does not produce the error and executes the php script. The script_response variable is empty however.
This is the last line of my test.php file:
return $aResult;

I checked the $aResult, it does contain a value so it's not returning properly. Do I need something else in my php script instead of return ?

A: You could use json to exchange data between processes. Replace return $result in the php script with:
echo json_encode($result);

And in Python:
import json
from subprocess import check_output

result = json.loads(check_output(["php", "/path/to/test.php"]).decode('utf-8'))

If php is not found then read this explanation about how Windows searches for executables.

A: You may have to use the full path to PHP instead of simply calling php.
If you're using a Unix system, you can find the full path by typing which php into your terminal, and that should return something like /usr/bin/php. On Windows, I think you can type where php.exe to find the full path.
Then in your Python script you can do:
# Run PHP script
command = "/full/path/to/php /path/to/myscript.php"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
response = process.stdout.read()
# Print response from PHP script
print response


text:
Q: Does JRuby support the { thing: "hello" } syntax? I'm getting a lot of syntax errors:
SyntaxError: /Users/davidtuite/dev/ruby/seenbefore_client/spec/lib/url_group_spec.rb:40: syntax error, unexpected ':'

      records = stub(length: length)

yet the JRuby Blog says that "Compiler handles all 1.9 syntax now" since JRuby 1.6.0.rc2.
I'm using JRuby 1.6.5
rvm info
  ruby:
    interpreter:  "jruby"
    version:      "1.6.5"
    date:         "2011-10-25"
    platform:     "darwin-x86_64-java"
    patchlevel:   "TM"
    full_version: "jruby 1.6.5 (ruby-1.8.7-p330) (2011-10-25 9dcd388) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_29) [darwin-x86_64-java]"

A: JRuby can be made 1.9.2-compatible by adding the --1.9 command line switch or by adding that switch to the JRUBY_OPTS environment variable:
$ export JRUBY_OPTS='--1.9'
$ bin/irb
irb(main):001:0> RUBY_VERSION
=> "1.9.2"
irb(main):002:0> {asd:3}
=> {:asd=>3}

Don't know how you can tell your RVM that, though. By the way, on Windows the batch syntax is set JRUBY_OPTS=--1.9.


text:
Q: Question about an integration problem to solve in different ways. integration problem
$$\int\frac{dx}{\sqrt{\sin x}\sqrt{\cos^7x}}=\int\frac{\frac{dx}{\cos^4x}}{\frac{\sqrt{\sin x}\sqrt{\cos^7x}}{\cos^4x}}$$
$$=\dots=2\sqrt{\tan x}+\frac25\sqrt{\tan^5x}+C$$
So, I've solved the problem in this way. I found a rule in our text book that if sin and cos are in denominator in multiplied form, then we should divide the numerator and denominator by cos^(summation of the powers of sin and cos). But is there any other way to do it?

A: Substitute $u=\sqrt{\tan x},$ $\frac{dx}{\cos^2x}=2udu$:
$$\int\frac{dx}{\sqrt{\sin x\cos^7x}}=2\int(1+u^4)du=\dots.$$


text:
Q: Logical Pattern With Sensors I have two sensors that control lights. when either one detects someone it turns on the light, when both sensors detect nobody it does not show any light. There are two special cases. If someone went to the first sensor and then left without going to the second sensor, it turns off the light. And if someone went from the first sensor to the second sensor. Not leaving
I tried to use Siddhi's Logical Pattern, but I didn't get the expected results.
@App:name("ControllerRightApp")
define stream inputStream(ternateId string,deviceId int,data string);
@sink(type='log',prefix='LOGGER')
define stream  OutputStream(action string);
@info(name='CargoWeightQuery')
from inputStream[ternateId =='demo']
select ternateId,deviceId, data,json:getString(data,'$.eventName') as eventName
insert into tempStream;
from every ((e1=tempStream)->(e2=tempStream[deviceId==1 and eventName=='out'] and e3=tempStream[deviceId==2 and eventName=='out']))
select "{'deviceId':'3','action':'close'}" as action
insert into OutputStream;

A: I am suggesting below solution as catering moving from one sensor to other is sensor areas are not overlapping is bit tricky. Here we are using a periodic trigger to check the sensor state and update bulb state every 5 seconds. Only compromise is this will have a maximum latency of n seconds to turn on/off lights.
@App:name("ControllerRightApp")
@App:description("Description of the plan")

define stream inputStream(ternateId string,deviceId int,data string);

@sink(type='log',prefix='LOGGER')
define stream  OutputStream(action string);

@PrimaryKey('deviceId')
define table sensorStateTable(deviceId int, state string);

define trigger actionTrigger at every 5 sec;

define trigger populateTrigger at 'start';

from inputStream[ternateId =='demo']
select ternateId,deviceId, json:getString(data,'$.eventName') as eventName
insert into tempStream;

from tempStream[deviceId == 1 or deviceId == 2]
select deviceId, eventName as state
update or insert into sensorStateTable on deviceId == sensorStateTable.deviceId;

--If at least one sensor is in IN state open the switch
from actionTrigger left outer join sensorStateTable as t1 on (t1.state == 'in')
select ifThenElse(state is null, "{'deviceId':'3','action':'close'}","{'deviceId':'3','action':'open'}") as action
insert into OutputStream;

--Queries to add initial state
from populateTrigger
select 1 as deviceId, 'out' as state
insert into sensorStateTable;

from populateTrigger
select 2 as deviceId, 'out' as state
insert into sensorStateTable;


text:
Q: Aerospike nodes without sync We want to deploy aerospike as replacement for memcache. We have two servers to deploy it.
For cache we don't want data replication across multiple nodes. In our architecture we have one cache on each node.
Now issue with aerospike is it's shared nothing architecture which increases the sync between two nodes. Data transfer leads to lot of bandwidth between two machines. As we are on 1gbps network and caching space is around 4Gb, it really uses up all bandwidth once the cache start to filling up.
We just want to use aerospike without its cluster support.
Anyway to turn it off in the aerospike.conf ?

A: That's definitely possible. In the namespace configuration you would state that the replication-factor is 1:
namespace cache {
    memory-size 4G
    storage-engine memory
    replication-factor 1
    high-water-memory-pct 80 # Evict non-zero TTL data if capacity exceeds 80%
    default-ttl 432000 # select a non-zero TTL that makes sense to your use-case
}

With a non-zero TTL the eviction of data happens based on a histogram, with the result being similar to the Memcached LRU eviction. What that number of seconds is will be something you need to estimate. Just be aware that TTL is reset whenever data is written to the record.