text:
Q: Page Not Found when executing a popup screen? I have an input element that's configured as a button (see code below). When clicked, it opens a popup window.
It works perfectly on almost every site its installed on. However, on this particular site, whenever its clicked, it goes to the WordPress "page not found", 404 page.
What could cause this?
<input
    type="button"
    id="testUpload"
    value="Upload"
    onclick="window.open(
        'http://www.mysite.com/wp-content/themes/mytheme/uploader.php?action=test',
        'popup',
        'width=330,height=235,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no'
        );
    return false"
/>

I've verified that the uploader.php file is present.

A: Can you reach the link by manually entering it into the browser's address bar?

*

*If not, then you're dealing with problems with the uploader.php (permissions?)

*If yes, there are some Javascript-related problems.


text:
Q: MySQL and average of multiple columns I need to return average for each of 12 columns I have in a table in DB. MySQL allows one to get average for one column only. The following query (for one column) works:
SELECT station_id, AVG(jan) AS avg_jan
FROM `climate_data`

WHERE element_name = "Temp_mean_mly" AND jan <> -999999
GROUP BY station_id

and the following (for multiple columns) does not (I get syntax error):
SELECT station_id, AVG(jan) AS avg_jan, AVG(feb) AS avg_feb, ... ,
AVG(dec) AS avg_dec
FROM `climate_data`

WHERE element_name = "Temp_mean_mly"
AND jan <> -999999
AND feb <> -999999
AND ...
AND dec <> -999999
GROUP BY station_id

Do I have to use 12 sub-queries to achieve the result I need?

A:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'dec)

dec is a reserved MySQL keyword; changing it to `dec` in your query would probably fix that error for you :).
Edit: note that you're also using it in the WHERE clause; it might work there (as it's unlogical for MySQL to find a keyword there), but keep it in mind that you might also have to escape that one :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swagger UI Download PDF I am using swagger-UI 2.1.3 for API documentation and in backend, I am using spring-webmvc .
I have one API which returns a pdf file, it works fine if I type the URL in browser (it popups a download and downloaded file works fine)
But the same api won't works in swagger ui, it gives me a download link after clicking on "try out", and that link downloads a file, but that file shows me blank pdf pages (corrupted pdf file) .
The response headers are following
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: public
Expires: 0
Access-Control-Allow-Origin: *
Content-Description: File Transfer
Content-Transfer-Encoding: binary
Transfer-Encoding: chunked
Content-Disposition: attachment; filename="example.pdf"
Access-Control-Expose-Headers: Content-Description,Content-Disposition,location
Content-Type: application/pdf
Content-Length: 268288
Date: Mon, 04 Jan 2016 12:18:16 GMT

Any solution around this ?
Addition Info:
This questions seems similar -
AngularJS: Display blob (.pdf) in an angular app
There they are saying that set responseType to arraybuffer in xhr, But i think that swaggar will take care of that (maybe i need to set some configuration??)


text:
Q: MySQL update 2 columns using IF statement I would like to update 2 columns within a table. The POST value is either 1 or 0.
So I have the below query, I not sure is it working but I am looking for better way to do this.
If the POST value ($yes_no) is equal to 1 then I need increase tableA.num_yes +1
and decrease tableA.num_yes -1.
So the same if POST value ($yes_no) is equal to 0.
t.num_yes = IF($yes_no = 1, t.num_yes + 1, t.num_yes),
t.num_no = IF($yes_no = 1, t.num_no - 1, t.num_no),
t.num_no = IF($yes_no = 0, t.num_no + 1, t.num_no),
t.num_yes = IF($yes_no = 0, t.num_yes - 1, t.num_yes)

A: You can alternatively use CASE on this problem. example,
UPDATE  tableName
SET     num_yes = CASE  WHEN $yes_no = 1
                        THEN num_yes + 1
                        ELSE num_yes - 1
                    END,
        num_no = CASE   WHEN $yes_no = 1
                        THEN num_no - 1
                        ELSE num_no + 1
                    END

*

*SQLFiddle Demo

A: Try this one
UPDATE  tableName as t
SET
        t.num_yes = IF($yes_no = 1,t.num_yes + 1,t.num_yes - 1),
    t.num_no = IF($yes_no = 1,t.num_yes - 1,t.num_yes + 1)


text:
Q: Nhibernate order of SQL statements when flushing session According to NHibernate documentation, SQL statements are issued in the following order when a session is flushed:

*

*all entity insertions, in the same order the corresponding objects were saved using ISession.Save()

*all entity updates

*all collection deletions

*all collection element deletions, updates and insertions

*all collection insertions

*all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete()

Why is it forced in this order and is there any way to change it so that the statements are executed in the same order that I give them?

A: It's in that order because it's the safest.
And no, you can't change the order. But also, you never gave NHibernate any order: you just mark entities for persistence; NHibernate determines what to do automatically.
If you think you need more control over individual SQL operations, you can use IStatelessSession instead of a regular ISession. You lose all the stuff NH does automatically (lazy loading, caching, dirty-tracking), but you can (must) say explicitly when to Insert, Delete or Update a record.

A: You can't change the order NHibernate generates SQL in per the above, but you can chunk up the units of work.
eg:
using(var transaction = Session.BeginTransaction())
{
    var company = Session.QueryOver<Company>().First();
    var employee = new Employee{ ID = Guid.NewID() };
    company.Employees.Add(employee);
    Session.Flush();

    var carSpace = new CarParkingSpace { EmployeeID = employee.ID };
    Session.Save(carSpace);

    transaction.Commit();
}

By adding the Session.Flush() - everything to that point will be pushed to the transaction. Without it, NHibernate would try to create a parking space allocated to a not yet existing employee.


text:
Q: How to add values to array from flutter to firestore In Firestore, I have a document with a field of type array, I want to add datetime values to it from flutter app. Can anyone suggest a way to do it?

A: Storing:
Use DateTime.now().millisecondsSinceEpoch
This would give you an int value in return that you can save in Firestore.
Retrieving:
You can easily get DateTime from the saved value using DateTime.fromMillisecondsSinceEpoch(valueSavedInFirestore)


text:
Q: How to add sprite to sencha touch chart I have sencha donut chart in window panel and text sprite in another panel. but i need to integrate this sprite with donut chart, so that if i will move the chart, the added text sprite will move accordingly.
Here is my code:
Ext.setup({
    tabletStartupScreen: 'tablet_startup.jpg',
    phoneStartupScreen: 'phone_startup.jpg',
    tabletIcon: 'icon-ipad.png',
    phoneIcon: 'icon-iphone.png',
    glossOnIcon: false,

    requires: ['Ext.chart.Panel',
        'Ext.chart.axis.Numeric',
        'Ext.chart.axis.Category',
        'Ext.chart.series.Pie'],
    onReady: function () {

    var donut = false;
        window.initExample('Pie Chart',
            "This example's uses many interactions.

" +
                "
Dragging the Pie Chart will rotate it.
" +
                "
Tap and hold will bring up additional information about a slice
" +
                "
Double-Tap will reset the chart back to the initial state (after confirmation)
");
        window.createPanel(new Ext.chart.Chart({
            themeCls: 'pie1',
            theme: 'Demo',
            store: store1,
            shadow: false,
            animate: true,
            insetPadding: 20,
            legend: {
                position: 'left'
            },
            interactions: [
                {
                    type: 'reset',
                    confirm: true
                },
                {
                    type: 'rotate'
                },
                'itemhighlight',
                {
                    type: 'iteminfo',
                    gesture: 'longpress',
                    listeners: {
                        show: function (interaction, item, panel) {
                            var storeItem = item.storeItem;
                            panel.setHtml(['

Month: ' + storeItem.get('name') + '
', '
Value:  ' + storeItem.get('2007') + '

'].join(''));
                        }
                    }
                }
            ],
            series: [
                {
                    type: 'pie',
                    field: '2007',
                    showInLegend: true,
                    highlight: false,
                    donut: 50,
                    listeners: {
                        'labelOverflow': function (label, item) {
                            item.useCallout = true;
                        }
                    },
                    // Example to return as soon as styling arrives for callouts
                    callouts: {
                        renderer: function (callout, storeItem) {
                            callout.label.setAttributes({
                                text: storeItem.get('name')
                            }, true);
                        },
                        filter: function () {
                            return false;
                        },
                        box: {
                            //no config here.
                        },
                        lines: {
                            'stroke-width': 2,
                            offsetFromViz: 20
                        },
                        label: {
                            font: 'italic 14px Arial'
                        },
                        styles: {
                            font: '14px Arial'
                        }
                    },
                    label: {
                        field: 'name'
                    }
                }
            ]
        }));
            mydrawComponent = new Ext.draw.Component({
               id:'mydrawComponent',
            fill:'blue',
            height: '100%',
            width: '100%',
            fullscreen: true,
            items: [{type: 'text',
                'text-anchor':'center',
                fill: 'black',
                font: '20px Arial',
                text: 'Investment',
                x: 860,
                y: 380,
                zIndex: 2},
                {type: 'text',
                'text-anchor':'center',
                fill: 'black',
                font: 'Bold 30px Arial',
                text: '$165m',
                x: 860,
                y: 410,
                zIndex: 3}]
        }).show();
        new Ext.chart.Panel({
        fullscreen: true,
        title: 'Text',
        items: mydrawComponent
          });
    }
});

This is the sencha touch donut chart javascript code. and here is the html code:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" href="../CSS/sencha-touch.css" type="text/css">
    <link rel="stylesheet" href="../CSS/touch-charts-demo.css" type="text/css">

    <title>Donut Chart</title>

I was thinking for 2 different approaches:
1) If we can get Donut chart center point X/Y co-ordinates then we can add sprite to that X/Y co-ordinates.
2) We can add panel to the chart and then add drawComponent or sprite to that panel.
Please let me know how we can do this.
Thanks!!


text:
Q: How do I use react to render the spring-boot api response from a link in an email when it is clicked? For security reasons, I can't post code snippets. We are building a rest api using spring-boot which is consumed by the frontend team using React.
I send a mail containing a link (eg: host/appointment/confirm?token=theGeneratedToken) when an appointment is created for visitors. When they each click the link, it calls that endpoint which uses the token to get some data, send the response as a json data which the Frontend guys have to display to the individual user.
I want to be able to send the response but without the "token=theGeneratedToken" in the url (cause right now, when the link is clicked and the response is sent, it still displays the link that made the request in the address bar a d displays the json data) and also want to be able to intercept the response and display it to the user using react.


text:
Q: How can I know how much memory allocated per every app running in glassfish? How can I know how much memory allocated per every app running in glassfish ?
Our glassfish application server is running on 10 GB of RAM but.  with more than 20 application running (WARs) , I need to know how much memory consumed or allocated for every application at certain time ?

A: You may use a profiling tool connected to your GlassFish - e.g. Netbeans, as described in detail here.


text:
Q: Run MySql from Java failed I'm trying to run MySql command from Java process using Process exec
the code:
String s = "mysql -h192.168.0.1 -u USER -PASSWORD DB_NAME-e \"select * from table\"
System.out.println(s);
Process p = r.exec(s);
p.waitFor();

When I'm running the sql query from command line its works great, but from the Java process I get '
Usage: mysql [OPTIONS] [database]... with all the MySql options.
Without the -e parameter its seems to work, no error but of course nothing happens.
In Win& machine its also works great, not on the deploy Linux machine.
Any ideas what I'm doing wrong?

A: Example of Java using MySQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

// assume that conn is an already created JDBC connection (see previous examples)

Statement stmt = null;
ResultSet rs = null;

try {
    stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT foo FROM bar");

    // or alternatively, if you don't know ahead of time that
    // the query will be a SELECT...

    if (stmt.execute("SELECT foo FROM bar")) {
        rs = stmt.getResultSet();
    }

    // Now do something with the ResultSet ....
}
catch (SQLException ex){
    // handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
    // it is a good idea to release
    // resources in a finally{} block
    // in reverse-order of their creation
    // if they are no-longer needed

    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException sqlEx) { } // ignore

        rs = null;
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException sqlEx) { } // ignore

        stmt = null;
    }
}

