text: Q: Unit testing InfoPath form C# code behind Does anyone know a decent way of unit testing the InfoPath FormCode of browser-enabled InfoPath Form Templates that submit data via web services? I can call the public methods from an external test project and mock some of the classes in a way of passing the data sources into the methods, but I cant seem to isolate them easily. The FormCode class cannot be inherited from and it inherits from XmlFormXostItem class which has the MainDataSource, NamespaceManager, etc properties without a setter, so I can`t easily implement my own and have the FormCode instance use them in my tests. Is there a way to do this? Thanks.


text:
Q: How to print currently used random_state in MLPClassifier from sklearn I use MLPClassifier (sklearn library) for neural network modeling in Python. I don't specified randome_state, but I want to see what random seed is used every time I run my model.
My model's example is below. For now random seed is fixed. I want to remove it from model but I'd like to see what seed was used when I print results.
model = MLPClassifier(hidden_layer_sizes=(50,), max_iter = 600, activation='tanh',
                  learning_rate = 'adaptive',
                  random_state = 40
                 )

Is it possible to print currently used random_state?
The only thing I could find is how to add random seed inside model - I know how to do it and that's not the issue.
I'm curious what random seed would be better for my model and data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magnific popup is not functioning when I add hover - text on image I want to add a text when the user hover the mouse on my image gallery and zoom the when they clicked it. It already zooming in but when I add a class and text between the image class the magnific popup is not working. It seems like the text is blocking the image to be selected. I don't know how and what to change. Thanks!
Image Gallery Code:

$(".container").magnificPopup({
  delegate: 'a',
  type: 'image',
  gallery:{
    enabled: true
  }
});
.box{
    width: 270px;
    height: 250px;
    position: relative;
    background-color: rgba(255,102,104,1.00);
    margin: 10px auto;
    cursor: pointer;
}
.box img{
    max-width: 100%;
    height: 100%;
    object-fit: cover;
}
.box:hover::after{
    transform: scale(1, 1.05);
}
.con-text{
    position: absolute;
    color: white;
    bottom: 0;
    width: 270px;
    height: 250px;
    padding: 75px 25px;
    display: none;
    text-align: center;
}
.box:hover .con-text{
    display: block;
}

  // Magnific popup doesn't work anymore when I add this div

Title


text:
Q: Java process in not closing after script execution I'm using robotframework 3.0. installed Sikuli library from source using maven. When I run a script SikuliLibrary.jar is started, even after script execution is completed the java process is still running. Next time when I run the script again a new process is created. I'm facing this issue in both Linux(RHEL) and Windows.
I will be running multiple scripts repeatedly and because of this issue RAM is getting filled with java processes.
Here are the java processes from linux server
root 21509 1 0 08:59 pts/26 00:00:16 java -jar /usr/jython/Lib/site-packages/SikuliLibrary/lib/SikuliLibrary.jar 55994 /tmp/xtttrrr
root 21769 1 0 11:27 pts/32 00:00:17 java -jar /usr/jython/Lib/site-packages/SikuliLibrary/lib/SikuliLibrary.jar 59637 /tmp/xtttrrr


text:
Q: mg_send_response_line() in mongoose not working I am trying to develop a server application using mongoose C library. In the initial stage of the my try, I am stuck at sending a response for an HTTP request.  I am trying to send a simple response of status 200 using following line of code:
 mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
 printf("Response sent...\n");

But the response is not received to the client(Postman or web-browser).
There is no error, and even the printf line of Response sent is printed.
As against to this, following lines are getting executed successfully:
 mg_http_send_error(nc,404, "Fatal Error!"); // I get this error at client side.

The basic simplest_web_server also works fine. Why is my single line of code sending response failing. I am not able to understand/ debug this.
Regards,
Neeraj.

A: The issue is that there is no content length or transfer encoding specified for the HTTP response and the server does not close the connection so the client hangs waiting for the response.
If you look through the source code, you will see that in mg_http_send_error(), the MG_F_SEND_AND_CLOSE flag is set but it is not set within mg_send_response_line() (though, like you, I assumed that this would be handled by the function).
To fix the issue in your context,
mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
printf("Response sent...\n");
nc->flag |= MG_F_SEND_AND_CLOSE;


text:
Q: Esconder DIV somente no IE8 estou com uma pequena duvida, como faço para esconder uma div (.laser) somente no IE8?
Preferencialmente gostaria de usa somente CSS ou também JS

A: Crie um arquivo .css chamado, por exemplo, ie.css. Faça a chamada dele no cabeçalho da sua página/site/aplicação da seguinte maneira:
<!--[if lte IE 8]>
    <link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

Dentro dele, basta esconder a div como você normalmente faria:
.laser{
    display: none;
}

Todas as regras dentro deste arquivo serão aplicadas apenas nas versões do IE 8 ou anteriores.
Se você quiser atingir outras versões do IE ou uma gama delas, eis uma excelente referência.


text:
Q: Decimal type in php Does PHP have Decimal(±1.0 × 10−28 to ±7.9 × 1028) data type?

A: The BC Math extension implements arbitrary-precision  decimal math:
$a = '0.1';
$b = '0.2';
echo bcadd($a, $b);     // prints 0.3

(From The Floating-Point Guide)


text:
Q: DATE_SUB and DATE_ADD in H2 for MySQL I am using MySQL as my database and H2 for testing. I am also using playframework 2.3.x and Scala, but I think does not matter for the question purpose.
H2 has a conflict with some functions that I am using in a query
SELECT *
FROM subscriptions
WHERE active_until >= (DATE_SUB(CURDATE(), INTERVAL 3 DAY))
AND active_until <= (DATE_ADD(CURDATE(), INTERVAL 1 DAY))
AND status = "ACTIVE"

The functions that cause the problem are DATE_SUB and DATE_ADD.
Is there a workaround where I can make this work or change the query without breaking it for mysql?

A: Finally I was able to solve it. I had to change DATE_ADD for TIMESTAMPADD and DATE_SUB with TIMESTAMPDIFF. Then I changed CURDATE() for CURRENT_DATE. Also the sign of the method change but works on both H2 and My.
SELECT *
FROM subscriptions
WHERE active_until >= (TIMESTAMPDIFF(DAY, 3, CURRENT_DATE))
AND active_until <= (TIMESTAMPADD(DAY, 1, CURRENT_DATE))
AND status LIKE 'ACTIVE'

A: this is my example. TIME_TO_BEGIN is TIMESTAMP type. "DATEADD" function name and parameters like "MONTH" should all be upper cased.
CREATE TABLE BLOCKED_BIN_RANGE (
  BLOCKED_BIN_RANGE_ID BIGINT not null,
  TIME_TO_BEGIN TIMESTAMP not null,
  USER_NAME VARCHAR(30)  not null
);

Insert into BLOCKED_BIN_RANGE (BLOCKED_BIN_RANGE_ID,TIME_TO_BEGIN, USER_NAME)
        values (304, DATEADD('MONTH', 1, CURRENT_TIMESTAMP), 'BILL');


text:
Q: Is it possible to open a full screen map in battlefield 4 during play (while alive)? Is it possible to open a full screen map in battlefield 4 during play (while alive)?
In the bottom left of the screen I see a mini map and looking around I can see the objectives.  Can i change the mini map zoom levels or even better expand the map to full screen temporarily so I can plan my next action?
If so, how? (I play on PS4)

A: If you hold Options and press R1 you should see a full map.

A: Its true on the xbox as well, just start and Rb


text:
Q: How to use routerlink in angular2? I am trying to redirect from one page to another using routerlink and I had tried the following code,
I have the following route as my url
http://localhost:3000/#/app/dashboard

I want to redirect to this,when i click on this
  [routerLink]=" ['tables/basic'] "

http://localhost:3000/#/app/tables/basic

but it is going to
http://localhost:3000/#/app/dashboard/tables/basic

Here dashboard should be removed and how can I do that? Can anyone pls provide some help?
my routes.ts,
import { Routes } from '@angular/router';
import { ErrorComponent } from './error/error.component';

export const ROUTES: Routes = [{
   path: '', redirectTo: 'app', pathMatch: 'full'
  }, {
    path: 'app',   loadChildren: () => System.import('./layout/layout.module')
  }, {
    path: 'login', loadChildren: () => System.import('./login/login.module')
  }, {
    path: 'error', component: ErrorComponent
  }, {
    path: '**',    component: ErrorComponent
  }
];

A: Perhaps
[routerLink]="['../tables/basic']"

or
[routerLink]="['/app/tables/basic']"

To be sure you would need to provide the information what routes your application has configured and what component contains the [routerLink]

A: if you want to route from button click you can easily use this, and also you can use it as a parameter parser through the components.firstly i will describe how to use it as a only for routing.
 complain

from above example we can route the user/complain using complain  tag
now i am going to describe the second one(how to parse the parameters through the components)
i will do it using the router params
complain

from that we can parse job.id to complain component.
in complain component.ts file -
export class ComplainComponent {

  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.id = params['id']; // (+) converts string 'id' to a number

   });

  }

}

we can assign a variable for router parameter in this file.then you can easily whether is it worked or not by complain component.html file by

{{job.id}}


text:
Q: New global search doesn't like tags When you visit the global search page:

https://stackexchange.com/search

and want to search for a tag like we used to do on the site search like so:

[haskell] pattern

you're directed to the error page with the Panda.
If tag search is supposed to work, can this be fixed? If tag search is not supposed to work there can you at a minimum not throw an error?

A: There was a bug in the search query parsing code. The code was trying to read tag synonyms from a DB table that doesn't exist in the stackexchange.com database. The fix is already deployed. I've only noticed this thanks to exceptions in our log :)
Tag synonyms are not (yet) supported in the global search, as they are a per-site concept, and are handled outside of our elasticsearch index (we'd have to resolve them on every Q&A site, before generating the query, and potentially issue multiple different search queries, instead of a single one, like we do now).


text:
Q: How to change the class of a H element in Wagtail Draftail Editor I would like to add custom classes to H1, H2, H3, etc. in the Draftail editor.
I was looking at hooks but I am unsure if I'm looking at the right method, if you get what I mean?
The result I would like to have is, for example:
<h1 class="custom-h2"> Lorem ipsum dolor sit amet </h1>

Thanks in advance!

A: If you're using a RichTextField() you can give it features to enable or disable Draftail settings.
class YourPage(Page):

    ...
    custom_model_field = RichTextField(features=["h1", "h2", "h3", "bold", "italic"])

You can do the same with the RichTextBlock in a streamfield like so:
class CustomStreamfield(blocks.StructBlock):

    ...
    content = RichTextBlock(features=["h1", "h2", "bold", "italic"])


text:
Q: spring-data-mongodb dose not map integer values properly spring-data-mongodb 1.7.2.RELEASE auto save integer as double is mongodb.
Document to object mapping is ok.
But when I read documents as java.util.Map, all integer values turned into double values :(
Is it possible to make spring-data-mongodb save integer as Integer(X) not a double in mongodb.
Is it a bug?
something like this:
@Document
public class Foo {
    private Integer count;
    ...
}

fooRepository.save(fooInstance);

in mongodb document, field 'count' saved as double not NumberInt(X)

A: If you are using a class representation, you can specify how it is going to be used. So, in this case if you use jackson mapping from the document in mongo db and in your class you use values like int value; it will be mapped as that.


text:
Q: MVCBuildViews ignores files added as link I have some .cshtml files I am trying to share between projects (e.g. editor templates and such).
So, what I have attempted is a combination of a custom virtual path provider (which is working) and adding the shared files as links in the .csproj, e.g.
<Content Include="..\SharedWebContent\Views\Shared\EditorTemplates\Foo.cshtml">
  <Link>Views\Shared\EditorTemplates\Foo.cshtml</Link>
</Content>

However, when I do this, setting
<MvcBuildViews>true</MvcBuildViews>

ignores the linked files.  I have this conditionally set on our CI server, so that we quickly know when we introduce a compilation error in to a view or template.  However, MvcBuildViews appears to only check files that are physically present in the project directory.
Is there a way to tell MvcBuildViews to also check linked files?


text:
Q: how to format an integer output in JavaScript to add , with every 3 numbers Example = 123456789 = 123,456,789
is there any function that does the above or should I create one ?
Thank you

A: Intl.NumberFormat has a localized number formatting.
That means if your browser is set to English you will get your expected format, but if the browser is set to German it will return the German format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"


text:
Q: How to see what applications are listening on what ports in Azure App Service? An app I ran tried to use certain ports, and threw an error saying they are already being used.  Without having to pick random ports, how can I see which ones are already being used?  Also, how can I see which apps/services are using those ports.
There is no access to netstat.

A: Not exactly sure what you're asking, but the only inbound ports on a web app (app service) from the outside world are 80 and 443. These end up getting mapped to ports assigned to your app (and accessible via environment variables).


text:
Q: Strange bug while combining images in Python I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images:
blank = Image.new('P',(100,100))
blank.paste(im,box)

The smaller images are in color, but the resulting image turns out in all grayscale. Is there a fix or workaround for this?

A: It's probably something to do with using a palette type image (mode P). Is there a specific reason you are doing this? If not, try passing 'RGB' as the first argument.


text:
Q: "TypeError: string indices must be integers" in python Good I try to create a function with a list of clients where when placing the name in the function gives me the name of the client. But I get an error "TypeError: string indices must be integers"
listclient = ["john","william","tom"]

def SearchClient(nameclient,listclient):
  for counter in range(len(listclient)):
    if(listclient[counter]["name"]==nameclient):
      return listclient[counter]

  return None

client = SearchClient("tom",listclient)
print("find client:" +client["name"])

TypeError: string indices must be integers

I tried to change the "name" of the condition to "nameclient" but it didn't work, and I can't change the data type.

A: If you are trying to find if a particular client is in your client list, this is how you do it:
def SearchClient(nameclient, listclient):
    if nameclient in listclient:
        return f'Found client {nameclient} in list of clients.'
    return f'Did not find client {nameclient} in list of clients.'

listclient = ["john","william","tom"]
print(SearchClient("john",listclient))

#prints: Found client john in list of clients.


text:
Q: How to count discrete variables in a dataset? I am trying to count how many times each gender occurs in the table. The I would like to print those values inline with the rest of the text (I don't need any tables, but I am
\documentclass{article}

\usepackage{xstring}
\usepackage{datatool}

\newcommand*{\thePassGrade}{2.0}

\begin{filecontents*}{grade.csv}
name,givenname,matriculation,gender,grade
Maier,Hans,12345,m,1.0
Huber,Anna,23456,f,2.3
Weisbaeck,Werner,34567,m,5.0
Weisbaeck,Werner,34567,p,5.0
Weisbaeck,Werner,34567,q,5.0
Weisbaeck,Werner,34567,q,5.0
\end{filecontents*}

\DTLloaddb{grades}{grade.csv}

\begin{document}
\newcounter{m}
\newcounter{f}
\newcounter{p}
\newcounter{q}

\DTLforeach*{grades}{\name=name,\g=gender}{
\IfStrEq{\g}{m}{\stepcounter{m}}{
\IfStrEq{\g}{f}{\stepcounter{f}}{
\IfStrEq{\g}{p}{\stepcounter{p}}{
\IfStrEq{\g}{q}{\stepcounter{q}}}}
}}

There are \them and \thef and \thep and \theq

\end{document}

I am trying to get There are 2 and 1 and 1 and 2, instead I get an error.

A: It is easier to use \IfStrEqCase instrad of a nested \IfStrEq:

Code:
\documentclass{article}

\usepackage{xstring}
\usepackage{datatool}

\newcommand*{\thePassGrade}{2.0}

\begin{filecontents*}{grade.csv}
name,givenname,matriculation,gender,grade
Maier,Hans,12345,m,1.0
Huber,Anna,23456,f,2.3
Weisbaeck,Werner,34567,m,5.0
Weisbaeck,Werner,34567,p,5.0
Weisbaeck,Werner,34567,q,5.0
Weisbaeck,Werner,34567,q,5.0
\end{filecontents*}

\DTLloaddb{grades}{grade.csv}

%% No need for this to be after \begin{document}
\newcounter{m}
\newcounter{f}
\newcounter{p}
\newcounter{q}

\begin{document}

\DTLforeach*{grades}{\name=name,\g=gender}{%
    \IfStrEqCase{\g}{%
        {m}{\stepcounter{m}}%
        {f}{\stepcounter{f}}%
        {p}{\stepcounter{p}}%
        {q}{\stepcounter{q}}%
    }%
}

There are \them\ and \thef\ and \thep\ and \theq.

\end{document}


text:
Q: How to synchronize this model correctly? Imagine there is a masseur and he has his own salon. He is sleeping the whole day until a customer enters the salon and wakes him up.
The customer is sleeping while he gets his massage. When the masseur finishes he wakes up the customer and gets paid for his service.
The customer leaves the salon.
The masseur enters the waiting room to look for another waiting (sleeping) customer. If there aren't any the masseur goes to bed again.
This is an interesting situation when working with threads.
public class Aufg1{
    public static void main(String args[]){
        MassageSalon ms = new MassageSalon();
        Customer c = new Customer(ms);
        Masseur m = new Masseur(ms);
        m.start(); c.start();
    }
}

Masseur.java
public class Masseur extends Thread{

    final MassageSalon salon;

    public Masseur(MassageSalon pSalon){
        salon = pSalon;
    }

    public void run(){
        while(true){
            salon.getNextCustomer();
            salon.finishedMassage();
        }
    }
}

and Customer.java:
public class Customer extends Thread{

    final MassageSalon salon;

    public Customer(MassageSalon pSalon){
        salon = pSalon;
    }

    public void run(){
        while(true){
            salon.getMassage();
        }
    }
}

I have a class MassageSalon. The code describes pretty much the same I just mentioned.
Now I want to use wait(), notify(), notifyAll() to ensure that everything works just like I mentioned it. I already edited the MassageSalon class and added wait(), notify() methods.
Do you think the positions for wait() and notify() are correct? When running this code the finishedMassage method isn't called. Why?
 public class MassageSalon {
    private int customerOnCouch = 0;
    private int customerPaid = 0;
    private int masseurAvailable = 0;
    private int masseurBusy = 0;
    private int masseurDone = 0;
    private int masseurClose = 0;

    public synchronized void getNextCustomer() {

        while(masseurAvailable != masseurClose){
            try{
                System.out.println("waiting for masseur...");
                wait();
            }catch(InterruptedException e){
                System.out.println(e);
            }
        }

        //masseur is available to handle a new customer

        System.out.println("masseur is available to handle a new customer");

        masseurAvailable++;

        while(customerOnCouch == customerPaid){
            try{
                System.out.println("waiting for customer...");
                wait();
            }catch(InterruptedException e){
                System.out.println(e);
            }
        }

        //and is busy as soon as a new customers takes his couch

        System.out.println("and is busy as soon as a new customers takes his couch");

        masseurBusy++;
    }

    public synchronized void finishedMassage() {
        //eventually the masseur finishes the massage

        System.out.println("eventually the masseur finishes the massage");

        masseurDone++;

        notify();

        //and closes the deal as soon as the customer paid

        System.out.println("and closes the deal as soon as the customer paid");

        masseurClose++;
    }

    public synchronized void getMassage() {
        //customer takes a couch

        System.out.println("customer takes a couch");

        customerOnCouch++;

        notify();

        while(masseurBusy != masseurDone){
            try{
                System.out.println("waiting to finish massage");
                wait();
            }catch(InterruptedException e){
                System.out.println(e);
            }
        }

        //and pays for the massage after it

        System.out.println("and pays for the massage after it");

        customerPaid++;
    }
}

A: You're describing Dijkstra's Sleeping-Barber problem, but with a massage salon instead of a barber shop. The solution remains the same, though, and can be found here: http://en.wikipedia.org/wiki/Sleeping_barber_problem#Solution

A: You could use a fair Semaphore called NotSleeping.
As long as the customer does not enter the saloon, it holds NotSleeping. When customer comes in, it releases the semaphore, which wakes the thread of the masseur trying to grab NotSleeping too. After release, customer tries to hold NotSleeping again during the massage.
When done, Masseur releases NotSleeping, which is grabed again by the customer. Masseur, tries to hold NotSleeping again, until customer comes in. Etc Etc...


text:
Q: Security of HTTP by
A: 1.It's Possible ?
Yes Ofcourse it's Possible, <script> element are useful Ajax Transports for One Primary Reason :
they are not subject to the same origin policy , so you can use them to request data from server other than your own.
2.What is the better way to do this ?
I think if you use <script> element as an Ajax Transport , You Have to Allow your Web Page to Run Whatever Javascript Code the remote server chooses to send you,This means that you must not use this technique described here with untrusted servers.

When You use trusted server, Keep in Mind if an Attacker can hack into that server, then the hacker can take over your web page run any code he wants and display any content he wants, and that content will appear to come your site.
Note that to use trusted third party script , especialy to embed advertising or "widgets" into a page, Using a <script> as an Ajax transport to communicate with trusted web service is no more dangerous than that.
the technique of using a <script> element as an Ajax transports has come to be knows as JSONP, it's work when the response body of the HTTP request is JSON-encode.


text:
Q: gulp.src(globs) From a Variable Array How can a variable (array) be used in gulp.src(globs)?
I have several Gulp tasks that use the same "group" of files but I do not know how to DRY the tasks to use the variable passed into the globs.
. . .
var configDir   = '../private/app/_config/',
    configFiles = [
        configDir + 'categories.yaml',
        configDir + 'params.yaml',
        configDir + 'taxonomies.yaml'
    ];

// Merge development config yaml(s)
gulp.task('yaml_merge-dev', function() {
  return gulp.src([
        'config.root.yaml',
        configDir + 'site.dev.yaml',
        configFiles
      ])
    .pipe(yamlMerge('config.dev.yaml'))
    .pipe(gulp.dest('../'));
});

// Merge production config yaml(s)
gulp.task('yaml_merge-prod', function() {
  return gulp.src([
        'config.root.yaml',
        configDir + 'site.prod.yaml',
        configFiles
      ])
    .pipe(yamlMerge('config.prod.yaml'))
    .pipe(gulp.dest('../'));
})
. . . // etc.

A: gulp.src() only accepts one flat array of files, not nested arrays. That means you have to add all the files in configFiles to the array that you pass to gulp.src().
Since gulp is just JavaScript, you can use any of the many possible ways that you can combine arrays in JavaScript. In your case  Array.prototype.concat() is probably the most appropriate:
gulp.task('yaml_merge-dev', function() {
  return gulp.src([
    'config.root.yaml',
    configDir + 'site.dev.yaml'
  ].concat(configFiles))
  .pipe(yamlMerge('config.dev.yaml'))
  .pipe(gulp.dest('../'));
});

A: You are correct to want to DRY your tasks.
Using yargs, you can narrow down your code to a single task that uses command line arguments.
Run:
npm install --save-dev yargs

Javascript
. . .
// Require yargs: https://www.npmjs.com/package/yargs
var args = require('yargs').argv;

// Site file based on argument
var siteFile = args.release? 'site.prod.yaml' : 'site.dev.yaml';

// Merge config file based on argument
var yamlMergeConfig = args.release? 'config.prod.yaml' : 'config.dev.yaml';

// Single declatations for readibility
var configDir = '../private/app/_config/';

// Your config files in a single glob
var configFiles = [
        configDir + 'categories.yaml',
        configDir + 'params.yaml',
        configDir + 'taxonomies.yaml'
        configDir + siteFile
    ];

gulp.task('yaml_merge', function() {
  /// <summary>
  /// Merge development or production config yaml(s)
  /// gulp yaml_merge             : deploys the development build
  /// gulp yaml_merge --release   : deploys the release build
  /// </summary>
  return gulp.src(configFiles)
    .pipe(yamlMerge(yamlMergeConfig))
    .pipe(gulp.dest('../'));
});
. . . // etc.


text:
Q: How to compile rhino/javascript files to .class bytecode for java at runtime I'm making a falling sand game in Java. I want users to be able to write their own engine for it using a simpler language. Falling sand games can be very CPU intensive so I want to have the engine running as fast as possible while not having to manually compile.
I need to know how to compile rhino javascript files to .class files by at runtime to be used.
I've looked for a way but couldn't find any other than manually compiling it by using the command line which I don't want users to have to do.

A: There's a short tutorial here:

*

*Scripting: Compiling Scripts in Java

A: My solution here:
Has anyone used or written an Ant task to compile (Rhino) JavaScript to Java bytecode?

A: You can compile your scripts at runtime using Context.compileString(). This produces a Script object which you can reuse.
Script s = someContext.compileString(myScript, "<cmd>", 1, null);

// Store s, cache it in a map or something, maybe even serialize and persist it.

// Later...

Object result = s.exec(anotherContext, someScope);

The performance difference between something like this and using Context.evaluateString() could easily be multiple orders of magnitude faster.

A: You can try the follow sample:
void toClassFile( String script ) throws IOException {
    CompilerEnvirons compilerEnv = new CompilerEnvirons();
    ClassCompiler compiler = new ClassCompiler( compilerEnv );
    Object[] compiled = compiler.compileToClassFiles( script, null, 1, "javascript.Test" );
    for( int j = 0; j != compiled.length; j += 2 ) {
        String className = (String)compiled[j];
        byte[] bytes = (byte[])compiled[(j + 1)];
        File file = new File( className.replace( '.', '/' ) + ".class" );
        file.getParentFile().mkdirs();
        try (FileOutputStream fos = new FileOutputStream( file )) {
            fos.write( bytes );
        }
    }
}


text:
Q: Nodejs SDK - Merge dialog + intents Is there any way I can merge the dialog with intent so that I do not need to have the redundant code snippet?
 bot.dialog('whats-your-name', require('./dialogs/whats-your-name'))
 intents.matches('whats-your-name', require('./dialogs/whats-your-name'))

A: You could plug your instantiated IntentDialog into your root dialog ("/") and have the IntentDialog handle all of the routing:
var intents = new builder.IntentDialog({ recognizers: [recognizer] });
bot.dialog("/", intents);

Or you could forgo the the IntentDialog and instead plug your recognizers into the bot-level like so:
bot.recognizer(recognizer);
bot.dialog("/", [ ... ]);

bot.dialog("luisIntentA", [ ... ])
   .triggerAction({
     matches: "luisIntentA"
   });

I recommend the latter approach as this affords more control over routing intents and switching between dialogs.


text:
Q: ServiceStack vs ASP.Net Web API I want to write a new REST style API and have looked at ServiceStack and quite like it. However, I have seen that Microsoft has released the ASP.Net Web API project as part of the new MVC 4 beta. Has anyone looked at the new Web API project? Can you give any pros/cons of each system?

A: As a customer of ServiceStack here is the pro for ServiceStack most important for me.
https://github.com/ServiceStack/Issues/issues/606
So. Bug found, bug identified, bug fixed. Same day. Extraordinary support!

A: They have very similar use-cases, as the lead maintainer for the ServiceStack project I have a good insight into ServiceStack's advantages and the many natural benefits of its message-based design.
ServiceStack has been around since 2008 as an OSS-run project from its inception with a single goal of promoting the correct design and implementation of friction-free remote services.
Simple and Elegant Design
In its pursuit for ultimate simplicity, it's built around a simple and elegant core - with most of its features naturally binding to your models, not your controllers - which is what MVC, WebApi does (as well as every other Web Service Framework Microsoft has produced).
Adopting a message-based design offers a superior approach for remote services, in that they promote more extensible and less brittle services, simplifies access and calling patterns, and contain many other natural benefits you get for free.
As a core mission, we fight complexity at every stage, aiming to keep an invisible and non-intrusive API and avoid introducing any new concepts or artificial constructs that aren't already familiar to .NET or web service developers today.
As an example your IService<T> service implementation is just a standard C# class with auto-wired dependencies. Thin and lightweight wrappers are used to provide a consistent and unified API around the core run-time IHttpRequest and IHttpResponse types. They also allow access to underlying ASP.NET or HttpListener's Request and Response classes so you're never restricted when using ServiceStack.
Contrasted with WCF and WebApi
Here's a brief overview of the contrasting API styles that ServiceStack and WCF promote. WebApi is different to WCF in that it encourages REST-ful API design. As for examples between the 2, this is the only known example I have with the same service written in both ServiceStack and WebApi.
Best Practices remote services
ServiceStack has a primary focus on simplicity, performance and in promoting web/remote service best-practices centered around embracing Martin Fowlers remote-service design patterns in as idiomatic C# as possible:

*

*The Facade Pattern - Which suggests the usage of batchful, coarse-grained interfaces when ever you communicate across process boundaries.

*The DTO pattern (MSDN) - Dictating the use of special-purpose POCOs to generate the wire format of your web services responses.

*The Gateway Pattern (MSDN) to encapsulate your client and server communications between the Client Gateway / DTO models and Service Interface tiers.
These patterns ensure a clean separation of concerns and a friction-free iterative dev experience.
Empowering your services
A ServiceStack web service at its core is centered around a dependency-free and auto-wired  pure C# IService<T> interface that gives you complete freedom to define your web service contract with your own Request and Response DTOs using clean POCOs - rendering ServiceStack's API practically invisible and non-invasive, i.e. it's trivial to extract your C# services logic and run it outside of a ServiceStack host.
This gist is a good example of what you get with just 1 C# .cs class in ServiceStack:

*

*Metadata pages for all registered formats

*

*With links to WSDLs, XSDs and C# client examples

*Human friendly HTML report view

*

*A single self-contained html page snapshot (i.e. no external refs). Includes embedded JSON web service response - allows programmatic access to data snapshots.

*Built-in Mini Profiler (port of the excellent MVC Mini Profiler)

*

*Includes Sql Profiling

*JSON/JSONP, XML, JSV, CSV and SOAP end-points

The RestServiceBase and ServiceBase classes are intended to host your custom C# logic for maximum potential re-use as possible, e.g. Its DTO-first design trivially allows for deferred and proxied execution where your same C# Service can also be hosted and executed in an MQ Host which is what happens when you register an IMessageService like the RedisMQ host and call your service via the /asynconeway endpoint (i.e. client.SendOneWay() in C# Clients)
You can also easily delegate and create composite services using the base.ResolveService<T>() method which returns an auto-wired instance of the selected service as seen in the Nortwind CustomerDetails Service example:
var ordersService = base.ResolveService<OrdersService>();
var ordersResponse = (OrdersResponse)ordersService.Get(
    new Orders { CustomerId = customer.Id });

Return plain C# objects
For the most part ServiceStack will serialize most C# objects as expected - here's a list of possible return types (from this answer):

*

*Any DTO object -> serialized to Response ContentType

*HttpResult, HttpError, CompressedResult (IHttpResult) for Customized HTTP response

The following types are not converted and get written directly to the Response Stream:

*

*String

*Stream

*IStreamWriter

*byte[] - with the application/octet-stream Content Type.

An example of the Custom HTTP headers support can be seen by this CORS example where you can configure HTTP Headers globally or on a per-service basis.
HTML Support
There are multiple options for returning HTML in ServiceStack that is explained in detail here.
Includes fastest text and binary serializers for .NET
Resilient and fast serializers are of primary importance in an API to ensure fast response times and a versionable API which doesn't break existing clients which is why ServiceStack includes the fastest text serializers for .NET with a NuGet option to enable @marcgravell's Protocol Buffers (.NET's fastest binary serializer).
ServiceStack's text serializers are very resilient and can withstand extreme versioning without error.
Friction-free dev experience End-to-End
ServiceStack's opinionated nature allows for a fast, typed, terse web service API end-to-end with built-in support for Sync/Async C#/.NET and Async Silverlight clients without any code-gen:
Sync C# Example
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });

Async C# Example
client.SendAsync<HelloResponse>(new Hello { Name = "World!" },
    r => Console.WriteLine(r.Result), (r, ex) => { throw ex; });

As it just returns pure JSON it's also trivially consumed with other HTTP Clients, e.g. JS client example using jQuery:
$.getJSON("http://localhost/Backbone.Todo/todos", function(todos) {
    alert(todos.length == 1);
});

Highly testable
All C#/.NET ServiceClients share the same interfaces which make them highly testable and swappable to the point where you can have the same unit test also serve as an XML, JSON, JSV, SOAP Integration Test.
Rich Validation and Error Handling built-in
In its mission to provide a friciton-free and clean dev experience, ServiceStack also includes typed validation and error handling built-in where throwing an C# Exception or using its built-in Fluent validation provides clients structured, typed errors easily accessible on web service clients, e.g:
try {
    var client = new JsonServiceClient(BaseUri);
    var response = client.Send<UserResponse>(new User());
} catch (WebServiceException webEx) {
    /*
      webEx.StatusCode  = 400
      webEx.ErrorCode   = ArgumentNullException
      webEx.Message     = Value cannot be null. Parameter name: Name
      webEx.StackTrace  = (your Server Exception StackTrace - if DebugMode is enabled)
      webEx.ResponseDto = (your populated Response DTO)
      webEx.ResponseStatus   = (your populated Response Status DTO)
      webEx.GetFieldErrors() = (individual errors for each field if any)
    */
}

To make it trivial to consume errors in JavaScript, you can use the lightweight ss-validation.js JavaScript library to trivially bind your response errors to your HTML form fields with a single line of code. The SocialBootstrapApi example project provides a good demo of this.
Rich Integration with ASP.NET and MVC
The ServiceStack MVC PowerPack re-writes and fixes a lot of the ails of ASP.NET and MVC with replacements for its crippling Session and Caching XML-encumbered ASP.NET providers with its own clean and dependency-free implementation of ICacheClient and ISession APIs.
ServiceStack also includes a newer and cleaner authentication and autorization provider model with a number of different AuthProviders in-built:

*

*Credentials - For authenticating with username/password credentials by posting to the /auth/credentials service

*Basic Auth - Allowing users to authenticate with Basic Authentication

*Twitter OAuth - Allow users to Register and Authenticate with Twitter

*Facebook OAuth - Allow users to Register and Authenticate with Facebook

The Authentication module is entirely optional and is built-on the clean ICacheClient / ISession APIs and OrmLite which allows your Sessions to be stored in Memory, Redis or Memcached and your UserAuth info persisted in OrmLite's supported RDBMS's of SQLServer, MySql, PostgreSQL, Sqlite as well as Redis data-store or InMemory (useful for dev/testing).
Great Documentation
ServiceStack is very well documented where most of the information about the framework is hosted on the GitHub wiki. Documentation for other parts of the framework (e.g. Serializers, Redis, OrmLite) can be found on servicestack.net/docs/
The ServiceStack.Examples Project provides the source code for all of ServiceStack's live demos and Starter Templates whilst the SocialBoostsrapApi project provides a great starting point of developing a Backbone.js Single Page App with ServiceStack and MVC based on Twitters Bootstrap template.
In addition to the above a treasure trove of information is contained within the Google Group which has expanded quite considerably in recent years.
Runs Everywhere
ServiceStack is a .NET 3.5 framework that runs on ASP.NET and HttpListener hosts and can be hosted on either .NET or Mono (trivia: www.servicestack.net is powered by CentOS/Mono). This allows your ServiceStack web services to be hosted on either:
Windows with .NET 3.5 & 4.0

*

*IIS 5/6/7 (uses IHttpHandler)

*VS.NET WebDevServer

*Console App or Windows GUI

*Windows Service
Linux/OSX with Mono

*

*Apache + mod_mono

*Nginx + MonoFastCGI

*XSP

*Console App

Developed with the Open Source development model
ServiceStack is a strong believer of the Open Source development model where it is actively developed in the open and has always been hosted under a liberal OSS licence (New BSD) since its inception. As of today it has received contributions from more than 47 developers and it currently stands at the 3rd most watched C# project on GitHub.
Disadvantages
I believe the biggest disadvantage is the same for most other OSS .NET projects where it wasn't developed (or even listed as an available option) by Microsoft. This means it's rarely ever the first choice when evaluating a framework. Most adopters will only evaluate ServiceStack as a last resort, where they're either frustrated with the imposed friction and brittleness of WCF or the performance of the preferred Microsoft Stack.
Feedback and Community Resources
ServiceStack has been very well received with positive feedback provided by most people who have evaluated it as visible by the positive sentiment in the mailing group. As of this year the @ServiceStack twitter account has been tracking mentions and feedback in its favorites.
The Community Resources wiki page is a good place to find out more about ServiceStack in the wild with links to Blog Posts, Pod Casts, Presentations, Gists and more.

A: It's been one year that I use SS and it's all great.
ORMLite is pure magic. I was able to remap an awfull MySQL DB to integrate in a mobile apps. No change on the database cause it's use with a php backend with another apps...
Mythz is an example regarding support and explanation. It upgraded my knowledge regarding apps design and simplicity on maintenance. Please try it and you will understand.
Also, don't compare SS with WebAPI. It's not enough, SS bring much more to your toolbox. ServiceStack.Text is a great Automapper too.

A: I can't really say much about ServiceStack, but Web API has a lot of great features and is currently at version 2.
Some of the things you can do with Web API:

*

*Self host in an OWIN application (i.e. runs anywhere).

*Full support for async and await.

*Good default Templates and tons of open source examples.

*Used great Json.Net JSON serializer.

*Rest-ish by default (you'll have to do hypermedia yourself).

*and more...

A: There is a new main difference that needs to be accounted for - ServiceStack is no longer free to use as of v4.  Since there is a pretty definitive answer on the SS pro's I wanted to throw a couple out for Web API
Web API
Pro's :

*

*Free to use in your project (provided you have a VS license that allows commercial use)

*Extraordinarily high level of free support available from Microsoft and all over the web, including here on StackOverflow.com.

*Quickly integrates with other Microsoft technology stacks like ASP.NET MVC which is extremely popular in Microsoft shops

*Built in support for RESTful authentication and authorization in your Microsoft stack

Con's :

*

*Doesn't support SOAP

Ancillary Benefits
(Please feel free to leave comments below adding to why Web API has benefits or has pros / cons I can add)


text:
Q: Using ImageView as Parent? Is it possible to use an ImageView as parent? I want to put a few TextViews on an ImageView and when the user zooms on ImageView, I want TextViews to be zoomed too!
Note: I made a zoom-able ImageView but i can't make a zoom-able RelativeLayout...
EDIT:
my xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

    <nikdan.m.metro.ZoomableImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/imgMap"
         android:layout_gravity="center" />

    <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:textAppearance="?android:attr/textAppearanceLarge"
         android:text="Hello"
         android:id="@+id/text"
         android:layout_gravity="center"
         android:textColor="#ff0000" />
</FrameLayout>

A: Make FrameLayout as the Parent and add TextViews after the ImageView.
That should do the trick.


text:
Q: Javascript performance suggestions for displaying huge tabled data I am a very visual programmer/designer, and I developed a mini-framework for my projects for displaying data from PHP output.
Basically I design my page and desginate div and li blocks to be looped and displayed using my IDE, Dreamweaver. I simply do a string replace routine on the target div/li elements using Javascript to generate the content. I guess you can say my design visually is the template itself. It's so much easier to do changes: before, I'd design it then copy and paste the HTML code for the block to be looped into PHP, and there I do the value filling.
So basically my PHP script outputs an object and my Javascript function does the magic and generates (appends to an element) as needed..
This has worked perfectly until I started handling huge amounts of table data (around 2000 rows). I notice the browser pausing for a bit while it tries to generate the content, and that's on a desktop - I'd imagine how much slower it can be when my page is ran on a mobile device.
This got me thinking, should i go back to generating content in the backend and do a simple output on the JS/browser side? I liked manipulating rows of data in JS already, and it's much more visually convenient to keep all the template code on the page, as is, where is, and have Javascript just pick it up and use it to generate content. I'd hate going back to having PHP generate the actual html code.
What would you recommend in this situation?
P.S.: For those who want to suggest cutting down data limiting display: in this case I can't. I have to show all returned rows without paginations. I have my reasons/requirements.

A: simple Implementation of underscore.js

        Id
        Name

Id

Name

fetch data and populate
var items = [
{name:"Nick"},
{name:"Lee"},
{name:"Jenny"},
{name:"Julie"},
{name:"Dennis"},
{name:"Shawn"},
{name:"Justin"},
{name:"Scott"},
{name:"John"},
{name:"Sherell"},
{name:"Janie"},
{name:"Graham"},
{name:"Erica"}]

var tableTemplate = $("#table-data").html(),
divTemplate = $("#div-data").html();
$("table.outer tbody").html(_.template(tableTemplate,{items:items}));
$("div.outer p").before(_.template(divTemplate,{items:items}));


text:
Q: Enabling PDO in php.ini file resulted in 500 Internal Server Error When I enabled PDO in php.ini file in root directory (C:\PHP) on Windows Server 2008 Standard it resulted in 500 Internal Server Error.
I use IIS as web server and MSSQL as database.
3 Websites are hosted on the server.  2 websites are running fine when PDO is enabled. Only 1 goes down with error message 500 Internal Server Error.
Please help. How do I fix this?
Below are the codes I uncommented from the php.ini file.
[PHP_PDO]
extension=php_pdo.dll

[PHP_PDO_MSSQL]
extension=php_pdo_mssql.dll

[PHP_PDO_ODBC]
extension=php_pdo_odbc.dll

Thanks.


text:
Q: Lualatex and Syriac (initial, middle and final letters) I have heard that it is possible to typeset Arabic texts with Lualatex, so I assume that it is also possible to typeset Syriac texts with LuaLatex. But when I run the following example, the output is not like it should be:
\documentclass{scrartcl}
\usepackage{fontspec}

\newfontfamily\syriacfont[Script=Syriac]{Serto Batnan}%unicode otf; available http://www.bethmardutho.org/images/fonts/melthofonts-1.21.zip
\newcommand{\syr}[1]{\bgroup\luatextextdir TRT\syriacfont #1\egroup}

\begin{document}

\syr{ܟܕ ܛܝܒܘܬܐ ܡܫܡ̇ܗ ܐܦ ܠܢܡܘܣܐ. ܚܠܦ ܠܡ ܗܝ̇ ܛܝܒܘܬܐ ܗܕܐ ܐܬܝܗܒܬܼ}

\end{document}

The letters and words appear in the right order (ie. right to left), but there is no distinction between initial, middle and final letters. lualatex always uses the stand alone letters. I'm pretty sure that this is not the font's fault, because running the following, similar example with XeLatex, the output is right:
\documentclass{scrartcl}
\usepackage{fontspec}
\usepackage{polyglossia}
\setotherlanguage{syriac}
\newcommand{\syr}[1]{\RL{\textsyriac{#1}}}

\newfontfamily\syriacfont[Script=Syriac]{Serto Batnan}

\begin{document}

\syr{ܟܕ ܛܝܒܘܬܐ ܡܫܡ̇ܗ ܐܦ ܠܢܡܘܣܐ. ܚܠܦ ܠܡ ܗܝ̇ ܛܝܒܘܬܐ ܗܕܐ ܐܬܝܗܒܬܼ}

\end{document}

How can I make lualatex access the relevant otf information to determine between inital, middle and final letters?

A: Arabic support for LuaLaTeX is still in development: see Typesetting arabic with LuaLaTeX. I don't know if there's Syriac support in LuaLaTeX. There is a package for XeLaTeX, however: (unfortunately not on CTAN): XeSyriac.


text:
Q: How to quit the Story Mode? I just bought a PS3 Slim and GTA V. When I open GTA V, it automatically opens up in Story Mode. I don't want to play the role playing aspect of it, I just wanna play the regular version, like, the one where you steal cars, shoot guns, but not the story mode. Can someone help me quit the story mode please?

A: There is no "regular mode", the game only has story mode and GTA Online. You first need to play until the end of the prologue and the first mission. After that, you can go around the city freely and cause all the damage you want, but well, most YouTubers and Twitch streamers play on GTA Online, so that's probably what you're thinking. You can switch to GTA Online through the pause menu, on the online tab (after completing the prologue), or by holding Left-Alt (keyboard) or down on the directional pad (controller), and navigating to the bottom of the circle.

A: After completing the Prologue and first mission, with the cars, you can enter your phone, go to settings and then click on "Do Not Disturb". Turn that on. This prevents you from recieving phone calls that could possibly progress the storyline.
Apart from that, avoiding mission markers is the best you can do.

A: Actually when you go into story mode, press menu and you'll see a tab that says game tap game start a new game and you don't have to do the missions. You can also get gta online and only do the beginning mission of gta v until the gta v logo shows up and you can play gta online


text:
Q: Why is $I$ often an ideal in quotient ring $A/I$? When talking about quotient ring $A/I$, where $A$ is a ring, $I$ is often assumed to be an ideal. Why is this so? What makes ideals very important when discussing quotient ring?

A: First, to construct the quotient space, you want the relation $\sim$ defined by $x\sim y\iff x-y\in I$ to be an equivalence relation.
Then you want to be able to define operations for the cosets so that $[x]+[y]=[x+y]$ and $[xy]=[x][y]$ are well defined and give $A/I$ the structure of a ring.
From these requirements it follows that $I$ is an ideal.
That is, you cannot form the quotient ring if $I$ is not an ideal.

A: Here is a fairly intuitive way to see why $I$ must be an ideal for the quotient to be a ring.
When we take a quotient $R/I$, what we would like to do is identify all elements of $I$ with a single element, and then identify other elements "as needed".
Recalling that $R$ is in particular an additive group, to get a nice quotient we want $I$ to be a subgroup (and fortunately, normality is then automatic as the group is abelian). This means that the additive structure on $R/I$ should be the one we are used to by taking a quotient of groups, and in particular, we need to identify all elements of $I$ with $0$.
Now (writing $\overline{y} = y + I$ for the class containing $y$ in $R/I$), we get that for any $r\in R$ and $x\in I$ we have $$\overline{rx} = \overline{r}\cdot\overline{x} = \overline{r}\cdot\overline{0} = \overline{r\cdot 0} = \overline{0}$$
So for all $r\in R$ and $x\in I$ we see that $\overline{rx} = \overline{0}$ in $R/I$. But the way we did the construction, we not only wanted to identify everything in $I$ with $0$, we did not want to identify anything else with $0$ (since we wanted to take the usual quotient of groups). So the above precisely says that $rx\in I$.
In some sense this means that the fact that being an ideal is sufficient to define a ring structure on the quotient is actually a bit of a surprise (we might well have needed something stronger, as we have above just used that multiplying with $0$ gives $0$). But it is of course an easy exercise that being an ideal is sufficient.


text:
Q: SimpleXML and namespaces I have following code.
 <entry>
  <job:location>
   <job:id>24</job:id>
   <job:region>6</job:region>
  </job:location>
 </entry>

I've problem with namespaces. How I can read content of job:region tag in SimpleXML.

A: Try this:
 <?php
    $entry = simplexml_load_file('entry.xml');
    printf("%s\n", $entry->children('job', true)->location->region);
 ?>

To check the above code in action, click here
For more information about SimpleXml refer to this article

A: You should register the job namespace, then you can use the registered namespace-prefix in an XPath to select what you want:
$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('job', 'http://example.org/you-did-not-provide-the-job-namespaceURI-in-your-example');
$result = $sxe->xpath('//entry/job:location/job:region');

foreach ($result as $location) {
  echo $location . "\n";
}

A: I would do it dynamically.
$xml = @simplexml_load_string($path) // loads your valid xml data
foreach($xml->channel->item as $entry) {

  $namespaces = $entry->getNameSpaces(true);
  foreach($namespaces as $ns=>$value)
  {
    $job = $entry->children($namespaces[$ns]);
    $author = (string)$job->creator;

    if ($author != "")
    {
      $someVariable = (string) $dc->creator;
    }
}


text:
Q: In a Postgresql database where a seller has many products and products have many sellers, where should price(s) get stored? Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this?

Per the recommendations below this is the correct db schema:

A: Since you have a case of many-to-many then your structure would use a link table. You'll have tables seller, product and link_seller_product. The last table has a link to the seller table via id as well as the product table via id. This table therefore can also have any information that is dependent on the seller and the product and is not fixed for either. So price-per-product-per-seller goes there.
So add the additional link table with columns sellerid, productid and price and you'll have only single rows in sellers and products but each seller can have their own price for the product.

A: You're not adequately representing the one-to-many relationship between products and sellers.  Your product table has the seller_id and the seller_price, but if one product is sold by many sellers, it cannot.
Instead of duplicating product entries so the same product can have multiple sellers, what you need is a table between products and sellers.
CREATE TABLE seller_products (
   seller_id integer,
   product_id integer,
   price decimal
);

I'll leave the indexes foreign keys etc to you.  Seller ID and product ID might be a unique combination ( historical data is best removed from active datasets for performance longevity ) , but of course any given product will be listed once for each seller that sells it and any given seller will be listed once per product it sells ( along with its unique price).
Then you can join the table back to products to get the data you currently store denormalized in the products table directly :
SELECT *
FROM products
LEFT JOIN seller_products ON ( seller_products.product_id = products.id)

A: This is a Data Warehouse question.
I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions.
Dimensions:

*

*Product

*Seller

*Manufacturer

Fact (Columns):

*

*List item

*Seller Price

*List item

*MRSP

*Product ID

*Seller ID

*Manufacturer ID

*Timestamp


text:
Q: Designing a database structure for huge sets of form data I am converting a form that takes up 35 pages of A4 size to a web based version, and will need to retain the data for each form submission in a MySQL database.
The form is complex and we could be looking at over 500 individual fields for each form submission.
I've been reading about the EAV data approach, which seems like it might be a good option. The info I was reading for EAV however suggested it was only a good choice for sparse matrix data, which I imagine this will not be.
500 columns seems like bad design, what do you think?

A: Have 'real' columns for a few of the fields -- the ones that you are likely to search or filter on.  Throw the rest (or, simply, all) of the fields into a big JSON string as another column.  Perhaps MEDIUMTEXT.


text:
Q: Sending Message to Application from Server- Connecting the GCM I try to implement an application with Google Cloud Messaging from http://developer.android.com/guide/google/gcm/gs.html
Sender sender = new Sender(myApiKey);

                Message message = new Message.Builder()
                .collapseKey("1")
                .timeToLive(3)
                .delayWhileIdle(true)
                .addData("message", "message is created at builder")
                .build();

                Result result = sender.send(message, reGid, 5);
                System.out.println("result of message is "+result);

and consequently i get a message id and can see from console; but i want to show message at my device with a toast.
GCMIntentService.java:
@Override
protected void onMessage(Context arg0, Intent arg1) {
    Log.i(TAG, "new message= ");
    Toast.makeText(this, arg1.getStringExtra("message"), Toast.LENGTH_SHORT)
            .show();
}

from GCM Advanced Topics:
When a 3rd-party server posts a message to GCM and receives a message ID back, it does not mean that the message was already delivered to the device. Rather, it means that it was accepted for delivery. What happens to the message after it is accepted depends on many factors.
In the best-case scenario, if the device is connected to GCM, the screen is on, and there are no throttling restrictions (see Throttling), the message will be delivered right away.
I can't understand what means "the device is connected to GCM".
How can device connect the GCM, connecting the internet and running the application from device isn't enough?

A: Connecting to GCM depends on a few things.

*

*The device has registered to receive messages - GCMRegistrar.register

*The device has a connection that allows the message to be delivered

*The device meets certain requirements for installed software that allows the delivery of messages - namely the Google API's - Minimum SDK 2.2

UPDATE:
When you send the message you receive a status response which if everything is ok will mean a message id. The device that sent the message will not receive the message unless the message was sent to that device (using the devices registered GCM id). The devices registration id is return following the call from the device to register.
Please note that with GCM there is no guarantee that the message will be delivered. It is normally very reliable but should not be used if delivery is critical.
Yes onMessage() is the entry point for a new message being received by the device.

A: You should follow this link to get answers of your all questions :
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
you just need to implement client and server. I have implemented on my own PC and got running code. I have already tested on PC to Mobile also.
Source Code is available.  you just need to download and follow some easy steps.
I bet you will get your code running within 30 min.
Happy to Help !!


text:
Q: iPhone iOS jQuery function $('content').height(); bug I've got a short script for solving absolute position height.
document.body.onresize = function () {
    contentHeightFix(currentConDiv);
}
contentHeightFix(currentConDiv);

function contentHeightFix(id) {
    currentConDiv = id;
    $('.heightFix').height($(id).height());
}

So I have an absolute div and it has text in it, so the height of div is variable. I've placed a blank div under this div, called it .heightFix and let jQuery set height of this div based on height of that absolute div.
Everything works fine on Mac, PC, android browsers. All of them, including Safari on MacOS.
But when I run this script on the iOS, it's bugged - look at screenshot 2. Script works perfectly until I scroll the page downwards (even 1px scroll breaks it, but scrolling up to the top is fine). That's weird in my opinion, cause the script doesn't operate with scrolling what so ever...
I can also attach screenshots of that behaving.
Proper behaving (before I scroll down):

Wrong behaving (after I scroll even 1px down):


text:
Q: Windmills generate electricity by the spinning blades. Why can't EV vehicles recharge their batteries from their spinning wheels? Is that too hard? I'm just a carpenter who's job it is to find the easiest answers to the biggest problems. I don't know much about EV vehicles, but this sounds like a no brainer. So there must be a specific reason as to why this isn't possible, standard, and mandatory. Thanks in advance for your knowledge.

A: The motion of a car is a form of energy, and to get the car moving in the first place that energy had to come from somewhere, either fuel or batteries.
If your car is electric, energy stored in the batteries (called "chemical potential energy") is converted into motion by electric motors. Some energy, however never makes to becoming motion, some is wasted overcoming electrical resistance in the wires on the way to the motors, some is wasted overcoming friction between the wheels and road, some is wasted moving air out of the way of the car, and so on. All this wasted energy ends up eventually as heat somewhere, and isn't usable any more by the car.
There is a physical law called "conservation of energy", which says that energy is never lost, is just gets transformed from one form to another, like heat, or motion, or light. If you add up all the various quantities of energy in its various forms and places in the system of vehicle and world, you find that the total never changes, due to the law of conservation of energy. The whole system is a perfect "energy accountant". Energy just gets moved around, never created or destroyed. There's no "inflation" or "interest" in this accounting system, no potential for profit or loss, it's penny-precise accounting, always.
Some of the energy, as I mentioned is wasted. Not "lost", just changed to a form (heat) that we can no longer control, or convert back into a form we can re-use (like putting it back in the battery). Once it becomes heat, it's as good as gone to us. However, before it becomes heat, we have the technology still to manipulate it. For instance, the energy of the forward motion of the car, and the spinning motion of the wheels, called "kinetic energy", can still be "captured" and converted back into chemical potential energy inside the battery.
The recovery process is also imperfect, and no matter how hard we try to make the conversion as efficient as possible, some energy will still be wasted (converted to heat) in that recovery process. That recovery process in electric vehicles cars is called "regenerative braking", but it is not 100% efficient.
Remember always that all energy is accounted for, perfectly. This means if the car is speeding up, the energy in the battery must be depleting. If we recover energy from the car's/wheel's motion, the battery may be charging again, but the car must be slowing down. The law of conservation of energy means that the best we can hope to achieve is a 100% efficient conversion between battery energy and motion energy, or back, but the total amount of energy available in the system to do this is limited to the total energy we put in the battery in the first place! The battery/car system is a reservoir of a fixed and limited amount of energy, and our aim is simply to move energy within that limited resource back and forth between battery charge and vehicle motion.
In reality we can never achieve 100% efficient conversion from any form to any other form of energy, heat is always generated in the process, which eventually finds it's way into the environment where it's of no use to us. For every 100 watt-hours of energy you remove from the battery to make motion, perhaps 10Wh becomes unrecoverable heat, and 90Wh becomes recoverable motion. This means that usable energy reserves dwindle over time, as heat energy is radiated out of the system.
To get to your question, which was about recharging the vehicle's battery from the energy of its motion, we already do that, with regenerative braking.  However, what I aimed to clarify here is that any energy we put back into the battery in doing so, came from the battery in the first place to accelerate the car, and isn't something you "get for free" from the world (unless you're driving down hill, in which case you do have gravity providing a free "top up"). It's all energy from the reserve that you provided by initially charging the car's battery before you left home.
I hope it's also clearer now, that because of inefficiencies in the energy conversions that take place, the total energy stored in various forms in car's system (battery charge and motion) diminishes over time, and that's why you have to keep topping up the battery with energy from the grid.
Therefore, yes, it's possible to charge the battery with energy from the spinning of wheels and forward motion of the car, but that's only energy you had to provide in the first place, and by recovering it, necessarily they must slow down, in accordance with the law of conservation of energy.
Let me illustrate this with an example.
You charge your battery at home with 10,000 watt-hours of energy. Then you accelerate the car to 100kph. This requires that you withdraw 1000 watt-hours of energy from the battery, and invest that energy into motion. The universe charges you a withdrawal fee, 100 watt-hours, for that privilege, so in reality you only have 900 watt-hours-worth of motion. The 100Wh withdrawal fee is what you would see as heat, unrecoverable, and belonging to the rest of the universe now. The remaining 900Wh is still owned by you, and is manifest as vehicle/wheel motion.
You slow to 0kph, to recover those 900Wh of energy and deposit it back into your battery-bank-account, but the universe charges you a 10% fee, 90Wh for the service. What you have in the battery is now 10,000Wh of energy minus the universal charges of 100wh and 90wh. That's only 9,810Wh.
You only have 9,810Wh of chemical potential energy in your account now, and the universal bank has 190Wh of heat. Penny-precise accounting.
Occasionally the world gives you free money, like a tail-wind, or a downhill slope. It feels good to get a combined 100Wh of gift vouchers, until you realise that you have to drive upwind and uphill again at some point, to get back home. And during the deposit and withdrawal of those watt-hours into and out of your account, the universal bank screws you over again, with additional fees. In fact you had to pay in the long term, for this free lunch. There's never a free lunch. The cake is a lie.

A: They do. It's called regenerative braking.
The only time you can practically recover energy from the wheels is during braking. Taking energy from them slows them down. If you do it while they are being powered by the motors, you're just making the motors work harder. If you do it while coasting, the vehicle will quickly slow down and the driver will need to accelerate.


text:
Q: Passing array to a routine going wrong In the following code I am expecting output in ScheduleRequestWrite() to be : 5,10
sub ProcessItem
{
    my @writeVal = ("5,10");

    foreach my $str (@writeVal)
    {
        print "\nProcessItem = $str\n";
    }
    ScheduleRequestWrite(\@writeVal);
}

sub ScheduleRequestWrite()
{
   my @write_value = $_[0];

   foreach my $str (@write_value)
   {
        print "\n$str\n";
   }
}

ProcessItem();

But I am getting : ARRAY<0x2ccf8>
Could anyone please help me point out my mistake. Thanks in advance!

A: You're passing in an array reference, \@writeVal, and then using that reference in your array @write_value ... so your array @write_value has a single item in it, a reference to another array.
You may have meant my @write_value = @{$_[0]}; which makes a copy of the array, or you may have meant to loop over the original array directly:
sub ScheduleRequestWrite
{
   my $write_value = $_[0];

   foreach my $str (@$write_value)
   {
        print "\n$str\n";
   }
}

(You also don't want the () prototype since you are taking a parameter! Just leave the prototype off.)


text:
Q: Logback Keep n Days Logs With Size Based Archiving I'm trying to configure logs rolling policy for a java web application. Here is what I have so far
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/appLog.%d{yyyy-MM-dd HH}.%i.log.gz
            </fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>500MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>7</maxHistory>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>

What I'm trying to achieve here is to keep all the logs for the past 7 days, but compress log files whenever they reach 500MB.
Logback configuration shown above keeps only last 7 files, so if there are lot of logs, I can have 7 files only for the last day, for example.
How can I configure logback in this case to keep all logs for the past 7 days? Any help is really appreciated.

A:
What I'm trying to achieve here is to keep all the logs for the past 7
  days,

Here you specify a pattern that considers a rolling policy until the hour granularity :
 <fileNamePattern>${LOG_HOME}/appLog.%d{yyyy-MM-dd HH}.%i.log.gz

The fileNamePattern is much more than a file name pattern.
It indicates also the rollover frequency.

The mandatory fileNamePattern property defines the name of the
  rolled-over (archived) log files. Its value should consist of the name
  of the file, plus a suitably placed %d conversion specifier. The %d
  conversion specifier may contain a date-and-time pattern as specified
  by the java.text.SimpleDateFormat class. If the date-and-time pattern
  is omitted, then the default pattern yyyy-MM-dd is assumed. The
  rollover period is inferred from the value of fileNamePattern.

By specifying this date pattern : %d{yyyy-MM-dd HH}, for each day of the year, at each time you log something at a new hour, the actual logs are archived and a new log file is created for the new hour.
For example : all what you log between the 01/03/17 09:00 and the 01/03/17 09:59are logged in the current log file.
As soon as 01/03/17 10:00, the first log you will do, will result to a log rotation (archive actual logs in a gz file with the filename pattern specified and clear the current log file).
Besides, as you specify <maxHistory>7</maxHistory>, it will archive only 7 distinct hours.
So if your application logs at each hour something, you will archive 7 hours of your application logs and not 7 days as you wish.
If you want to have logs history for 7 days, just remove the HH in the pattern :
 <fileNamePattern>${LOG_HOME}/appLog.%d{yyyy-MM-dd}.%i.log.gz

but compress log files whenever they reach 500MB.

When in fileNamePattern you specify a compression extension as a suffix of the file as gz, zip, etc ... the compression is automatic :

Note that file compression is also specified via this property. For
  example, fileNamePattern set to MyLogFile%i.log.zip means that
  archived files must be compressed using the zip format; gz format is
  also supported.

And anyway, Logback doesn't provide a way to compress archive only when a specific condition is encountered.
Logs should be compressed or should not.
When you declare this property :
 <maxFileSize>500MB</maxFileSize>

You specify the max file size by archive.
If you don't need to set a limit in the archive size, don't specify it and leave the default value (10MB).
You can retrieve all these information in the logback appenders documentation :

A: <maxHistory>168</maxHistory> would work in such case(24*7)


text:
Q: Count excel rows from specific index to last row - Apache POI for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i++) {
    if (loc2.workbook.getNumberOfSheets() <= i) return;

    loc1.sheet = loc1.workbook.getSheetAt(i);
    loc2.sheet = loc2.workbook.getSheetAt(i);

    int num1 = loc1.sheet.getPhysicalNumberOfRows();
    int num2 = loc2.sheet.getPhysicalNumberOfRows();
}

How do I count the no. of rows starting from a specific index? The above code counts the total no. of rows. loc1 and loc2 are ref variable of the class containing workbook, sheet, row, and cell variable.

A: Well thats maybe a little bit stupid (and maybe I didnt get the difference between physical rows and logical), but
getPhysicalNumberOfRows() - specific_index;

A: You can use an Iterator to read the row.
int indexStart = 1;
Iterator<Row> rows = sheet.rowIterator();
while ( rows.hasNext() ) {
   Row row = rows.next();

   if( row.getRowNum() < indexStart  ) {
      continue;
   }

// your code
}


text:
Q: Folder Monitoring using Powershell Not writing to a folder I have set up the power shell script which is not currently writing to my outlog.txt file, can anyone see anything obvious? I am monitoring the C drive as it states in the first line.
Code:
  $folder = 'C:\Users\GeorgeH\Documents\Count' # Enter the root path you want to monitor.
  $filter = '*.*'  # You can enter a wildcard filter here.

  # In the following line, you can change 'IncludeSubdirectories to $true
  if    required.
   $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @
  {IncludeSubdirectories = $false;NotifyFilter =
   [IO.NotifyFilters]'FileName, LastWrite'}

 # Here, all three events are registerd.  You need only subscribe to events
 that you need:

 Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
 $name = $Event.SourceEventArgs.Name
 $changeType = $Event.SourceEventArgs.ChangeType
 $timeStamp = $Event.TimeGenerated
 Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
 Out-File -FilePath C:\Users\GeorgeH\outlog.txt -Append -InputObject "The
 file '$name' was $changeType at $timeStamp"}

  Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
  $name = $Event.SourceEventArgs.Name
  $changeType = $Event.SourceEventArgs.ChangeType
  $timeStamp = $Event.TimeGenerated
  Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
  Out-File -FilePath C:\Users\GeorgeH\Desktop\outlog.txt -Append -\
  InputObject "The file '$name' was $changeType at $timeStamp"}


text:
Q: Circuit Analysis Question For the circuit given in Figure Q6, calculate the total current and power of
the voltage supply, and the voltages V1 and V2. All resistors are of 1 kΩ

I have tried applying the Kirchhoff's law like this.

But i couldn't get to answer. I found the Voltage Drop between V1 1,6 Volts but i couldn't find V2.
Thanks

A: Since this is school work, direct answers are strongly discouraged.  Here is some guidance to "see" the problem more clearly.

*

*Assign reference designators to each component.  Assign a GND symbol to the 10 V negative node.

*Anywhere there are two or more resistors in series without any connections to the joining nodes, combine them.

*Anywhere there are two or more resistors in direct parallel, combine them.

*Redraw the schematic so all resistors are either vertical or horizontal.  See the way the two resistors connected to GND are spaced apart for clarity?  Do that for the +10 V node.

*Now the current paths should be easier to see and discuss.


text:
Q: Optimizing Search Results using LINQ I have a search that uses pagination. My Queries bring back more results then I can list per page. I am afraid that down the road as my site scales this could become a performance issue. I am unsure how to effectively attack this problem and was hoping for some guidance. Below is the method that i call to perform my query.
   private List<dynamic> AdminSearchAll(string keyword)
        {
            string DDL = DDLAddDivision.SelectedValue;
            int DDLInt;
            int searchID = 0;

            if (int.TryParse(DDL, out DDLInt))
            {
                //int searchID;
                if (!int.TryParse(keyword, out searchID))
                    searchID = -1;  // set to an invalid ID
            }

            ItemContext db = new ItemContext();
            var contacts = (from c in db.Contacts
            join cat in db.Categories on c.CategoryID equals cat.CategoryID
            join div in db.Divisions on c.DivisionID equals div.DivisionID

                            where
                 (DDLInt == 1 || c.DivisionID == DDLInt) &&
                    (c.Deleted == false) &&
                                //Contains
                    (
                     c.ContactName.Contains(keyword) ||
                     c.ContactEmail.Contains(keyword) ||
                     c.ContactOPhone.Contains(keyword) ||
                     c.ContactID.Equals(searchID)

                       )
                            select new
                            {

                                Name = c.ContactName,
                                Phone = c.ContactOPhone,
                                Type = c.Type,
                                Email = c.ContactEmail,
                                ID = c.ContactID

                            });
            var items = (from i in db.Item
            join cat in db.Categories on i.CategoryID equals cat.CategoryID
            join div in db.Divisions on i.DivisionID equals div.DivisionID
                         where
                           (DDLInt == 1 || i.DivisionID == DDLInt) &&
                           (i.Deleted == false) &&

                          //Contains

                     (
        i.ItemName.Contains(keyword) ||
        i.Email.Contains(keyword) ||
        i.Description.Contains(keyword) ||
        i.ItemID.Equals(searchID)
                      )
                         select new
                         {

                             Name = i.ItemName,
                             Phone = i.Phone,
                             Type = i.Type,
                             Email = i.Email,
                             ID = i.ItemID
                         });

            var all = contacts.Union(items);

            return all.ToList<dynamic>();

I use a Asp.net Data Pager for my Pagination. I display 10 results per page. My Data Pager uses a method  OnPreRender="Pager_PreRender"
protected void Pager_PreRender(object sender, EventArgs e)
        {
    if (IsPostBack)
                {

                        string keyword = txtSearch.Text.Trim();

                        List<dynamic> Cresults = AdminSearchAll(keyword);

    }
}

My question is what is the correct approach using LINQ to SQL to limit my Queries to RETURN only ten results as I page instead of returning all results and only displaying 10 because of the pager.
PS I apologize for all the code but I wanted you to see exactly what I was doing.

A: You can implement your pagination at the LINQ level instead of delegating it to the data pager, but it would take a little bit of re-coding. LINQ allows you to perform a Skip-Take operation where you can specify appropriate page sizes to, well, skip and take.
There are many ways to implement this, but since this is the only part of the code I see, here's what I would suggest.

*

*Pass your page size and current page parameters to your search method

*Order your list so that proper pagination can be done by LINQ

*Use the Skip() and Take() methods after ordering

Point #1
private List<dynamic> AdminSearchAll(string keyword, int pageSize, int currentPage)

The search method needs to accept a pageSize and currentPage parameter which will be used later.
Point #2
var all = contacts.Union(items).OrderBy(a => a.Id);

Your list needs to be ordered so that when succeeding calls to the procedure occur, you will still be able to accurately locate what set you want to extract.
Point #3
var all = contacts.Union(items).OrderBy(a => a.Id).Skip(pageSize * currentPage)
                  .Take(pageSize);

The Skip(int X) method tells LINQ that you want to pass-over the first X number of entries. In this case, we skipped pageSize * currentPage. If you're on the very first page (index 0), no items will be skipped. The Take (int X) method tells LINQ that you only want to extract X number of elements from the starting index, which corresponds to your page size.
When you return your "all.ToList()", it should only contain as many elements as indicated in your pageSize parameter. On your main application, you should be able to easily keep track of your pageSize and currentPage per session.


text:
Q: Fill dynamically-sized Rectangle with a RadialGradient sized to fit perfectly using SwiftUI in Swift 5.1 for iOS I've got a SwiftUI screen that displays data in a grid format, dynamically sizing the cells so that they always fill the width available, and making sure they are always squares.
I've got the layout working nicely, but the gradients are a little frustrating.  When creating a RadialGradient, you need to specify beginRadius and endRadius in actual screen points, rather than unit points (from 0.0 to 1.0).
Like this:
RadialGradient(gradient: item.isBlue ? self.blue : self.red,
               center: .center,
               startRadius: 0.0,
               endRadius: 100.0)

In the example above, I've picked an arbitrary size of 100 points for the endRadius.  This works just fine, but really gives the squares a different look when they are different sizes.  Check out the two examples below.
Example 1 -- 3x2 grid:

Example 2 -- 2x3 grid:

Here's all the code in an example project ContentView.swift which demonstrates clearly what I mean:
import SwiftUI

struct MyDataItem: Identifiable {
    let id: UUID = UUID()
    let text: String
    let isBlue: Bool
}

struct MyDataRow: Identifiable {
    let id: UUID = UUID()
    let items: [MyDataItem]
}

struct ContentView: View {

    @State private var datasetIndex: Int = 0
    @State private var sets = [
        // First data set
        [
            MyDataRow(items: [
                MyDataItem(text: "A", isBlue: false),
                MyDataItem(text: "B", isBlue: true),
                MyDataItem(text: "C", isBlue: true),
            ]),
            MyDataRow(items: [
                MyDataItem(text: "D", isBlue: false),
                MyDataItem(text: "E", isBlue: false),
                MyDataItem(text: "F", isBlue: false),
            ]),
        ],

        // Second data set
        [
            MyDataRow(items: [
                MyDataItem(text: "A", isBlue: false),
                MyDataItem(text: "B", isBlue: true),
            ]),
            MyDataRow(items: [
                MyDataItem(text: "C", isBlue: true),
                MyDataItem(text: "D", isBlue: false),
            ]),
            MyDataRow(items: [
                MyDataItem(text: "E", isBlue: false),
                MyDataItem(text: "F", isBlue: false),
            ]),
        ]
    ]

    var body: some View {
        VStack {
            Picker(selection: $datasetIndex, label: Text("Pick a data set")) {
                Text("Set 1").tag(0)
                Text("Set 2").tag(1)
            }.pickerStyle(SegmentedPickerStyle())
            GridThing(rows: self.$sets[self.datasetIndex])
            Spacer()
        }
    }
}

struct GridThing: View {
    @Binding var rows: [MyDataRow]

    private let spacing: CGFloat = 20.0

    let blue = Gradient(colors: [Color.blue, Color(red: 0.85, green: 0.85, blue: 1.0)])
    let red = Gradient(colors: [Color.red, Color(red: 1.0, green: 0.85, blue: 0.85)])

    var body: some View {
        VStack(alignment: .center, spacing: spacing) {
            ForEach(self.rows) { row in
                HStack(alignment: .top, spacing: self.spacing) {
                    ForEach(row.items) { item in
                        ZStack {
                            Rectangle()
                                .fill(RadialGradient(gradient: item.isBlue ? self.blue : self.red,
                                                     center: .center,
                                                     startRadius: 0.0,
                                                     endRadius: 100.0))
                                .aspectRatio(1.0, contentMode: .fit)
                            Text(item.text)
                                .foregroundColor(.black)
                        }
                    }
                }
            }
        }
    }
}

I want to have the RadialGradient use an endRadius that matches the height and width of the square.
I'd love it to be able to do this automatically.  LinearGradient, for example, takes UnitPoint for startPoint and endPoint, which would be perfect, but for RadialGradient we need to do all the work I guess.
My main thought on this is to somehow incorporate a GeometryReader.
I've tried to wrap it like this, calculating an endRadius with the GeometryReader.  This one fails because "the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions":
var body: some View {
        VStack(alignment: .center, spacing: spacing) {
            GeometryReader { geom in
            ForEach(self.rows) { row in
                HStack(alignment: .top, spacing: self.spacing) {
                    ForEach(row.items) { item in
                        ZStack {
                            Rectangle()
                                .fill(RadialGradient(gradient: item.isBlue ? self.blue : self.red,
                                                     center: .center,
                                                     startRadius: 0.0,
                                                     endRadius: (geom.size.width - (self.spacing * (row.items.count + 1))) / row.items.count))
                                .aspectRatio(1.0, contentMode: .fit)
                            Text(item.text)
                                .foregroundColor(.black)
                        }
                    }
                }
            }
            }
        }
    }

Thanks!

A: Geometry reader is correct, but instead of wrapping the whole grid, just wrapped square and then you don't need to do any extra computations: the geometry width is the width of the square and that's twice the radius of your gradient.  here's a playground:
import SwiftUI
import PlaygroundSupport

struct V: View {
  var body: some View {
    VStack(alignment: .center, spacing: 10) {
      ForEach(0..<4) { row in
        HStack(alignment: .top, spacing: 10) {
          ForEach(0..<4) { item in
            ZStack {
              GeometryReader { geometry in
                Rectangle()
                  .fill(
                    RadialGradient(
                      gradient: Gradient(colors: [Color.white, Color.red, Color.green]),
                      center: .center,
                      startRadius: 0.0,
                      endRadius: geometry.size.width / 2 )
                   )
                  .aspectRatio(1.0, contentMode: .fit)
              }
              Text("text")
                .foregroundColor(.black)
            }
          }
        }
      }
    }
  }
}

PlaygroundPage.current.setLiveView(V())


text:
Q: How to find the last 'working' day of last month? Is there a way to find the last working day of last month? I know I can get last day of last month with SELECT (date_trunc('month', now())::date - 1), but how do I get the last "weekday"?

A: I believe this does what you want:
select (date_trunc('month', current_date) + interval '1 month' -
        (case extract(dow from date_trunc('month', current_date) + interval '1 month')
              when 0 then 2
              when 1 then 3
              else 1
         end) * interval '1 day'
       ) as last_weekday_in_month

Such requests often suggest the need for a calendar table.

A: Piggy-backing off of Gordon's answer, I think this is what you want:
SELECT (
    date_trunc('month', current_date) - interval '1 day' -
    (case extract(dow from date_trunc('month', current_date) - interval '1 day')
         when 0 then 2
         when 6 then 1
         else 0
      end) * interval '1 day'
)::date as last_weekday_in_last_month;

Assuming your weekends are 0 (Sunday) and 6 (Saturday). It uses OP's original logic to find the last date of the last month, then Gordon's CASE logic to subtract more days if the last date is 0 or 6.


text:
Q: Why is using module keyword instead of name when excluding dependencies in Gradle? For adding new dependencies we can use string and map notations:
 configurationName "group:name:version:classifier" configurationName
 group: group:, name: name, version: version, classifier: classifier

To exclude dependency we use:
dependencies {
    compile("org.gradle.test.excludes:api:1.0") {
        exclude module: 'shared'
    }
}

So why we use the keyword module, not name. Is this something that comes from ANT or the reason is other?

A: I think the original author considered name a bit too vague here, so he chose module instead. (It really is the name of the module.)


text:
Q: where is cart success.phtml called? Where is the file: CartSuccess.phtml being called from when the users clicks on the "Add to cart" button on a simple product from within a category page?
I want to change the way that the Cart Success is being rendered so that it features multiple "pop-up" boxes

A: Use grep to find out where the template file is injected. Run this:
grep -rni "cart_success.phtml" /full/path/to/magento/project/http/app/

Where -r is top recursively search the directories.
Where -n option is to precede each line of output with the number of the line in the text file from which it was obtained:
Where -i is to force grep to ignore word case i.e match boo, Boo, BOO and all other combination
Hope this will help.


text:
Q: Contracting gamma matrices with explicit indices So I was calulating the matrix element of an interaction and arrived at the following contraction
$$\gamma^\mu_{ab}\gamma_{\mu\,cd}$$
With $a,b,c,d$ spinor indices that are never contracted with each other through other matrices. I know that in $D$ dimensions we have the representation independent result
$$\gamma^\mu\gamma_\mu=D$$
But that's just when the matrices are contracted with each other, which in my case they aren't. Is there a representation independent result for this contraction I need?
In Schwartz there is the relation
$$\bar u_s(p)\gamma^\mu u_{s'}(p)=2\delta_{ss'}p^\mu$$
So there must be something similar to what I want.

A: To derive an expression for $\sum_\mu\gamma^\mu_{ab}\gamma_{\mu\ cd}$, note that this is equivalent to requesting an expression for
$$
 \sum_\mu\text{trace}(X\gamma^\mu Y\gamma_\mu)
$$
for aribtrary matrices $X$ and $Y$. To derive such an expression,  express $X$ and $Y$ as sums of products of Dirac matrices (with arbitrary coefficients), and use the anticommutation relations to get an expression for
$$
 Y' := \sum_\mu\gamma^\mu Y\gamma_\mu.
$$
The keywords Fierz identities should lead you to more information about manipulations like this. The book Supergravity by Freedman and van Proeyen (2012) includes a relatively thorough treatment of such identities.

A: Let's expand on @Chiral Anomaly's answer via taking a look at a concrete example.
In 2D, one would have the traceless property:
$$
\sum_\mu\gamma^\mu\gamma^\sigma\gamma_\mu = 0
$$
which can be verified easily, e.g.
$$
\sum_\mu\gamma^\mu\gamma^0\gamma_\mu=\gamma^0\gamma^0\gamma_0 + \gamma^1\gamma^0\gamma_1 = (\gamma^0\gamma_0)\gamma^0 - (\gamma^1\gamma_1)\gamma^0= \gamma^0- \gamma^0 = 0
$$
This identity is representation-independent, since it only invokes the anti-commuting properties of the Gamma matrices. The identity can be extended to any vector $l = \sum_\sigma l_\sigma \gamma^\sigma$:
$$
\sum_\mu\gamma^\mu l\gamma_\mu = 0
$$
The identity implies that the QED vacuum polarization is traceless:
$$
\sum_{\mu\nu}\Pi^{\mu\nu}(p)g_{{\mu\nu}} \sim \sum_{\mu\nu}\int_l Tr\left(\gamma^\mu\frac{1}{\not l}\gamma^\nu\frac{1}{\not l+\not p}\right)g_{{\mu\nu}} = \int_l \frac{Tr\left(\sum_{\mu}\gamma^\mu{\not l}\gamma_\mu({\not l+\not p})\right)}{l^2(l+p)^2} = 0
$$
But for 2D massless QED (Schwinger model), it turns out that a Ward identity compatible vacuum polarization  is NOT traceless
$$
\sum_{\mu\nu}\Pi^{\mu\nu}(p)g_{{\mu\nu}} \sim \sum_{\mu\nu}(g^{{\mu\nu}} - \frac{p^\mu p^\nu}{p^2})g_{{\mu\nu}} = 2 - \frac{p^2}{p^2} = 1 \neq 0
$$
Confused? Welcome to the wonderful QFT club which is purportedly self-consistent!
Hint:
$$
0*\infty \neq 0
$$
Infinities and dimensional regularization can do magic whereby Ward identity
$$
\sum_{\nu}p_\nu \Pi^{\mu\nu}(p) \sim p^{{\mu}} - \frac{p^\mu p^2}{p^2}=0
$$
 is preserved at the cost of tracelessness.

For $D=4$, let's say you want to calculate $\sum_\mu\text{trace}(X\gamma^\mu Y\gamma_\mu)$, and Y can be expressed as:
$$
Y = AI + B^\mu\gamma_\mu + C^{\mu\nu}\gamma_\mu\gamma_\nu + D^\mu\gamma_\mu \gamma_5 + E \gamma_5,
$$
then
$$
Y' := \sum_\mu\gamma^\mu Y\gamma_\mu \\
=4AI -2 B^\mu\gamma_\mu +2 D^\mu\gamma_\mu \gamma_5 -4E \gamma_5.
$$
Note that the antisymmetric portion $C^{\mu\nu}\gamma_\mu\gamma_\nu$ drops out for $D=4$, as opposed to vector portion dropping out in 2D.
The last step is to calculate:
$$
\sum_\mu\text{trace}(X\gamma^\mu Y\gamma_\mu)= \text{trace}(XY')
$$