Taken from here.

A: Try this, see if it aids your efforts
http://pastebin.com/XpRyGQBq
Usage:
                DBConnectionHandler | new DBConnectionHandler(connectionURL, username*, password*)          ResultSet | +query(String sqlStatementGoesHere)
                     void | +update(String sqlStatementGoesHere)
                     ResultSet | +getTables()
*means optional


text:
Q: funcion contactenar textos en java /**
* Desarrollar un algoritmo que permita concatenar dos cadenas (colocar
* la segunda inmediatamente después de la primera), hay que tener en
* cuenta que la cadena resultante tendrá un tamaño mayor que
* cualquiera de la cadenas operandos si son distintas de la cadena vacía
* (la cadena resultante debe quedar guardada en una variable aparte).
**/
```
public class Problema5 {

    //funcion que realizara la concatenaicion de los textos ingresados
    public static String contactenarTexto(String texto1, String texto2){
        String s = texto1 + ", " + texto2;
         return s;
    }

    //Realizar el proceso
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String texto1;
        String texto2;
        System.out.println("Ingresa el 1er texto");
        texto1 = sc.next();
        System.out.println("Ingresa el 2do texto");
        texto2 = sc.next();
        System.out.println(contactenarTexto(texto1, texto2));
    }
}
```

A: Si queres que no figure la " , " tenes que borrarla de String s = texto1 + ", " + texto2;
Deberias usar el nextLine() para que te tome todo. Lo probe y funciono:
    System.out.println("Ingresa el 1er texto");
    texto1 = sc.nextLine();
    System.out.println("Ingresa el 2do texto");
    texto2 = sc.nextLine();


text:
Q: if (fork()) fork() I am studying for an OS quiz and I did not understand what output
if(fork())
    fork()

will produce.  Can someone explain?
I didn't understand this line:
if(fork())

Edit:
What I meant with "output" is how many processes will be there if this code was executed.
Sorry I'm a bit dizzy after studying.

A: Perhaps you are best off just trying it, reading the documentation for fork, and then, if it still doesn't make sense, asking a more specific question about what part you don't understand.
Start by trying this:
#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv){
    int x,y=0;
    x = fork();
    if (x) y = fork();
    printf("x: %d, y: %d\n",x,y);
    return 0;
}

A: i had a same problem like you.
the meaning of  ::::::> if (fork())
if (fork() !=0), and as you know:

*

*fork(): can take 3 values!

*fork() = 0 for child.

*fork() < 0 error.

*fork() > 0 parent.
So:
if ( 0 != O ) ==> false (in this case you dont have to do the 2 fork())
if (-123 != 0 ) ==> True (yes you have).
if (5 != 0 ) ==> true (yes you have).
good like

A: Here's a hint: if (fork()) is just a short way of writing if (fork() != 0).

A: for parent
if (fork()) is

evaluated as
if(pid_of_child)

and for child process it is evaluated as:
if(0)

that is it :)


text:
Q: Thread 1: Program received signal:"Sigbart 1" When I run the app in the iPhone Simulator, everything works just fine .. but with time I'll try to get my iPhone

Thread 1: Application Received
  signal:" Sigbart 1"

why?
Here is the code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

golfbaner *detailViewController = [[golfbaner alloc] initWithNibName:@"Golfbaner" bundle:nil];

detailViewController.golf = [banenavn objectAtIndex:indexPath.row];

[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];

}

XCode says it's HERE:

[self.navigationController pushViewController:detailViewController animated:YES];

it goes wrong
I can admit that I'm quite a beginner.... lol

A: seems to be u are new bee.so here i assume u would be created the golfbaner with nib file .so it would be same as filename for nibname.
Golfbaner.NIB is not with your project.//check out this
maybe like golfbaner.NIB
so use
golfbaner *detailViewController = [[golfbaner alloc] initWithNibName:@"golfbaner" bundle:nil];

A: Most likely is that detailViewController is nil. If you look at the console output it will tell you for certain.
The reason its nil on hardware is that the file system is case sensitive on hardware and hence
golfbaner *detailViewController = [[golfbaner alloc] initWithNibName:@"Golfbaner" bundle:nil];
"Golfbaner" != "golfbaner"
Check your nibname for case match. I suspect its "golfbaner.xib".
See iOS Objective-C Image file name/path different behavior betwewen simulator and device
As a style point class names should be capitalised otherwise it makes a class hard to separate from a variable when reading code.

A: It may be spelling mistake after @"Golfbaner"
just copy nibfile name and paste it.


text:
Q: In Android Studio How Can I Set Gradle JDK Version for all Projects I'm using Android Studio Dolphin version 11.0.13+  I upgraded recently from an older version.  The older version used a Gradle JDK Version of 1.8 and now it uses 11.
To set the Gradle JDK Version to version 11 on every new project I create, I do the following:
'''
File >> Project Structure >> SDK Location
Click the link in the sentence JDK location was moved to Gradle Settings. Then, in the new pop-up screen, select desired version in Gradle JDK dropdown.
Is there a way to set the ```Gradle JDK Version`` in Android Studio so it is automatically set when I create a new project, so I don't have to do it every time?
I have other software that uses JDK and not sure if removing 1.8 will affect them.  I need to look into them.
Thanks for any help,


text:
Q: Not able to push object in an array I am trying to iterate over two array of objects and trying to push combined object in a new array. I have two arrays, allData and users. I am iterating over these array and if author from allData matches the id of users array then I am pushing data into newData array.
But I am not able to access imageURL while pushing into the newData array. Can someone point out why it is happening and what is solution
let allData = [{
    "id": 5,
    "message": "bnnnbnb",
    "parentId": 1,
    "author": 2
}];

let users = [{
    "id": 1,
    "name": "abc",
    "imageUrl": "avatar1.jpg"
}, {
    "id": 2,
    "name": "def",
    "imageUrl": "avatar2.jpg"
}, {
    "id": 3,
    "name": "qwe",
    "imageUrl": "avatar3.jpg"
}];

let newData = [];
allData.map((dataItem) => {
    users.map((user) => {
        if(dataItem.author === user.id){
            newData.push({...dataItem, user.imageUrl})
        }
    })
})

I am expecting below result:
let newData = [{
    "id": 5,
    "message": "bnnnbnb",
    "parentId": 1,
    "author": 2,
    "imageUrl": "avatar2.jpg"
}];

A: You need to define property imageUrl in map and then push into array.

let allData = [{
    "id": 5,
    "message": "bnnnbnb",
    "parentId": 1,
    "author": 2
}];

let users = [{
    "id": 1,
    "name": "abc",
    "imageUrl": "avatar1.jpg"
}, {
    "id": 2,
    "name": "def",
    "imageUrl": "avatar2.jpg"
}, {
    "id": 3,
    "name": "qwe",
    "imageUrl": "avatar3.jpg"
}];

let newData = [];
allData.map((dataItem) => {
    users.map((user) => {
        if(dataItem.author === user.id){
            dataItem.imageUrl = user.imageUrl;
            newData.push(dataItem);
        }
    })
})
console.log(newData);

A: You're really close, you'd want something like this:
    let newData = [];
    allData.map(dataItem => {
        users.map(user => {
            if(dataItem.author === user.id){
                let imageUrl = user.imageUrl;  // define the name of the property
                newData.push({...dataItem, imageUrl})
            }
        })
    })

So json output would look like this:
[
  {
    "id": 5,
    "message": "bnnnbnb",
    "parentId": 1,
    "author": 2,
    "imageUrl": "avatar2.jpg"
  }
]

A: newData.push({...dataItem, imageUrl: user.imageUrl})

This would fix the problem. The name definition is missing from your code

A: Better if you use find like this:
const newData = allData.map((dataItem) =>
  ({
    ...dataItem,
    imageUrl: (users.find(user => dataItem.author === user.id)||{}).imageUrl
  }))

A: Map over the array of objects using map and then match id's using find and then push the matched record to the resultant array

let allData = [
  {
    id: 5,
    message: "bnnnbnb",
    parentId: 1,
    author: 2
  }
];

let users = [
  {
    id: 1,
    name: "abc",
    imageUrl: "avatar1.jpg"
  },
  {
    id: 2,
    name: "def",
    imageUrl: "avatar2.jpg"
  },
  {
    id: 3,
    name: "qwe",
    imageUrl: "avatar3.jpg"
  }
];

let newData = [];
let output = allData.map((dataItem, i) => {
  let temp = users.find(user => dataItem.author === user.id);
  newData.push({ ...dataItem, imageUrl: temp.imageUrl });
  return newData;
});

console.log(newData);

A: You should use newData.push({...dataItem, imageUrl: user.imageUrl}) instead.
You need to define the name of the property imageUrl in the new object you're pushing.


text:
Q: yield return in custom foreach not working as expected I have an overrided SaveChangesAsync EF method as following:
    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        ChangeTracker
            .Entries()
            .Where(e => e.State == EntityState.Added)
            .Select(e => e.Entity as BaseEntity)
            .ForEach(e => e.ModifiedOn = e.CreatedOn = DateTimeOffset.Now);

        return base.SaveChangesAsync(cancellationToken);
    }

BaseEntity is also my class with some common properties like CreatedOn and every entity inherits from this class. This overrided method uses my own ForEach extension:
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (var item in enumerable)
        {
            action(item);
            yield return item;
        }
    }

And the foreach loop is not executing when there is a yield statement. If I change it to this:
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (var item in enumerable)
        {
            action(item);
        }

        return enumerable;
    }

Then it works perfectly. Why does yield is not executing it this iteration?

A: Deferred execution. The code is executed at the time when you consume the yielded items, eg. by looping over the result or by calling .ToList() on it. In your code example it seems like you never consume the result of the iteration, so it is never executed.

A: Because an iterator needs to iterate
Call ToList();
yield (C# Reference)

You use a yield return statement to return each element one at
  a time.
You consume an iterator method by using a foreach statement or LINQ
  query. Each iteration of the foreach loop calls the iterator method.
  When a yield return statement is reached in the iterator method,
  expression is returned, and the current location in code is retained.
  Execution is restarted from that location the next time that the
  iterator function is called.

In short
The call to ForEach doesn't execute the body of the method. Instead the call returns an IEnumerable, Since nothing enumerates over it, the method doesn't even hit the body at all as it has never started iterating.

A: If you use yield return or yield break your code will only be executed if someone iterates over the IEnumerable<T> you get from the function.
The yieldoperator makes it possible to write lazy code.
Append .ToList() or .ToArray() to the statement, but I recommend .ToList(), because .ToArray() needs to create multiple arrays if the argument is not of the type ICollection<T>.
See


text:
Q: How does the baryon asymmetry control temperature fluctuations of CMB? The temperature fluctuations of the Cosmic Microwave Background (CMB) have a sensitive dependence on the quantity of baryon asymmetry of the universe. In fact, analysis of CMB fluctuations is one of the ways of inferring the amount of baryon asymmetry. However, purely on physical grounds, how does one understand how the amount of baryon asymmetry controls the fluctuations CMB temperature?

A: I am afraid this will not be a complete answer; also, there is a similar question on the site [How does the CMB constrain the baryon asymmetry? ].
If the universe were uniformly occupied by equal amounts of matter and antimatter, it is reasonable to imagine that the CMB spectrum would take note of the frequent annihilations. I am going to quote the following recent work on this. The crux of their argument is that "if large domains of matter and antimatter exist, then annihilations would take place at the interfaces between them. If the typical size of such a domain was small enough, then the energy released by these annihilations would result in a diffuse gamma ray background and a distortion of the cosmic microwave radiation". This paper in turn cites other, earlier work on this issue, but these date far back, so I will not cite them here.
If the universe had far separated regions dominated by matter or antimatter, so that annihilations were infrequent, this would not be as visible, so there is a question of how efficient annihilations have to be to leave its signature on the CMB. Nevertheless, in a uniform plasma, large enough antimatter density would have an imprint on CMB as this diffuse background.

A: In the early universe, it is expected that baryons and anti-baryons existed. As the universe cooled, it would become impossible to create baryon/anti-baryon pairs. The remaining baryons and anti-baryons would annihilate, ultimately resulting in photons. The baryon to photon ratio after these annihilations run to completion characterises the baryon asymmetry; the excess of baryons to anti-baryons that must have existed in order for baryons to be present in the universe today.
The CMB arises about 400,000 years after the big-bang, when the universe cooled sufficiently to allow electrons to combine with protons and form a transparent atomic hydrogen gas. This occured at 3000 K and the photons emitted at that time have been redshifts by a factor of 1100, so they are mainly at microwave wavelengths.
To first order, the CMB is totally uniform and isotropic (after removing the effects of the peculiar velocity of our Galaxy with respect to the CMB). Small fluctuations in temperature of about 1 part in $10^5$ are caused by compressions and rarefactions in the gas at (and after) the epoch when the CMB was generated.  Broadly, compressions heat the gas and cause a temperature rise and rarefactions the opposite.
These acoustic oscillations can be thought of as an oscillator where radiation pressure acts as a spring that is being compressed by the tendency of gravitational mass to clump. The size of the oscillations is therefore dependent on the ratio of radiation pressure to the density of self-gravitating material.
At the time of the CMB formation, any dark energy is negligible compared with the matter density. The matter is in the form of baryons, which interact with the radiation field, and dark matter which does not. It is the baryon density which acts as the mass in the oscillation analogy above. If you increase the baryon density relative to the radiation pressure, which is controlled by the number of photons, then that mass gets bigger and has the effect of making the compressions in the oscillation deeper. If the compressions get deeper, the principle acoustic peaks in the CMB spatial spectrum get stronger.
Thus measurement of the amplitude of these acoustic peaks in the CMB spatial spectrum directly measures the baryon to photon ratio at the epoch of CMB creation, which in turn tells us what the baryon asymmetry was (in a uniform universe), because the number of baryons is conserved and the number of photons produced by baryon/anti-baryon annihilation is also (almost) conserved since mechanisms that absorb photons are in balance with mechanisms that create photons.

A:
However, purely on physical grounds, how does one understand how the amount of baryon asymmetry controls the fluctuations CMB temperature?

From a cursory reading of this reference,, the fluctuations called acoustic oscillations on the CMB temperature

Imagine an overdense region of the primordial plasma. While this region of overdensity gravitationally attracts matter towards it, the heat of photon-matter interactions creates a large amount of outward pressure. These counteracting forces of gravity and pressure created oscillations, analogous to sound waves created in air by pressure differences.

In their model, they assume that if matter and antimatter densities exist in the primordial plasma , extra gamma rays due to the annihilations would change the acoustic oscillations by changing the densities locally where the annihilation takes place. They have modeled this behavior and fit a parameter for the baryon density to the data.


text:
Q: What happened to the "Run" and "Run On" commands in Visual Studio 2010 Database Projects? I have migrated a database project from VS2008 to VS2010.  While in VS08, I used to be able to right-click on a .sql or .cmd file and select a "Run" or "Run On" command from the context menu.
In VS2010, though, these menu items seem to have gone away.
I have a number of .sql and .cmd scripts that I am used to being able to run directly from the Visual Studio IDE.
Can someone point me in the right direction?
Thanks,
Steve

A: Open the sql source you want to execute. Now, right click in the editor and select "Execute SQL". First time you will be asked to connect to a database. If you want to execute on a second database you have to right click and select "Connection->Disconnect" first.

A: Unfortunately they have not been implemented (much to the annoyance of developers)
MS say:

Unfortunately we were unable to add
  the right click on database
  reference/server explorer conx to the
  product.

More details at:
http://social.msdn.microsoft.com/Forums/en/vstsdb/thread/f374c604-a7eb-496d-a261-9374790cdbf9


text:
Q: Stuggling with unexplained behaviour in Spring Boot: using profiles I have two different environments that need different property values and have researched that the proper way to do this is using spring profiles.  As such I have setup two different files:
application.properties
application-dev.properties

The run-time environment is setup and includes the following:
spring.profiles.active=dev

Inside the application.properties file a property "foo.bar" set where:
foo.bar=defaultProp

in the applications-dev.properties file
foo.bar=devProp

Inside the app the following code is included:
@Value("${foo.bar}")
String foobar;

@Autowired
Environment env;

When I run the app with the following:
String x = env.getProperty("spring.profiles.active");

x reports the value of "dev" (working as expected)
BUT
foobar reports its value as "defaultProp"
Both the applications.properties and applications-dev.properties are located together in the same directory.
Later the following was included for testing:
for(String s: env.getActiveProfiles())
{
   logger.info("Act:" + s);
}
for(String s: env.getDefaultProfiles())
{
   logger.info("Def:" + s);
}

with the following output:
 Act:dev
 Def:default

Again this was also expected and appears to be working
Finally, another variable was inserted into application-dev.properties
ding=dong

and in the app the following code was wired in
@Value("${ding}")
String dingvalue;

Low and behold the value of "dingvalue" reports as "dong", again this is working as expected -- values are being picked up from the application-dev.properties file!
Hence it appears that the active profile is actually being set to "dev" and values are being picked up as expected.
Finally, according the doc.spring.io:

23.4 Profile-specific properties
In addition to application.properties files, profile-specific
  properties can also be defined using the naming convention
  application-{profile}.properties.
Profile specific properties are loaded from the same locations as
  standard application.properties, with profile-specific files always
  overriding the default ones irrespective of whether the
  profile-specific files are inside or outside your packaged jar.

Can anyone please explain why the application.properties value is not being overwritten by the application-dev.properties as per the documentation?

A: It is working as expected.
/product-model-configuration/src/main/resources/product-model.yml:
foo:
  bar: defaultProp
/product-model-configuration/src/main/resources/product-model-loc-isolated.yml:
foo:
  bar: bar


text:
Q: populating content inside div into multiple vertical coumns I have which is populated with content. How can this content vertially align into multiple columns like it's on image.
Update:

       {{ n }}

A: maybe this can help:

var sec = document.body.getElementsByTagName("section")[0];
for (var i=1; i<=150;i++){
    var n = document.createTextNode(i);
    var li = document.createElement('li');
    li.appendChild(n);
    sec.appendChild(li)
}
li{list-style:none}
section{
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;
}


text:
Q: What's the best way to upgrade from a Drake version that is >3 months old? I have some code using an older version of Drake, and I'd like to upgrade to a much newer version.
How should I proceed?

A: TL;DR
For the quickest but most informative way to upgrade, you should incrementally upgrade across releases that are 3 months or less apart:
https://drake.mit.edu/release_notes/release_notes.html
More words
For stable public API that needs to be removed, we try to mark old API as deprecated for about a 3-month period; these deprecations should include warnings that direct you towards newer API (or alternatives). In C++, this should show up as a build or runtime warning. In Python code, it should show up as a runtime warning. In Bazel code, it should show up during build process.
At present (2021-04), Drake releases on a monthly cadence, so generally you just need to skip 3 minor versions.


text:
Q: How do I concisely check for nulls in a long method chain in Scala? I'm in the situation that I receive a tree data structure from outside, which can be of several different shapes.
I need to do a sorta switch case depending on what kind of tree I get. The code I'm writing is beginning to look like this:
val first = Option(root.getA)
    .flatMap(o => Option(o.getB))
    .flatMap(o => Option(o.getC))
...
val second = Option(root.getA)
    .flatMap(o => Option(o.getD))
    .flatMap(o => Option(o.getE))
...
first.getOrElse(second.getOrElse...

'first' checks if the tree has the shape root->A->B->C..., 'second' checks if the tree has the shape root->A->D->E... etc.
I feel like there ought to be a simpler way to express this idea in code, since all this code is doing is checking for null at every step by wrapping and unwrapping Options, but I can't find it.

A: If getA etc are placeholders for something with parameters like getValue("A"), you can write a simple function that took root and ("A", "B", "C") and easily walk the tree checking for nulls along the way. I assume you've asked the question because it's not this simple. However you could parameterise on method calls using reflection.
Another possibility if the tree is relatively small or your Scala code is performing the majority of the work on it is to recursively copy and transform the tree into a more Scala-like structure that is easier to process. If you are feeling particularly twisted, you could transform it into an XML document and then use pattern-match using XML primitives.
Alternatively, you could write custom extractors if there are relatively few different getX functions:
object GotA {
  def unapply(x: Thing) = Option(x) map {_.getA}
}

Then your code becomes simple pattern-matching like this:
root match {
   case GotA(GotB(GotC(x))) => x
   case GotA(GotD(GotE(x))) => x
}

If the node-finding rules are so irregular that it's not amenable to any of these approaches, you can at least use a for comprehension that's the equivalent code to what you gave, which you may find more aesthetically pleasing:
val first = for {
  a <- Option(root.getA)
  b <- Option(a.getB)
  c <- Option(b.getC)
} yield c

Sadly, because you've heavily anonymised the question and don't indicate how many of these lookups would be required or how complex they are, I can't recommend a specific solution.

A: You could do:
val first = Try(root.getA.getB.getC).toOption

But this can be slow, and not recommended. Much better way to make your getN methods return Option, and use them as you originally intended, but with for-comprehension:
val first = for {
       a <- root.getA
       b <- a.getB
       c <- b.getC
       ...

A: You can do this
case class Node(val a: Node, val b: Node, val c: Node, val data: Int)

node match {
    case Node(a: Node, b: Node, c: Node, _) => ...
    case Node(null, b: Node, c: Node, _) => ...
    case Node(a: Node, null, c: Node, _) => ...
    case Node(a: Node, b: Node, null, _) => ...
    case _ => ...
}


text:
Q: Как изменить названия кнопок в MessageBox в C#? Как можно изменить названия кнопок в MessageBox в C#?
A: Никак. Но можно создать форму нужных размеров, повесить там кнопки, информацию (label), и открывать её как MessageBox по виду, единственное лишний код будет, MessageBox для того и придуман что бы одной строчкой её показать и что-то так написать.
Открыть форму можно так:
Form form = new Form1();
form.ShowDialog();

На это форме помещаешь кнопку и обработчик.
Закрыть форму:
form.Close();

A: Не соглашусь с ответами Василия и johniek_comp, возможность изменить тексты кнопок MessageBox есть. Совсем недавно был подобный вопрос (Как изменить тип MessageBox?).
В случае с кнопками реализация почти ничем не отличается - нужно поставить hook и отлавливать момент создания окна MessageBox и его внутренних контролов.
На CodeProject есть готовый пример по изменению текстов кнопок MessageBox на C#: Localizing System MessageBox

A: Класс MessageBox является оберткой над вызовом функции Windows API MessageBox и как таковой не позволяет менять названия кнопок. Вам потребуется создать свой собственный диалог и уже в него добавить необходимые кнопки.


text:
Q: How to find the radius of visible MKMapView visible screen area? I want to know the radius of visible area in iphone screen, as I will zoomout and zoom in the visible area will change, so I want to know the radius of that particular area, how can I do it?

A: Its not radius what is required.
You need to use the region parameter from mapView.
Check out apple docs, it is pretty much clear from those.
Go thru this tutorial. It will help you a lot
icode blog mapkit demo
specifically you need to set something like this..
MKCoordinateSpan span = [self coordinateSpanWithMapView:self centerCoordinate:centerCoordinate andZoomLevel:zoomLevel];
MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span);
[self setRegion:region animated:animated];

where span can be calculated as
- (MKCoordinateSpan)coordinateSpanWithMapView:(MKMapView *)mapView
                         centerCoordinate:(CLLocationCoordinate2D)centerCoordinate
                             andZoomLevel:(NSUInteger)zoomLevel
{
// convert center coordiate to pixel space
double centerPixelX = [self longitudeToPixelSpaceX:centerCoordinate.longitude];
double centerPixelY = [self latitudeToPixelSpaceY:centerCoordinate.latitude];

// determine the scale value from the zoom level
NSInteger zoomExponent = 20 - zoomLevel;
double zoomScale = pow(2, zoomExponent);

// scale the map's size in pixel space
CGSize mapSizeInPixels = mapView.bounds.size;
double scaledMapWidth = mapSizeInPixels.width * zoomScale;
double scaledMapHeight = mapSizeInPixels.height * zoomScale;

// figure out the position of the top-left pixel
double topLeftPixelX = centerPixelX - (scaledMapWidth / 2);
double topLeftPixelY = centerPixelY - (scaledMapHeight / 2);

// find delta between left and right longitudes
CLLocationDegrees minLng = [self pixelSpaceXToLongitude:topLeftPixelX];
CLLocationDegrees maxLng = [self pixelSpaceXToLongitude:topLeftPixelX + scaledMapWidth];
CLLocationDegrees longitudeDelta = maxLng - minLng;

// find delta between top and bottom latitudes
CLLocationDegrees minLat = [self pixelSpaceYToLatitude:topLeftPixelY];
CLLocationDegrees maxLat = [self pixelSpaceYToLatitude:topLeftPixelY + scaledMapHeight];
CLLocationDegrees latitudeDelta = -1 * (maxLat - minLat);

// create and return the lat/lng span
MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
return span;
}

Cheers :)

A: I might be misunderstanding the question, but isn't it as simple as:
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    CGFloat latD = mapView.region.span.latitudeDelta;
    CGFloat lngD = mapView.region.span.longitudeDelta;
    NSLog(@"This is the latitude delta of the visible map: %f", latD);
    NSLog(@"This is the longitude delta of the visible map: %f", lngD);
}


text:
Q: How to pass value from Broadcast receiver to Activity in android? I am developing the sample application in android.I want to know how to pass the variable from broadcast receiver to to the Activity class
Please any one help me how to do that in android
Thanks in advance

A: If you are using Intent to start an Activity,  then send values to the intent by using intent.putExtra(key, value) and get the same in your Activity.


text:
Q: Rails onclick => 2 items The following works great for carrying forward data from one page to another:
<%= link_to 'New Work Order', new_workorder_path, :class => 'btn btn-primary', :onclick =>  session[:worequest_id]  %>

How would I add a 2nd field?  The following doesn't work:
          <%= link_to 'New Work Order', new_workorder_path, :class => 'btn btn-primary', :onclick =>  session[:worequest_id] = @worequest.id, [:client_id] = @worequest.client_id %>

Thanks!
UPDATED
This is the code I'm using in the new work order form.  It picks up the worequest_id field from the session
       <% if session[:worequest_id] != nil %>
        <%= f.hidden_field :worequest_id, :value => session[:worequest_id] %>

A: onclick doesn't really work this way – it's an html attribute used to store JavaScript code to be executed when the element is clicked. While you can use it to evaluate Ruby code in the context of a Ruby method call (in this case as part of the options hash given to link_to), it doesn't really make sense to do so.
In your first example, it doesn't actually do anything. If you check your rendered html on the page where that link appears, I expect it evaluates to something like New Work Order. You can, however, store data in session (which is persistent for as long as the user remains logged in), which is why you're seeing this data carrying forward from page to page.
If you're trying to fill in default values for the new workorder, you could pass them as params to the path method:
link_to 'New Work Order',
  new_workorder_path('workorder[worequest_id]' => @worequest.id,
                     'workorder[client_id]'    => @worequest.client_id),
  :class => 'btn btn-primary'

In your workorders#new action, your model instantiation would need to include the params:
def new
  @workorder = Workorder.new(params[:workorder])
end

However, this might not be the best way to proceed. If there will always be a client or worequest associated with a workorder, you might want to look into nested routes.


text:
Q: OAuth2 password-less GAE upload using Google's Maven GAE plugin I know that Google support password-less GAE app uploads using appcfg.{sh,cmd], as described here: https://developers.google.com/appengine/docs/java/tools/uploadinganapp#Passwordless_Login_with_OAuth2
However, I would like to know if I can do the same using Google's official Maven GAE plugin. There is a goal called appengine:update that is used for uploading the local GAE app to the cloud. However, I cannot find information anywhere as to whether this will support OAuth2. Anyone know how I can combine OAuth2 and this Maven plugin?
The reason why is because I am using Jenkins to build my project and I would much rather prefer to upload my application automatically using a Maven goal during the build instead of running a script (more complex than Maven goal) as a post-build step.

A: It seems that it have been improved in recent versions of GAE Maven plugin (no appcfg invocation necessary). It is enough to invoke:
mvn clean appengine:update

if there is no ~/.appcfg_oauth2_tokens_java it will pop your browser, and will ask for credential to Google Account. After successful authentication you are presented with OAuth2 token. Paste it in the terminal window, where you invoked mvn and you're done.

A: It appears that appengine:update automatically supports OAuth2. I just had to run a manual build with appcfg.sh. If that shell script was on your PATH, then the command looks something like this:
appcfg.sh --oauth2 update myapp/war-directory

Once I follow the manual steps to deploy my app and download the OAuth2 token for my user, I can run mvn appengine:udpate. This will detect my OAuth2 token and not require any manual interaction.


text:
Q: Ubuntu/Xfce disable global shortcuts for specific application This question has been asked by someone else on a different stackexchange site, but has not received any answers, hopefully more traffic here will get an answer.
I'm running a java gui application and would like that when this application has focus, it handles all keyboard events, including ones which would normally be intercepted by the window manager (eg alt-left which changes desktop). I do not want to have to change all relevant shortcuts manually.
If there is no configuration way to do this, would a possible solution be to write a low level X windows application in C which could attach itself to a specified window and intercept all keypresses BEFORE the window manager, passing them through to the specified window ?

A: The best solution I have up to now is:

*

*Install very light weight wm like 'twm': (sudo apt-get install twm)

*Kick off a concurrent X session with no wm: xinit /usr/bin/xterm -- :2

*Switch to new X session: control-alt-F8

*Start twm in xterm within new session: twm &

*Run program, enjoy programs shortcuts and be happy, switching back to other X session with control-alt-F7


text:
Q: Organizing fragments for each activity I have two activities, MainActivity and UserActivity. Each activity has 3 swipeable tabs, where each tab has its own fragment.
Each fragment contains the exact same layout but loads content into it differently. The tabs in UserActivity are the exact same tabs that exist in MainActivity.
Should I just have a total of 3 fragments, used for both activities or have 6 fragments where 3 are used for MainActivity and the other 3 are for UserActivity?
If I should only have a total of 3 fragments, how can I differentiate which activity is being used?

A: good question and I think the answer is a little subjective.
But anyway:
If both activities have the same 3 fragments and they have more or less the same functionalities you should only have 3 fragments and re-use them.
Fragments are especially useful because they can easily be reused and that's a perfect use case.
Only if their functionality would be a lot different you should distinguish between them.
How to differentiate ? Well that's pretty easy:

*

*Create a newInstace method for your fragments and pass a int (based on the type):
public class TestFragment {
 public static TestFragment newInstance(int testInt) {
   TestFragment fragment = new TestFragment();

   Bundle args = new Bundle();
   args.putInt("testInt", testInt);
   fragment.setArguments(args);

   return fragment;
 }
...
}

*To create a fragment use: Fragment testFragment = TestFragment.newInstance(testInt);

*Later to get the data passed in the newInstance method just use something like this: getArguments().getInt("testInt", -1);
Based on the int that you passed, you can filter/decide which data you would like to show/use.
EDIT:
If all the 3 fragments inside 1 activity are the same, just use 1 fragment for all the 6 tabs.
Distinguish witch activity is being used, doesn't make really sense... You can access the activity inside your fragment by calling getActivity();
Hope this helps...
Cheers


text:
Q: How to find dates between two dates excluding start and end date using python I have two dates 10-02-2016 and 16-02-2016 in dd-mm-yyyy format, I want the list of dates between those dates without including start and end date.
Expected output:
11-02-2016
12-02-2016
13-02-2016
14-02-2016
15-02-2016

I have the following code snippet:
import datetime

date1 = datetime.datetime.strptime('10-02-2016', '%d-%m-%Y').date()
date2 = datetime.datetime.strptime('16-02-2016', '%d-%m-%Y').date()

delta = date2 - date1
for i in range(delta.days):
    print(date1 + datetime.timedelta(i))

Which gives output as:
10-02-2016
11-02-2016
12-02-2016
13-02-2016
14-02-2016
15-02-2016

Does anyone have any suggestions?
Thanks.

A: import datetime

date1 = datetime.datetime.strptime('10-02-2016', '%d-%m-%Y').date()
date2 = datetime.datetime.strptime('16-02-2016', '%d-%m-%Y').date()

delta = date2 - date1
for i in range(1,delta.days):
    print(date1 + datetime.timedelta(i))

A: Option with list comprehension, slice where you need:
list_of_dates = [ date1 + datetime.timedelta(i) for i in range((date2 - date1).days + 1) ]

for date in list_of_dates[1:-1]:
  print(date)

# 2016-02-11
# 2016-02-12
# 2016-02-13
# 2016-02-14
# 2016-02-15


text:
Q: Android Studio - Too many libraries imported to project eventhough they are not compiled in dependencies I am creating a new Android application that using Firebase. I followed goolge guide to add Firebase SDK to my project.
below are my project gradle:
buildscript {
    repositories {
        jcenter(){
            url "http://jcenter.bintray.com/"
        }
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

And application build.gradle
....
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    /* For Google Play Services */
    //Firebase
    //addd firebase notification - messaging.
    //add firbaes dynamic link:
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.google.android.gms:play-services-safetynet:9.0.2'
    compile 'com.google.android.gms:play-services-auth:9.0.2'
    compile 'com.firebaseui:firebase-ui:0.2.2'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    compile 'com.google.firebase:firebase-invites:9.0.2'
    compile 'com.google.android.gms:play-services:9.0.2'
}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

I checked in External library of my project. There are too many library that I don't not need such as: play-service-location-9.0.2, play-service-maps-9.0.2, play-service--nearby-9.0.2...
enter image description here
Could you explain and help me reduce unused library that I don't added into my project ?

A: Try removing the dependencies you don't need by deleting the dependency from the build.gradle one by one, if you get an error after removing one of your dependencies, add the dependency you just removed back.
As long as you get no errors or problems when removing the dependencies you don't need, everything will be fine.


text:
Q: The stock item was unable to be saved. Please try again. Magento 2.4.0 I installed magento 2.4.0 on my Linux server from godaddy. I'm unable to add the products to it. It is showing the Error is The stock item was unable to be saved. Please try again. Can any one help me from this please

A: I have fixed it. There was an entry missing in cataloginventory_stock
try to run this query
INSERT INTO cataloginventory_stock (stock_id, website_id, stock_name) VALUES ('1', '1', 'default');

A: Please change all indexer as Update by Schedule mode in system-> index management. It's working for me.

A: Go to Magento 2.4.2 installation location:
cd /var/www/html

Flush cache
sudo php bin/magento cache:flush

Chek Indexer Status
php bin/magento indexer:status

Reset Indexer
php bin/magento indexer:reset

Reindex Indexer
php bin/magento indexer:reindex

Chek Indexer Status
php bin/magento indexer:status

Chek indexer Info
php bin/magento indexer:info

Finally Flush Cache
php bin/magento cache:flush

Restart
sudo reboot

Login to admin and check

A: If you are using Elasticsearch instead of Mysql. then please check once that elasticsearch is working or not.
sudo service elasticsearch status    // for checking the Running Status
sudo service elasticsearch start    // for Start
sudo service elasticsearch restart    // for Restart

A: Make sure you have Elastic search service active status ?
service elasticsearch status

A: I've Migrated the magento 2.3.x into 2.4.x. I faced the same issues.
I've resolved this issue the following way.

*

*INSERT INTO cataloginventory_stock (stock_id, website_id, stock_name) VALUES ('1', '1', 'default');

*php bin/magento indexer:reindex

*php bin/magento cache:flush
But still i am facing the same issue, then I did the below steps.

*

*mysqldump --single-transaction -u root -p mydb --triggers | sed -e 's/DEFINER[ ]=[ ][^]*/*/' > mydb_without_definer.sql

*DROP DATABASE mydb;

*create DATABASE mydb;

*mysql -u root -p mydb < mydb_without_definer.sql

*php bin/magento indexer:reindex

*php bin/magento cache:flush

Thank you!
Pilathraj

A: I had the same issue, I just had to execute:
php bin/magento indexer:reindex


text:
Q: iphone app with uinavigationcontroller and uitabbarcontroller I'm new to iphone programming and i'm trying to build an application that has a uinavigationcontroller and the rootviewcontroller is a uiviewcontroller that is basicly a login screen from the login screen the user moves to uitabbarcontroller that has 5 tabs and each tab is a uinavigationcontroller and each navigationcontroller has two button in the navbar one button brings a messages view and the other notifications view each view is a uiviewcontroller.
Now the user can press the message button on every tab and the message view will appear and i want to make sure that if he presses the button on the first tab and then goes to another tab then the message view will disappear and deallocated from memory and when he presses the message button on the new tab then another message view will appear.
I tried the create a single message view in the app delegate and every time that the user presses the message button to call a method from app delegate then in the method i check which tab is pressed and push the view to the navigation controller that belongs to that tab but that doesn't work properly.

A: You can embed your login views inside the AppDelegate and show them as needed. From there you would load your rootController, which should be your tabBar. Then you can load up your navigation controller inside each tab. One for each tab. Your message view can be called from any of the tabs. Just need to make sure you layer your controllers the right way.
AppDel --> TabBar --> NavController --> Individual Views

A: Do you realize that you can replace the root view controller in a window? Your app delegate's -applicationDidFinishLaunching:withOptions: method probably does something like:
window.rootViewController = loginViewController;

When you set the window's rootViewController property, the window will add that view controller's view as a subview of itself.
There's nothing particularly special about -applicationDidFinishLaunching:withOptions: -- it just happens to be the delegate method that's called when the app has finished loading and is ready to get down to business. You can set the window's rootViewController property just as well from other methods, so when your login view controller determines that the user has successfully logged in, it can do something like one of the following:

*

*instantiate the tab bar controller and set the window's rootViewController property itself

*send a message to its delegate (which would probably be the same object as the app delegate) to inform it that login was successful; the delegate could then install the tab bar controller

*broadcast a notification to tell anyone who cares that login was successful, and let someone else install the tab bar controller


text:
Q: Javascript validation using activerecord models validators I have an activerecord model and set of validators to it, But I also have to provide front end validation.
Is there a gem or a smart way to use activerecord validators, for instance in jquery validation plugin, instead of writing it by hand?
Thanks

A: You can check client_side_validations

*

*client_side_validations

*client_side_validations-simple_form
Regards.

A: Jquery has a validation library. Plus there are many others too. Google for Javascript form validation.
Unfortunately, some validations require more access to the business rules of your app in your browser/JS code. So you'll then have to weigh the costs of duplicating business logic in your JS vs the benefit of the immediate feedback to the user.
Just be sure not to skimp on implementing your business rules (and testing them) in your server-side sw first. Remember that clients can never be trusted--even the clients that you write yourself!

A: No need to duplicate the costs.
There are some gems/plugins around that duplicate the Model's validations in the client side.
yes, you'll have to do some client-side customizations still, but it should be very easy.
here's an example of such plugin: http://github.com/grimen/validatious-on-rails


text:
Q: Get Data of not visible items from recyclerview adapter I want a help from you guys can anybody solve this problem i am trying to insert three rows into mysql table but right here only two rows are visible and third on get visible on scrolling down so when i click submit it gets me an error it inserts 2 visible rows on the screen and throws a null pointer expection on the 3 row that is not visible can some one help me to get the data from the view that is not visible i know its recyclerview and it re uses the view i know the mechanism i just want the solution from some that so that the 3 row that is not visible can get added successfully to the database
Here is an image for that :
https://imgur.com/a/rkARs
My recyclerview adapter code:
public class MyAdapterClosing extends RecyclerView.Adapter<MyAdapterClosing.myViewHolder> {

    private Context context;
    private List<DataofClosing> student;

    public MyAdapterClosing(Context context, List<DataofClosing> student){
        this.context = context;
        this.student = student;
    }

    @Override
    public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layoutclosing,parent,false);
        return new myViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(myViewHolder holder, int position) {
        DataofClosing s = student.get(position);
        holder.brand.setText(s.Brandname);

    }

    public void updateList(List<RecyclerviewWholesale> student)
    {
        student = student;
        notifyDataSetChanged();
    }
    public void addItem(int position, DataofClosing stud)
    {
        student.add(position, stud);
        notifyItemInserted(position);
    }

    public void removeItem(int position) {
        student.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, student.size());
    }

    @Override
    public int getItemCount() {
        return student.size();
    }

    @Override
    public int getItemViewType(int position) {

        return position;
    }

    public class myViewHolder extends RecyclerView.ViewHolder{
        TextView brand;
        EditText qts,pts,nip,ml90;

        public myViewHolder(View itemView) {
            super(itemView);

            brand = (TextView) itemView.findViewById(R.id.brand);
            qts = (EditText) itemView.findViewById(R.id.qts);
            pts = (EditText) itemView.findViewById(R.id.pts);
            nip = (EditText) itemView.findViewById(R.id.nip);
            ml90 = (EditText) itemView.findViewById(R.id.ml90);

            String qtss = qts.getText().toString();
            String ptss = pts.getText().toString();
            String nipp = nip.getText().toString();
            String ml900 = ml90.getText().toString();

            DataofClosing dataofClosing = new DataofClosing();
            dataofClosing.qts = qtss;
            dataofClosing.pts = ptss;
            dataofClosing.nip = nipp;
            dataofClosing.ml90 = ml900;

        }
    }

}

Inserting code in the main activity is:
class Insertclosing extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * Creating product
         */
        protected String doInBackground(String... args) {
            for (int i = 0; i < mAdapter.getItemCount(); i++) {
                rcData = data.get(i);
                View view1 = closingService.getChildAt(i);
                EditText nameEditText = (EditText) view1.findViewById(R.id.qts);
                String name = nameEditText.getText().toString();
                EditText ptss = (EditText) view1.findViewById(R.id.pts);
                String pts = ptss.getText().toString();
                EditText nipp = (EditText) view1.findViewById(R.id.nip);
                String nip = nipp.getText().toString();
                EditText ml900 = (EditText) view1.findViewById(R.id.ml90);
                String ml90 = ml900.getText().toString();
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();

                params.add(new BasicNameValuePair("brand", rcData.Brandname));
                params.add(new BasicNameValuePair("quantity", name));
                params.add(new BasicNameValuePair("discount",pts));
                params.add(new BasicNameValuePair("ammount",nip ));

                // getting JSON Object
                // Note that create product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_insert_product_sales,
                        "POST", params);

                // check log cat fro response
                Log.d("Create Response", json.toString());

                // check for success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                    /*runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(ChangeAddress.this, "Order Placed Successfully", Toast.LENGTH_SHORT).show();
                        }
                    });*/
                    } else {
                        runOnUiThread(new Runnable() {
                            public void run() {

                                Toast.makeText(closing.this, "Try Again", Toast.LENGTH_SHORT).show();
                            }
                        });               // failed to create product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {

             Toast.makeText(closing.this, "Closing added Successfully", Toast.LENGTH_SHORT).show();

        }
    }

A: I found a solution for this.
adapter has two methods
onViewAttachedToWindow(RecyclerView.ViewHolder holder){}

and
onViewDetachedFromWindow(RecyclerView.ViewHolder holder){}

Cretae a HashMap in your adapter
public HashMap<Integer, RecyclerView.ViewHolder> holderHashMap = new HashMap<>();

and add holder into it in onDetach and remove the same onAttach. Like this.
 @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        holderHashMap.put(holder.getAdapterPosition(),holder);
        super.onViewDetachedFromWindow(holder);
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        holderHashMap.remove(holder.getAdapterPosition());
        super.onViewAttachedToWindow(holder);

    }

to access all viewHolders including the invisible ones use this in you activity.
for(int i =0; i<recyclerView.getItemCount();i++){
RecyclerView.ViewHolder holder = surveyQuestionList.findViewHolderForAdapterPosition(i);

            if(holder == null){
                holder = adapter.holderHashMap.get(i);
            }
}

This is the best solution so far I have come up with.
Let me know if it works for you.


text:
Q: Group actions, permutation representations and currying I have been studying group actions for about a month, so I am at a basic stage and forgive me if this turns out to be a stupid question. It is about the two equivalent definitions of group action and permutation representation. In the 'action' definition of a left group action, we use a map $ \alpha: G \times X \rightarrow X $, which I understand can be curried to give a chain of two functions $ \phi : G \rightarrow (X \rightarrow X) $, which leads to the alternative definition of the group action as a permutation representation $ \phi : G \rightarrow Sym(X)$.
But how does this work for the right group action $ \alpha: X \times G \rightarrow X $, as following the same currying technique would give a chain of functions $ \phi: X \rightarrow (G \rightarrow X)$ and not a permutation representation?
In addition, what are the main reasons for wanting two equivalent definitions as an action and permutation representation? It seems to me that the definition as a group representation is quite natural, whereas the action definition is axiomatic and seems to come from nowhere. Many thanks.

A: Those are not precisle equivalent definitions: any group action on a set determines a homomorphism from the group to the group of symmetries (permutations) of the set, and the other way around is also true.
Thus, if $\,\phi: G\times X\to X\,$ is a group action on a set $\,X\,$ (and it really doesn't matter whether this is a right or left action), then we get a homomorphism
$$\Phi:G\to\operatorname{Sym}_X\,\,\,,\Phi(g)(x):=\phi(g,x)$$
and this means that for any $\,g\in G\,$, the permutation $\,\Phi(g)\,$ is such that it maps and element $\,x\in X\,$ to the element $\,\phi(g,x)\,$ in $\,X\,$.
It's easy to check the above is really a groups homomorphism, and also that we can do the same thing the other way around: begin with a homom. $\,G\to\operatorname{Sym}_X\,$ and get an action $\,G\times X\to X\,$ uniquely determined by the homomorphism.

A: Your observation is correct, indeed left group actions are exactly those functions corresponding to group homomorphisms (seen as functions from $G$ to the endofunction monoid $\text{End}(X)=\mathbf{Set}(X,X)$) via the following adjunction.
$$\mathbf{Set}(G \times X, X) \cong \mathbf{Set}(G,\text{End}(X))$$
This correspondence extend to right group actions, but the object which correspond to these actions are the antihomomorphisms of groups.
In general an antihomomorphism between the two groups $G$ and $H$ is just a function $f \colon G \to H$ such that for each pair $x,y \in G$ the equality
$$f(xy)=f(y)f(x)$$
holds.
Another way to state this is to see an antihomomorphism as a group homomorphism from the opposite group of the $G$, namely $G^\text{op}$ to $\text{Sym}(X)$.
$G^\text{op}$ is the group having as underlining set $G$ (so $G^\text{op}=G$ as set) having as multiplication the operation $\cdot \circ \sigma \colon G^\text{op} \times G^\text{op} \to G^\text{op}$ (where $\cdot \colon G \times G \to G$ is the group multiplication of $G$ and $\sigma \colon G \times G \to G \times G$ is the bijection sending the pair $(x,y)$ in the pair $(y,x)$, it's easy to prove that this is a group operation).
For every $r \colon X \times G \to X$ right action of $G$ on $X$ we can get the map $r \circ \sigma \colon G^\text{op} \times X = G  \times X \to X$ which is a left action of the group $G^\text{op}$ on the set $X$. So by what you told in your answer this action via currying correspond to homomorphism $G^\text{op} \to \text{Sym}(X)$ which are antihomorphisms from $G$ to $\text{Sym}(X)$.
Hope the answer was sufficiently clear and helpful.


text:
Q: Multiple aggregate functions in Java 8 Stream API I have a class defined like
public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}

I would like to perform the following SQL statement using Java 8 Stream API.
SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate

I tried :
Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

A: To do it without a custom Collector (not streaming again on the result), you could do it like this. It's a bit dirty, since it is first collecting to Map<String, List<TimePeriodCalc>> and then streaming that list and get the average double.
Since you need two averages, they are collected to a Holder or a Pair, in this case I'm using AbstractMap.SimpleEntry
  Map<String, SimpleEntry<Double, Double>> map = Stream.of(new TimePeriodCalc(12d, 10d, "A"), new TimePeriodCalc(2d, 16d, "A"))
            .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
                    Collectors.collectingAndThen(Collectors.toList(), list -> {
                        double occupancy = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getOccupancy));
                        double efficiency = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getEfficiency));
                        return new AbstractMap.SimpleEntry<>(occupancy, efficiency);
                    })));

    System.out.println(map);

A: Here's a way with a custom collector. It only needs one pass, but it's not very easy, especially because of generics...
If you have this method:
@SuppressWarnings("unchecked")
@SafeVarargs
static <T, A, C extends Collector<T, A, Double>> Collector<T, ?, List<Double>>
averagingManyDoubles(ToDoubleFunction<? super T>... extractors) {

    List<C> collectors = Arrays.stream(extractors)
        .map(extractor -> (C) Collectors.averagingDouble(extractor))
        .collect(Collectors.toList());

    class Acc {
        List<A> averages = collectors.stream()
            .map(c -> c.supplier().get())
            .collect(Collectors.toList());

        void add(T elem) {
            IntStream.range(0, extractors.length).forEach(i ->
                collectors.get(i).accumulator().accept(averages.get(i), elem));
        }

        Acc merge(Acc another) {
            IntStream.range(0, extractors.length).forEach(i ->
                averages.set(i, collectors.get(i).combiner()
                    .apply(averages.get(i), another.averages.get(i))));
            return this;
        }

        List<Double> finish() {
            return IntStream.range(0, extractors.length)
                .mapToObj(i -> collectors.get(i).finisher().apply(averages.get(i)))
                .collect(Collectors.toList());
        }
    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finish);
}

This receives an array of functions that will extract double values from each element of the stream. These extractors are converted to Collectors.averagingDouble collectors and then the local Acc class is created with the mutable structures that are used to accumulate the averages for each collector. Then, the accumulator function forwards to each accumulator, and so with the combiner and finisher functions.
Usage is as follows:
Map<String, List<Double>> averages = list.stream()
    .collect(Collectors.groupingBy(
        TimePeriodCalc::getAtDate,
        averagingManyDoubles(
            TimePeriodCalc::getOccupancy,
            TimePeriodCalc::getEfficiency)));

A: Assuming that your TimePeriodCalc class has all the necessary getters, this should get you the list you want:
List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(Collectors.toList(), TimePeriodCalc::avgTimePeriodCalc)))
    .values()
);

Where TimePeriodCalc.avgTimePeriodCalc is this method in the TimePeriodCalc class:
public static TimePeriodCalc avgTimePeriodCalc(List<TimePeriodCalc> list){
    return new TimePeriodCalc(
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
            list.get(0).getAtDate()
            );
}

The above can be combined into this monstrosity:
List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(
            Collectors.toList(), a -> {
                return new TimePeriodCalc(
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
                        a.get(0).getAtDate()
                        );
            }
        )))
    .values());

With input:
List<TimePeriodCalc> list = new ArrayList<>();
list.add(new TimePeriodCalc(10,10,"a"));
list.add(new TimePeriodCalc(10,10,"b"));
list.add(new TimePeriodCalc(10,10,"c"));
list.add(new TimePeriodCalc(5,5,"a"));
list.add(new TimePeriodCalc(0,0,"b"));

This would give:
TimePeriodCalc [occupancy=7.5, efficiency=7.5, atDate=a]
TimePeriodCalc [occupancy=5.0, efficiency=5.0, atDate=b]
TimePeriodCalc [occupancy=10.0, efficiency=10.0, atDate=c]

A: You can chain multiple attributes like this:
Collection<TimePeriodCalc> collector = result.stream().collect(Collectors.groupingBy(p -> p.getAtDate(), Collectors.averagingInt(p -> p.getOccupancy())));

If you want more, you get the idea.


text:
Q: Is there a way to use Python to open specific webpages after typing in input? I'm trying to find a way to write a script that accepts input from the user, After which, it will open webpages. The code looks like this so far:
jurisdiction = input("Enter jurisdiction:")
if jurisdiction = 'UK':
    import webbrowser
    webbrowser.open('https://www.legislation.gov.uk/new')
    webbrowser.open('https://eur-lex.europa.eu/oj/direct-access.html')
elif jurisdiction = Australia:
    import webbrowswer
    webbrowser.open('https://www.legislation.gov.au/WhatsNew')
else:
    print("Re-enter jurisdiction")

This leads to a syntax error at line 3:
File "UK.py", line 3
if jurisdiction = UK
                ^
SyntaxError: invalid syntax**

I would like to know if there is anything in the code that I have missed or should not have had there? Also, is there an alternative way to do what I am trying to achieve here?

A: I recommend reading up on Python String Comparison. Easy fix, but you would benefit from a basic understanding of how string comparison does and does not work in Python.
Both UK and Australia need to be Strings as well...
And don't import webbroswer package in the body of your code. You only need to do it once.
import webbrowser

jurisdiction = input("Enter jurisdiction:")
if jurisdiction == 'UK':
    webbrowser.open('https://www.legislation.gov.uk/new')
    webbrowser.open('https://eur-lex.europa.eu/oj/direct-access.html')
elif jurisdiction == 'Australia':
    webbrowser.open('https://www.legislation.gov.au/WhatsNew')
else:
    print("Re-enter jurisdiction")

A: A cleaner approach:
import webbrowser

mapping = {'UK': ['https://www.legislation.gov.uk/new', 'https://eur-lex.europa.eu/oj/direct-access.html'],
           'Australia': ['https://www.legislation.gov.au/WhatsNew']}

jurisdiction = input("Enter jurisdiction:")
urls = mapping.get(jurisdiction)
if urls is not None:
    for url in urls:
        webbrowser.open(url)
else:
    print("Re-enter jurisdiction")


text:
Q: why the output error, I do not understand create table qbey (
idqbey int primary key auto_increment,
bey int,
users int,
foreign key (users) references persons(idusers) on delete cascade on update cascade,
foreign key (bey) references bey(idbey) on delete cascade on update cascade,
);

Program Error:

error code: 1005 can't create table '.\soft_tj\qbey.frm' (errno:150)

A: The documentation explains this error, though it's not too easy to find: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

If you re-create a table that was dropped, it must have a definition
  that conforms to the foreign key constraints referencing it. It must
  have the right column names and types, and it must have indexes on the
  referenced keys, as stated earlier. If these are not satisfied, MySQL
  returns error number 1005 and refers to error 150 in the error
  message.


text: Q: Brackets виснет Старый Brackets (не помню какой версии) предложил залить новую версию, установил. При запуске ПО меню доступно, но не реагирует, даже "О программе" не работает. Снес, переустановил до 1.7- все равно не работает. Решил установить Eclipse (так как там тоже можно делать панели для Фотошоп), инсталляция стала ругаться что не поддерживает Java 1.7, установил 8 Java, перегрузил. Eclipse по-прежнему ругается и не устанавливается, Brackets 1.7 по-прежнему не работает, даже закрывать его приходится через Менеджер задач. При открытом Brackets попробовал удалить, возникло предупреждение что будут закрыты Brackets и Node.js:Server-Side Java Script. Из чего сделал предположение что какие-то проблемы с сервером. Скачал и установил NodeJS, установил Brackets 1.10 - результат один и тот же. Версия Java 8, но отчего Eclipse считает что 7 ? Может тут что-то порыть ?


text:
Q: Insert fonts in Latex I found this command that allows you to insert an Adobe font like Helvetica
\renewcommand{\stitlefont}{\fontfamily{phv}\fontsize{14pt}{14pt}\selectfont}
I have more questions:

*

*phv is an abbreviation? Are there others?

*Similarly I can insert font ttf? Just change the name between braces, like {berasans}?

Thanks!


text:
Q: Error using sp_trace_create with parameters I'm running the following SQL on SQL Server 2000:
exec sp_trace_create @options = 2,
         @tracefile = N'h:\\trace.trc',
         @filecount = 2

and am getting the following error and can't understand why:

Procedure expects parameter '@tracefile' of type 'nvarchar(128)'

If I pass all of the parameters in like so:
declare @id int
exec sp_trace_create @id output,
         @options = 2,
         @tracefile = N'h:\\trace.trc',
         @filecount = 2,
         @maxfilesize = 5,
         @stoptime = '2013-8-15'

I get the error:

Procedure or function sp_trace_create has too many arguments specified.

A: Martin Smith has answered https://dba.stackexchange.com/a/24728/8783
This will work :
DECLARE @new_trace_id INT;

EXECUTE master.dbo.sp_trace_create
  @someinteger = @new_trace_id OUTPUT,
  @someinteger = 0,
  @someinteger = N'C:\trace\TestTrace.trc';

  -- get trace status
  SELECT * FROM ::fn_trace_getinfo(NULL)
  -- stop trace
  EXEC sp_trace_setstatus @traceid = 1 -- CHANGE THIS AS PER YOUR TRACE id
                    , @status = 0
  go
  -- delete trace
  EXEC sp_trace_setstatus @traceid = 1  -- CHANGE THIS AS PER YOUR TRACE id
                    , @status = 2

A: I'm not sure why but it appears that sp_trace_create requires all parameters be passed.  This includes the @traceid parameter.  The error is definitely misleading.  Add the @traceid parameter and the next error you get will be for @maxfilesize.


text:
Q: Energy current in a quantum chain I have seen in (e.g. this paper) the definition of the energy current in a chain with $H = \sum_{j=1}^L h_j$
where $H_j$ has support on the $k$ sites $j,j+1,j+2,...,j+(k-1)$ as
$$J_j - J_{j+1} = i[H, h_j].$$
This definition is motivated as a discrete version of the continuity equation, namely $J_j - J_{j+1} = \frac{dh_j}{dt}.$

However, I have only found explicit forms for $J_j$ in terms of the set of $\{h_i\}$ in the case of $k=2$, for which
$$J_j - J_{j+1} = i([h_{j-1}, h_j]+[h_{j+1}, h_j]) = i[h_{j-1}, h_j]-i[h_{j}, h_{j+1}]$$
which has the immediate solution $J_j = i[h_{j-1}, h_j]$.

What is the explicit solution of $J_j$ for $k>2$?

A: After a bit of staring at the problem and adding and subtracting quantities in pairs, I've come up with the correct general form for $H_j$ with support on $j,j+1, ..., j+k-1$.
$$J_j = i\sum_{q=1}^{k-1} \sum_{r=0}^{q-1} [h_{j-k+q}, h_{j+r}]$$
To see this, notice that separating out the $r=0$ terms in $J_j$  gets
$$\begin{align} J_j &= i\sum_{q=1}^{k-1} \sum_{r=0}^{q-1} [h_{j-k+q}, h_{j+r}]\\ &= i\sum_{q=1}^{k-1}[h_{j-k+q}, h_j] + i\sum_{q=2}^{k-1} \sum_{r=1}^{q-1} [h_{j-k+q}, h_{j+r}] \\& = i\sum_{q=-(k-1)}^{-1}[h_{j+q}, h_j] + i\sum_{q=2}^{k-1} \sum_{r=1}^{q-1} [h_{j-k+q}, h_{j+r}]  \end{align} $$
while separating out the $q=k-1$ terms in $J_{j+1}$ gives
$$\begin{align} J_{j+1} &= i\sum_{q=1}^{k-1} \sum_{r=0}^{q-1} [h_{j+1-k+q}, h_{j+1+r}]\\ &= i\sum_{r=0}^{k-2}[h_j, h_{j+1+r}] + i\sum_{q=1}^{k-2} \sum_{r=0}^{q-1} [h_{j+1-k+q}, h_{j+1+r}] \\&= -i\sum_{r=1}^{k-1}[h_{j+r}, h_j] + i\sum_{q=1}^{k-2} \sum_{r=1}^{(q+1)-1} [h_{j-k+(q+1)}, h_{j+r}] \\&= -i\sum_{r=1}^{k-1}[h_{j+r}, h_j] + i\sum_{q=2}^{k-1} \sum_{r=1}^{q-1} [h_{j-k+q}, h_{j+r}] \end{align}$$
Thus, after all this index manipulation, we find at last
$$J_j - J_{j+1} = i\sum_{q=-(k-1)}^{k-1} [h_{j+q}, h_j] = i[H,h_j]$$
which confirms the correctness of the form of $J_j$.


text:
Q: Why does this Javascript match() function Crash My Browser? WHAT I DO:

*

*Make sure Firebug is working.

*Put a break point in the isWrappedInParens() function.

*Navigate to my webapp.

*Trigger a call to isWrappedInParens().

*Step through isWrappedInParens(). Everything goes fine, but it does not proceed past the line of code indicated as the "CRASH POINT".

*I also tried it without Firebug running or having a break point, but it still freezes.

WHAT I NOTICE:

*

*In most cases, isWrappedInParens() works fine.

*When it does not work, Firefox freezes. I can still minimize/expand/close the window, though.

*I also noticed that when the test string is a bit shorter (less parentheses), firefox hangs but eventually finishes (~30 seconds) correctly.

EXAMPLE STRING THAT CRASHES FIREFOX
// Note that this is not wrapped in parentheses,
// since it is two separate sets of nested parentheses
var test = "(the OR (and) OR (and) OR (and)) AND ((to) OR (to) OR (to))";

BACKGROUND

*

*Browser: Firefox 3.6.18

*The webapp is a jetty application.

CODE
isWrappedInParens = function(str){
    if(_.isNull(str)) {
        return false;
    }
    str = str.trim();

    var pattern = /^[(](([(][^()]+[)]|[^()]+)|[(]([(][^()]+[)]|[^()]+)+[)])+[)]$/;

    var matchesPattern;
    try{
        matchesPattern = str.match(pattern) || null; //CRASH POINT!!!!!!!!!!!
    }catch(err){
        return false; //Note that no error is ever caught from freezing
    }

    var isWrapped = !_.isUndefined(matchesPattern) && !_.isNull(matchesPattern);
    return isWrapped;
}

WHERE THE REGEX CAME FROM:
// Atoms, building blocks for the expressions
var parenAtom = "[(][^()]+[)]";
var nonParenAtom = "[^()]+";

// Expressions, building blocks for the final regular expression
var baseCase = "(" + parenAtom + "|" + nonParenAtom + ")";
var nestedCase = "[(]_base_[)]"
    .replace("_base_", baseCase);

// Regular Expression
var wholeCase = "^[(](_base_|_nested_)+[)]$"
    .replace("_base_", baseCase)
    .replace("_nested_", nestedCase);
var pattern = new RegExp(wholeCase, "");

A: From my comment:

Looking through the Firefox bug database, there have been many regular expression bugs found and categorized loosely as "exponential behavior" bugs. Most of them have been fixed in the newer versions of the browser.

In this bug there are a couple of comments from Brendan Eich about the issue, and he lists several other bugs (some pretty old).  Another comment there alludes to an "overhaul in regular expression" in Firefox 4, suggesting that many changes occurred as far back as that.


text:
Q: Calling non-empty constructor when defining a member object within a header file I feel like this is a mere syntactical question, but I can't find a unique/succinct way to describe it so Google isn't helping.
Here is a code snippet to see what I am talking about. The part that is preventing compilation is pointed out in a comment.
Deck.h:
#include <random>
#include <iostream>

class Deck{
    int top;
    int cards[52];

    public:
     Deck();
     void shuffle();

    private:
        // the "(0,51)" on the following line is a syntax error
        // without it, compilation is fine
        std::uniform_int_distribution<int> distribution(0,51);
        std::shuffle_order_engine<std::default_random_engine, 52> engine;
};

Deck.cpp:
#include "Deck.h"
#include <random>
#include <algorithm>

Deck::Deck(){}

void Deck::shuffle(){
    top = 0;
    int oldCards[52];
    std::copy_n(cards, 52, oldCards);
    for(int i = 0; i < 52; i++){
        int random = distribution(engine);
        std::cout << "random= " << random << std::endl;
        cards[i] = oldCards[random];
    }
}

I need to have the uniform_int_distribution instantiated with the range 0 to 51 to shuffle the deck. I could declare it as a pointer and allocate it dynamically, but this seems like it shouldn't be necessary.
Coming from experience in C, I am trying to learn to write good, idiomatic C++ code, so anything else you can point out is appreciated. Of course, the actual working of the shuffling will be debugged once I can get compilation.
Thank you for any answers.

A: You can use curly braces, or copy initialization syntax.
Alternatively you can initialize that member in each constructor's member init list.
For C++03 the latter is the only possibility.

Curly braces:
std::uniform_int_distribution<int> distribution{ 0, 51 };

Copy initialization syntax (only available if the type is copyable or movable):
std::uniform_int_distribution<int> distribution =
    std::uniform_int_distribution<int>( 0, 51 );

Initialization in constructor member init list:
Deck::Deck()
    : distribution( 0, 51 )
{}

A: C++11 supports both parenthesis and braces when initializing members in a class declaration, eg:
class Deck
{
    ...
    private:
        std::uniform_int_distribution<int> distribution(0,51);
        ...
};

class Deck
{
    ...
    private:
        std::uniform_int_distribution<int> distribution{0,51};
        ...
};

For non-C++11 compilers, you have to use the initializer list of the containing class's constructor to provide values to class member constructors (a C++11 compiler silently translates the above code into this logic behind the scenes), eg:
class Deck
{
    ...
    private:
        std::uniform_int_distribution<int> distribution; // <-- DO NOT try to invoke the constructor here!
        ...
};

Deck::Deck()
  : distribution(0,51) <-- invoke the constructor here instead!
{
}


text:
Q: Change font-color of TextField inside MovieClip I've a problem to change the font-color of a TextField after it has been added as a child to a MovieClip.
My code:
var btn:MovieClip = new MovieClip();
// other code for button

var tf:TextFormat = new TextFormat();
tf.size = 12;
tf.bold = true;
tf.font = "Arial"
tf.color = 0x000000;

var capt:TextField = new TextField();
capt.defaultTextFormat = tf;
capt.width = 200;
capt.height = 50;
capt.text = "Test";
capt.y = 20;
capt.x = 20;
capt.border = false;
capt.selectable = false;

btn.addChild(capt);

// .....

How can I Change the font-color after the last line?

A: It sounds like you're looking for TextField.setTextFormat(). You can either adjust your original TextFormat or just make a whole new one.
tf.color = 0xFF0000;
capt.setTextFormat(tf);

A: Assuming the TextField falls out of scope after that last line (you don't show enough to know if it does or not), you'll need to loop through the button to get the TextField and do it from there.
var i:uint;
var l:uint = btn.numChildren; //numChildren and length are 'heavy' getters, never use them as restrictors in a loop
for ( i = 0; i < l; i++ ) {
    var cur:DisplayObject = btn.getChildAt( i );
    if ( cur is TextField ) {
        ( cur as TextField ).setTextFormat( /*set new TextFormat in here*/);
        break;
    }
}

That assumes there is only the single TextField, of course. If there are multiple, I would extend MovieClip and add a public property for the value you want to change.

A: You can also just use the textColor property of a textfield:
capt.textColor = 0xFF0000;


text:
Q: How to sort complex numbers by real part follow by imaginary part I want to sort a list (or in julia speak an one dimensional array) of complex numbers, by real part then by imaginary part of the complex number. I tried using anonymous function for the lt but it does not work.
julia> b=[3 + 1im,1 + 2im,1 + 1im,5 + 6im]
4-element Array{Complex{Int64},1}:
 3 + 1im
 1 + 2im
 1 + 1im
 5 + 6im

julia> sort(b,lt = x,y -> if(real(x)==real(y)) imag(x)<imag(y) else real(x)<real(y) end)
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at none:0

I want the following results
 1 + 1im
 1 + 2im
 3 + 1im
 5 + 6im

A: So close!
julia> sort(b, lt = (x,y) -> real(x)==real(y) ? imag(x)<imag(y) : real(x)<real(y))
4-element Array{Complex{Int64},1}:
 1+1im
 1+2im
 3+1im
 5+6im

A: Tuples are sorted in lexicographic order (the 1st element; then the second one, and so on).
You could just do:
b = [3 + 1im, 1 + 2im, 1 + 1im, 5 + 6im]
sort(b, lt = (x, y) -> (real(x), imag(x)) < (real(y), imag(y)))

edit: The comment above, using by= , is much cleaner.


text:
Q: NodeJS + MySQL - Коверкает число В базе данных есть некий SteamID:

76561198160247832

Он лежит в ячейке (steamid) в базе данных.
Я случайным образом выбираю одну строку с каким-либо steamid (в данном случае строка содержит предоставленный выше стимайди), и вывожу его в консоль:
con.query("SELECT * FROM players WHERE id=" + mysql.escape(id), function (err, result20, fields) {
log("Победитель: " + result20[0].steamid);

Мне возвращает:

Победитель: 76561198160247840

В чём может быть проблема?
В таблице steamid имеет тип bigint (255) и заполнен верно.

A:
Из 64 бит, отведённых на число, сами цифры числа занимают до 52 бит, остальные 11 бит хранят позицию десятичной точки и один бит – знак. Так что если 52 бит не хватает на цифры, то при записи пропадут младшие разряды.
Интерпретатор не выдаст ошибку, но в результате получится «не совсем то число», что мы и видим в примере выше. Как говорится: «как смог, так записал».

источник
Проще говоря, если в числе больше 16 знаков, будет искажение:

console.log(76561198160247832)
console.log(765611981602478328)

A: Как говорилось в ответе выше - для записи таких длинных чисел тупо "не хватает памяти",
но это можно исправить двумя строками:
При CreateConnection указать параметры:
supportBigNumbers: true, bigNumberStrings: true.


text:
Q: how to change activeIds of ngb Accordion based on the button we click in angular I'm implementing the ngbAccordion in a modal in another component. When I click on a button1 ,my modal with the accordian should popup, with "Acc1" tab open , similarly with button 2.
Could anyone help me. please find my code.
https://stackblitz.com/edit/github-6r9hfp-k7upwx?file=src%2Fapp%2FaccordionInModal%2Facc-in-modal.component.html

A: Answer updated: Just used @Input directive for panelId .  Please find it here:
https://stackblitz.com/edit/github-6r9hfp-k7upwx?file=src%2Fapp%2Fapp.component.ts


text:
Q: OleDB Select Statement I have a search button in my program. What I want is every time I search I will type the lastname and when the lastname is equivalent to any lastname in the database, the firstname and the lastname of the person will be displayed in a listbox and whenever I click on the result in the listbox, the person's details will be displayed in the textboxes. The problem is when there are persons with same surname, their names are listed uniquely but when I click on the name, same details appear in the textboxes.
Please help.
Here's my code:
    connection.Open();
    OleDbCommand select = new OleDbCommand();
    select.Connection = connection;
    select.CommandText = "Select * From Accounts Where Lastname  = '" + searchtb.Text + "'";
    OleDbDataReader reader = select.ExecuteReader();
    while (reader.Read())
    {
        listBox1.Items.Add(reader[1].ToString() + "," + reader[2].ToString());
    }
    connection.Close();

A: You dont have any error in this code, Your error can possibly be on your listbox_events.
Show your codes for the listbox part.

A:  cFat_items2 = new OleDbDataAdapter("
      SELECT COUNT(Fat_Items.i_num) AS Count_i_num, Fat_Items.i_num, g.i_num
      FROM Fat_Items INNER JOIN Fat_Items AS g ON Fat_Items.fat_nr = g.fat_nr
      WHERE Fat_Items.i_num = '" + this.kLDataSet.Fat_Items.Rows[i].ItemArray[0].ToString() + "'
      AND g.i_num = '" + this.kLDataSet.Fat_Items.Rows[j].ItemArray[0].ToString() + "'
      GROUP BY Fat_Items.i_num, g.i_num HAVING COUNT(Fat_Items.i_num)>='" + Support + "'", con);

 cFat_items2.Fill(dFat_items2);


text:
Q: Prove that: $8^{a}+8^{b}+8^{c}\geqslant 2^{a}+2^{b}+2^{c}$ $a,b,c \in \mathbb{R}$ and $a+b+c=0$.
Prove that: $8^{a}+8^{b}+8^{c}\geqslant 2^{a}+2^{b}+2^{c}$
I think that $2^{a}.2^{b}.2^{c}=1$, but i don't know what to do next

A: Hint: $f(x) = x^3 - x$, $g(x) = \dfrac{x^3}{9} - x$ $\text{ increases}$, $x \geq 3$ and Jensen's inequality !

A: As it was said, you can take $x=2^a$, $y=2^b$ and $z=2^c$ to obtain:
$$
x^3+y^3+z^3\ge x+y+z
$$
With $x,y,z>0$ and $xyz=1$. It is equivalent to:
$$
x^2(x-1)+y^2(y-1)+z^2(z-1)\ge 0 \iff \frac{x^2(x-1)+y^2(y-1)+z^2(z-1)}{3}\ge 0
$$
Since $x^2$ and $x-1$ ar equally ordered, we might apply Chebychevs inequality to obtain:
$$
\frac{x^2(x-1)+y^2(y-1)+z^2(z-1)}{3}\ge \frac{x^2+y^2+z^2}{3}\frac{(x-1)+(y-1)+(z-1)}{3}
$$
And to show that the two factors are greater than zero isn't difficult. (AM-GM)

A: Let $x=2^a,y=2^b,z=2^c$. Then $x,y,z>0$ and
$$ xyz=2^{a+b+c}=1.$$
By Holder's inequality
$$(x^3+y^3+z^3)(1+1+1)(1+1+1)\ge (x+y+z)^3.$$
Therefore,
$$x^3+y^3+z^3\ge\dfrac{(x+y+z)^3}{9}\ge (x+y+z)$$
because use AM-GM inequality
$$(x+y+z)^2\ge (3\sqrt[3]{xyz})^2=9.$$

A: We have
$$
8^a+1+1\geq3\sqrt[3]{8^a}=3\times 2^a,
$$
$$
8^b+1+1\geq3\sqrt[3]{8^b}=3\times 2^b,
$$
$$
8^c+1+1\geq3\sqrt[3]{8^c}=3\times 2^c,
$$
$$
2^a+2^b+2^c\geq 3\sqrt[3]{2^{a+b+c}}=3.
$$
It follows that
\begin{eqnarray}
8^a+8^b+8^c&\geq&3(2^a+2^b+2^c)-6\\
&=&(2^a+2^b+2^c)+2(2^a+2^b+2^c-3)\\
&\geq&2^a+2^b+2^c.
\end{eqnarray}