text:
Q: Blocking unwanted users from access another users profile data with function based view in Django I am working with some function-based views in Django. I have a custom build decorator named industry_required which allows passing by verifying a user is authenticated from an Industrial account or not.
I have some functions in views.py and their particular URL in urls.py. like:
in urls.py:
path('industryDetails/', views.industryDetails.as_view(), name='industryDetails'),
path('industry_create_report/<int:pk>/', views.industry_create_report, name='industry_create_report'),

in views.py:
@method_decorator(industry_required, name='dispatch')
class industryDetails(DetailView):
    model = Industry
    template_name = 'app/industryDetails.html'

    def get_queryset(self):
        return Industry.objects.filter(user=self.request.user)

    def get_object(self):
        return get_object_or_404(Industry, user=self.request.user)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['inserted_text'] = "inserted text from EmployeeDetails of views.py"
        context['employee_table'] = self.object.employee_set.all()
        return context

def industry_create_report(request):
    industry_create_report_dict = {

    }
    #bla bla....
    return render(request, 'app/industry_create_report.html', industry_create_report_dict)

Now my problem is when I use the DetailView, I can easily ensure that which user logged in that user can see only his DetailView profile by using the method_decorator named industry_required and get_queryset and get_object method.
But when I use the function-based view, suppose an Industrial account user with pk=1 can also see the data of pk=2 with using URL pattern (industry_create_report/2/), which is not desireable.
How can I fix it?

A: In your function based view, you need to fetch the industry using a similiar filter to what you had specified in industryDetails.get_queryset.
def function_based_view(request, pk):
    industry = get_object_or_404(Industry.objects.filter(user=self.request.user), pk=pk)


text:
Q: Как передать значение переменной из одного окна в другое Qt? Есть два окна MainWindow и Dialog. Нужно что бы при нажатии на кнопку открывалось диалоговое окно(Dialog) и из MainWindow в Dialog передавалось значение переменной "x" из MainWindow в label в Dialog.
// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_Button_clicked()
{
    QString x = "hello";
    Dialog window;
    window.setModal(true);
    window.exec();
}

// dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

A: Объяви в Dialog.h член-функцию void setLabel(const QString& x) и определи в Dialog.cpp реализацию:
void Dialog::setLabel(const QString& x)
{
    ui->label->setText(x);
}

Потом после создания объекта класса Dialog вызывай window.setLabel(x);

A: Сделайте конструктор Dialog со вторым аргументом
Dialog(QWidget *parent, QString labelText);

да и window.setModal(true); излишне его QDialog::exec() сам делает

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserialize JSON to c# object {"facet_counts":{
  "facet_queries":{},
  "facet_fields":{},
  "facet_dates":{},
  "facet_ranges":{
    "createdat":{
      "counts":[
        "2015-05-17T00:00:00Z",155,
        "2015-05-18T00:00:00Z",162,
        "2015-05-19T00:00:00Z",200,
        "2015-05-20T00:00:00Z",218,
        "2015-05-21T00:00:00Z",181,
        "2015-05-22T00:00:00Z",137],
      "gap":"+1DAY",
      "start":"2015-05-17T00:00:00Z",
      "end":"2015-05-23T00:00:00Z"}}}}

I am trying to deserialize the above json into my object but the counts part is not getting deserialized. My object is
public class FacetCounts
{
    public class Facet_Ranges
    {
        public class CreatedAt
        {
            public List<Counts> counts { get; set; }
            public class Counts
            {
                public Dictionary<string, int> count { get; set; }
            }
        }
        public CreatedAt createdat { get; set; }
    }
    public Facet_Ranges facet_ranges { get; set; }
}

I also tried removing the public Dictionary<string, int> count { get; set; } but still it fails.
My deserialize code is
objObject = JsonConvert.DeserializeObject<FacetCounts>(json);

Any help would be appreciated !!

A: public class FacetCounts
{
    public class Facet_Ranges
    {
        public class CreatedAt
        {
            public List<string> counts
            {
              get
              {
                return Counts
                  .SelectMany(pair => new[]{pair.Key, pair.Value.ToString()})
                  .ToList();
              }
              set
              {
                var pairs = new Dictionary<string, int>();
                for (var i = 0; i < value.Length / 2; ++i)
                {
                  pairs[value[2*i]] = int.Parse(value[2*i+1]);
                }
                this.Counts = pairs;
              }
            }

            [JsonIgnore]
            public Dictionary<string, int> Counts {get;set;}
        }
        public CreatedAt createdat { get; set; }
    }
    public Facet_Ranges facet_ranges { get; set; }
}

A: Your JSon is invalid.
The error is the lack of braces around the complete JSon string {}
Here is a working JSon string:
{
"facet_counts": {
    "facet_queries": {},
    "facet_fields": {},
    "facet_dates": {},
    "facet_ranges": {
        "createdat": {
            "counts": [
                "2015-05-17T00:00:00Z",
                155,
                "2015-05-18T00:00:00Z",
                162,
                "2015-05-19T00:00:00Z",
                200,
                "2015-05-20T00:00:00Z",
                218,
                "2015-05-21T00:00:00Z",
                181,
                "2015-05-22T00:00:00Z",
                137
            ],
            "gap": "+1DAY",
            "start": "2015-05-17T00:00:00Z",
            "end": "2015-05-23T00:00:00Z"
            }
        }
    }
}

I used JSon Lint for validating your JSon, and fixed error by error.
I am not sure if your C# code is correct to Deserialize your JSon, so I would recommend you to use e.g. JSon2CSharp in order to create you JSon objects in C#. Then you can fix variable names, etc.

A: Surround each item in counts with {}
"facet_counts":{
    "facet_queries":{},
    "facet_fields":{},
    "facet_dates":{},
    "facet_ranges":{
        "createdat":{
            "counts":[
                {"2015-05-17T00:00:00Z",155},
                {"2015-05-18T00:00:00Z",162},
                {"2015-05-19T00:00:00Z",200},
                {"2015-05-20T00:00:00Z",218},
                {"2015-05-21T00:00:00Z",181},
                {"2015-05-22T00:00:00Z",137}],
        "gap":"+1DAY",
        "start":"2015-05-17T00:00:00Z",
        "end":"2015-05-23T00:00:00Z"}}}

A: That isn't valid json - Your count objects need to be in {braces}.
FYI - You can also use json2csharp.com to auto-generate the c-sharp object to deserialize with, which would also highlight issues like this.

A: From JSON2CSHARP
public class Createdat
{
    public List<object> counts { get; set; }
    public string gap { get; set; }
    public string start { get; set; }
    public string end { get; set; }
}

This worked for me


text:
Q: Creating radar image from web api data To get familiar with front-end web development, I'm creating a weather app.  Most of the tutorials I found display the temperature, humidity, chance of rain, etc.
Looking at the Dark Sky API, I see the "Time Machine Request" returns observed weather conditions, and the response contains a 'precipIntensity' field:  The intensity (in inches of liquid water per hour) of precipitation occurring at the given time. This value is conditional on probability (that is, assuming any precipitation occurs at all).
So, it made me wonder about creating a 'radar image' of precipitation intensity?
Assuming other weather apis are similar, is generating a radar image of precipitation as straightforward as:

*

*Create a grid of latitude/longitude coordinates.

*Submit a request for weather data for each coordinate.

*Build a color-coded grid of received precipitation intensity values and smooth between them.

Or would that be considered a misuse of the data?
Thanks,
Mike

A: This would most likely end up in a very low resolution product. I will explain.
Weather observations come in from input sources ranging from mesonet stations, airports, and other programs like the "citizen weather observer" program. All of these thousands of inputs are input into the NOAA MADIS system, a centralized server that stores all observations. The companies that generate the API's pull the data from MADIS.
The problem with the observed conditions is twofold : one is that the stations are highly clustered in urban areas. In Texas, for example - there are 100's of stations in Central TX near the cities of San Antonio and Austin, but 100 miles west there is essentially nothing. To generate  a radar image using this method would involve extreme interpolation- and...
The second problem is observation time. The input from rain gauges are many times delayed several minutes to an hour or more. This would give inaccurate data.
If you wanted a gridded system, the best answer would be to use MRMS (multi-radar-multi-sensor) data from the NWS. It is not an API. These are .grib files that must be downloaded and processed.  This is the live viewer  and if you want to work on the data itself you can use the NOAA Weather Climate Toolkit to view and/or process by GUI or batch process (You can export to geoTIF and colorize it with GDAL tools). The actual MRMS data is located here and for the basic usage you are looking for, you could use the latest data in the "MergedReflectivityComposite" folder. (That would be how other radar apps show rain.) If you want actual precip intensity, check the "PrecipRate" folder.
For anything else except radar (warning polygons, etc) the NWS has an API that is located here.
If you have other questions, I will be happy to help.


text:
Q: HTTP post header is incorrect I am using node.js to send HTTP POST to an APP server. The email address joe@gmail.com in POST body shows up as joe%40gmail.com on APP server side. I used Content-Type text/plain in the following code but application/x-www-form-urlencoded is actually in the POST request header, according to the server log.
My earlier post has a mistake on Chrome postman results. Please ignore it, and sorry for the confusion.
I am new to this, and may have missed something obvious here. Any help is appreciated.
Here is the code:
var express = require("express");
var app = module.exports = express();
var request = require('request');
var config = require('../config');
app.post('/', function(req, res) {

    var username = req.body.name;
    var password = req.body.passwd;
    var email = req.body.email;
    console.log("email=", email);

    // connect to APP server
    var url = config.appServer;

    request( {
        uri: url,
        method: "POST",
        timeout: 10000, // 10 sec
        headers: {
            'Content-Type': 'text/plain'
        },
        form: {
            act: 'create',
            username : username,
            passwd: password,
            email: email
        }
        }, function (error, response, body) {
            // handle return here

A: That's completely normal behavior. Also you don't need to set the content-type header when using the form option with request.
Here is a short example:
request({
  uri: 'http://requestb.in/1g2xzno1',
  method: 'POST',
  timeout: 10000, // 10 sec
  form: {
    act: 'create',
    username : 'username',
    passwd: 'password',
    email: 'joe@gmail.com'
  }
  }, function (err, res, body) {
    if (err) console.log(err)
    console.log(body)
  })

You can see the results from that request here. This is what your app server receives. Then all you need to do is parse the request body on your app server (it's the string below the RAW BODY header):
var qs = require('qs')
qs.parse('act=create&username=username&passwd=password&email=joe%40gmail.com')

{ act: 'create',
  username: 'username',
  passwd: 'password',
  email: 'joe@gmail.com' }

Alternatively if you are using Express on your app server you can use the body-parser middleware that will do the same for you:
app.use(bodyParser.urlencoded({extended: true}))


text:
Q: TOAD "Never include" option doesn't work? My TOAD version is 13.3.0.181.
I set "object loading"->"Owner name" option to "Never include" BUT the schema name is still prefixes all objects I load!
Is it a bug? Or is there another option to configure?

A: I'm on 13.2.0.258 and it works properly.
Did you, by any chance, load objects from files stored on your hard disk?
Because, this option is related to objects stored in the database, e.g. when you navigate to procedures node (in the Schema Browser), double-click the procedure, and its source is then opened in the Editor.
Doing so, and having the "Owner name" option set to "Never include", will omit owner name from the source code.

As you want to exclude schema name from the "Script" tab, then:

*

*while in Schema Browser, on the right-hand side, when you navigate to the "Script" tab ...

*... click the first icon in the toolbar - its name is View/Edit Script Options

*the very first checkbox under "Create and Drop" block is Schema name - uncheck it

That should do.


text:
Q: Upgrading to struts 2.3.15.1 does not set HashMap values on action class I upgraded from 2.1.6 to 2.3.15.1 because of the security fixes available in the latest version. However, now the form field values are not posted to the Action class.
Basically, I populate the HashMap props from the JSP into the Action class, when the form is submitted. When I upgraded the struts version to 2.3.15.1 this does not work. There has been no code change. When I debugged the code, I noticed that the setProps method is not invoked. Is this not allowed anymore. Is there any workaround? As soon as I revert the struts library changes, everything works perfect. Please help.
Here is how my code looks like:
Action class:
    private Map<String, Wall> props;

    public void prepare(){
          //fill up props map here.
        }
    public String view(){
        return INPUT;
    }

    public String save(){
        myService.setProps(props);
        return INPUT;
    }

    public void setProps(Map<String, Wall> props) {
        this.props = props;
    }

    public Map<String, Wall> getProps() {
        return props;
    }

JSP:
<s:iterator value="props.entrySet()" id="prop" status="propStatus">
    <s:textfield name="props['%{#prop.key}'].value" value="%{#prop.value.value}" />
</s:iterator>

A: There have been huge changes since Struts 2.1.6. Struts 2 will not create objects for you if you don't explicitly tell it to do. The prepare method calls before the params interceptor sets props to the action, and you commented that you populate the map

//fill up props map here.

not surprisingly, that Struts not call that setter setProps because it already contains a map instance. So, it simply calls getProps. Then it should set the indexed property values to the map. But it doesn't know a type of the object that is an element of the collection to convert to, and if it should create a new object for element if it's null. By putting annotations on the props field it should solve the problem populating a map on submit.
@Element(value = Wall.class)
@CreateIfNull(value = true)
private Map<String, Wall> props = new HashMap<>();

I guess the key it will determine automatically. The same could be done if you specify it in Action-conversion.properties
Element_props=Wall
CreateIfNull_props=true

Next your JSP could be replaced to
<s:iterator value="props">
    <s:textfield name="props['%{key}'].value" />
</s:iterator>

And last the Wall class you haven't posted, should look like
public class Wall {
  String value;
  //getter and setter here
}

A: Solved it. With the new Struts versions parameter names are more restrictive. In my case, I had parameter names such as props['1.2.3'], props['a.b.c'] or props['a-b-c']. These were filtered out by the new struts. Here is the link which explains this: http://struts.apache.org/development/2.x/docs/s2-009.html. The very last part explains why the collections might stop working.
I changed the acceptParamNames in the interceptor stack to <param name="acceptParamNames">\w+((\.\w+)|(\[\d+\])|(\['\w+(\-\w+)*'\]))*</param> and it solved the issue. I got rid of the props['a.b.c'] property names so the above regex does not cover it, but it does cover props['a-b-c'].
Thanks to @Roman C for coming forward to help me.


text:
Q: Access flashvar defined in HTML from child loaded swf? ANSWER PROVIDED BELOW I have a flash var stored in my html file:
<script type="text/javascript">

    var flashvars = {

        map:"mapGAcentury21.xml"

    };

    var params = {

        menu: "false",

        scale: "noScale",

        allowFullscreen: "true",

        allowScriptAccess: "always",

        bgcolor: "#FFFFFF"

    };

    var attributes = {

        id:"REMap"

    };

    swfobject.embedSWF("REMap.swf", "altContent", "840", "630", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

</script>

I have a flash application I developed in FlashDevelop. From within this Flash application I load a file called 728x90.swf.   I can freely edit my 728x90.fla file but I do not want to change my main flash application files.
How can I access the flashvars variable from within my 728x90.swf file?
EDIT:
The following codes traced "your variable is undefined"
1. trace("your variable is " + stage.loaderInfo.parameters.flashvars);
2. trace("your variable is " + loaderInfo.parameters.flashvars);
3. trace("your variable is " + loaderInfo.parameters.flashvars.map);
4. trace("your variable is " + stage.loaderInfo.parameters.flashvars.map);

EDIT 2:
I pasted my entire javascript code into my original post. my flashvars are being passed into my main swf file called "REMap.swf" The REMap.swf
public var requestAd:URLRequest = new URLRequest("media/728x90.swf");

Then in a function the following code loads my 728x90.swf file
loaderAd.load(requestAd);
addChild(loaderAd);
loaderAd.contentLoaderInfo.addEventListener(Event.COMPLETE, promoLoaded);

A: You can get the parameters of the parent swf by calling
parent.loaderInfo.parameters

A: Your document object is a MovieClip. The flashvars associated with the MovieClip are stored in its loaderInfo.parameters property. Don't get the flashvars from stage.loaderInfo.parameters unless you want the flashvars associated with the original calling flash movie.
Edit to add:
Read about how to pass flashvars to a flash video. I'm getting the feeling that you're trying to access a JavaScript object from flash. That can be done too, you'll just need to read up on flash.external.ExternalInterface
Edit #2:
public var requestAd:URLRequest = new URLRequest("media/728x90.swf");

should probably be:
public var requestAd:URLRequest = new URLRequest("media/728x90.swf?map=mapGAcentury12.xml");

Check out what HTML is generated by the swfobject.embedSWF call. It might not be sending the flashvars correctly.

A: Simple answer:
Create a variable and name it whatever you want. I tried the following three:
var s1:String = stage.loaderInfo.parameters["map"];
var s2:String = this.root.loaderInfo.parameters["map"];
var s3:String = root.loaderInfo.parameters.map;

trace(s1 + " " + s2 + " " + s3);

The output: mapGAcentury21.xml null null
Answer:
In order to access flashvars of a parent swf from a child swf use the following code:
var s1:String = stage.loaderInfo.parameters["PLACE THE NAME OF YOUR FLASHVAR WITHIN QUOTATIONS"];
trace(s1);

A: Phil is correct that:
var s1:String = stage.loaderInfo.parameters["map"];

will work, but it will only work if the child SWF has already been added to the stage. This happens one/some frame(s?) after loading is complete.
You can listen the the event in the child like so:
public function instantiateChildClass(){
   trace(stage.loaderInfo.parameters["map"]); //throws error if this SWF has just been loaded into a parent SWF
   addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void{
   removeEventListener(Event.ADDED_TO_STAGE, init);
   trace(stage.loaderInfo.parameters["map"]); //traces map param
}


text:
Q: Fetching Max(id) in a list-partitioned table takes > 2 min to fetch data I have a table which is partitioned by a small int field.
The table looks like this:
CREATE TABLE t (
    sent         BIGINT   NOT NULL,
    received     BIGINT   NOT NULL,
    id           BIGINT   NOT NULL,
    property     SMALLINT NOT NULL ) PARTITION BY LIST (property);

And I am trying this:
 SELECT max(id) FROM t where property = ANY (ARRAY[0,1,2])

This query takes a very long time to fetch the results.
And Analyze shows:
Finalize Aggregate  (cost=127530081.31..127530081.32 rows=1 width=4)
->  Gather  (cost=127530081.09..127530081.30 rows=2 width=4)
        Workers Planned: 2
        ->  Partial Aggregate  (cost=127529081.09..127529081.10 rows=1 width=4)
              ->  Parallel Append  (cost=0.00..121341655.08 rows=2474970404 width=4)
                    ->  Parallel Seq Scan on t_0  (cost=0.00..66038474.72 rows=1463937981 width=4)
                          Filter: ((property = 0) OR (property = 1))
                    ->  Parallel Seq Scan on t_1  (cost=0.00..42928328.34 rows=1011032423 width=4)
                          Filter: ((property = 0) OR (property = 1))

But I get a very quick response when I use UNION query to do the same.
 SELECT max(max)
 FROM (
   SELECT max(id) FROM t WHERE property = 1
   UNION
   SELECT max(id) FROM transfer where property = 2
   UNION
   SELECT max(id) FROM t where property = 3
 ) as t1

How can this behaviour be explained?


text:
Q: How to reload a tableviewcontroller inside scrollview with pagination? I have several instances of Tableviewcontroller inside a Scrollview using NSMUTABLEARRAY with pagination. The basic usage of scrollview is to create instances of tableviewcontroller with different dates and display tableviews inside scrollable scrollview. Now what I am trying to achieve is to reload tableview with different data using a button at navigation?
Parent-view is Scrollview
for x=50, all the child-view is alloc and initialized null then updated with data. how when i do change a parameter. all the new pages created will make request according to the new parameter but those all loaded will stills how previous data.

A: Based on your last comment (without much more information), you could do something like this:
Call this method like so: [self reloadTableViewsInScrollView:yourScrollView];
- (void)reloadTableViewsInScrollView:(UIScrollView *)scrollView
{
    for (UITableViewController *sub in scrollView.subviews)
    {
        [sub.tableView reloadData];
    }
}

A: I am posting the answer for future results. Finally figured out after trying it hard.
   CGFloat width = scrollView.frame.size.width;
    //Getting the Current Page of ChildTableController inside scrollview
    NSInteger page = (scrollView.contentOffset.x + (0.5f * width)) / width;
    ChildTableController *child =[[ChildTableController alloc]initWithPageNumber:page];
    [child.tableView reloadData];

This is
how I did it and it works.

*

*get the width of the scrollview that was created

*round the page int from the float

*instantiate the ChildTableController at page

*reload tableview inside instance


text:
Q: Source code parsing and macro-like handling of similar constructions TL;DR VERSION: Is there a parser generator that supports the following: when some rule is reduced (I assume LALR(1) parser), then reduction isn't performed, but parser backs off and replaces input with different code using values from this rule and parses that code. Repeat if needed. So if code is "i++" and rule is "expr POST_INCR", I can do more or less:
expr POST_INCR -> "(tmp = expr; expr = expr + 1; tmp)"

So basicaly code rewriting using macros?
LONG VERSION:
I wrote yet another simple interpreted language (in Java for simplicity). It works ok, but it raised some question. Introduction is pretty long, but simple and helps to shows my problem clearly (I think).
I have "while" loop. It is pretty simple, given:
WHILE LPARE boolean_expression RPAREN statement

I generate more or less the following:
new WhileNode(boolean_expression, statement);

This creates new node that, when visited later, generates code for my virtual machine. But I also have the following:
FOR LPAREN for_init_expr SEMICOLON boolean_expression SEMICOLON for_post_expr RPAREN statement

This is "for loop" known from Java or C. From aforementioned rule I create more or less the following:
new ListNode(
    for_init_expr,
    new WhileNode(
        boolean_expression,
        new ListNode(
            statement,
            new ListNode(for_post_expr, null))))

This is of course simple transformation, from:
for (for_init ; boolean_expression ; for_post_expr)
    statement

to:
for_init
while (boolean_expression) {
    statement
    for_post_expr;
}

All is fine and dandy, but things get hairy for the following:
FOR LPAREN var_decl COLON expression RPAREN statement

This if well known and liked:
for (int x : new int[] { 1, 2 })
    print(x);

I refrain from posting code that generates AST, since basic for loop was already a little bit long, and what we get here is ever worse. This construction is equal to:
int[] tmp = new int[] { 1, 2 };
for (int it = 0 ; it < tmp.length; it = it + 1) {
    int x = tmp[it];
    print(x);
}

And since I'm not using types, I simply assume that "expression" (so right side, after COLON) is something that I can iterate over (and arrays are not iterable), I call a function on a result of this "expression" which returns instance of Iterable. So, in fact, my rewritten code isn't as simple as one above, is more or less this:
Iterator it = makeIterable(new int[] { 1, 2 });
while (it.hasNext()) {
    int x = it.next();
    print(x);
}

It doesn't look THAT bad, but note that AST for this generates three function calls and while loop. To show you what mess it is, I post what I have now:
113     | FOR LPAREN var_decl_name.v PIPE simple_value_field_or_call.o RPAREN statement.s
114                                         {: Symbol sv = ext(_symbol_v, _symbol_o);
115                                            String autoVarName = generateAutoVariableName();
116                                            Node iter = new StatementEndNode(sv, "",
117                                                new BinNode(sv, CMD.SET, "=",
118                                                    new VarDeclNode(sv, autoVarName),
119                                                    new CallNode(sv, "()",
120                                                        new BinNode(sv, CMD.DOT, ".",
121                                                            new MkIterNode(sv, o),
122                                                            new PushConstNode(sv, "iterator")))));
123                                            Node varinit = new StatementEndNode(sv, "",
124                                                new BinNode(sv, CMD.SET, "=",
125                                                    v,
126                                                    new PushConstNode(sv, "null")));
127                                            Node hasnext = new CallNode(sv, "()",
128                                                new BinNode(sv, CMD.DOT, ".",
129                                                    new VarNode(sv, autoVarName),
130                                                    new PushConstNode(sv, "hasNext")));
131                                            Node vargennext = new StatementEndNode(sv, "",
132                                                new BinNode(sv, CMD.SET, "=",
133                                                    new VarNode(sv, v.name),
134                                                    new CallNode(sv, "()",
135                                                        new BinNode(sv, CMD.DOT, ".",
136                                                            new VarNode(sv, autoVarName),
137                                                            new PushConstNode(sv, "next")))));
138                                            return new ListNode(sv, "",
139                                                new ListNode(sv, "",
140                                                    new ListNode(sv, "",
141                                                        iter
142                                                    ),
143                                                    varinit
144                                                ),
145                                                new WhileNode(sv, "while",
146                                                    hasnext,
147                                                    new ListNode(sv, "",
148                                                        new ListNode(sv, "",
149                                                            vargennext
150                                                        ),
151                                                        s)));

To answer your questions: yes, I am ashamed of this code.
QUESTION: Is there are parser generator that let's me do something about it, namely given rule:
FOR LPAREN var_decl COLON expr RPAREN statement

tell parser to rewrite it as if it was something else. I imagine that this would require some kind of LISP's macro mechanism (which is easy in lisp due to basically lack of grammar whatsoever), maybe similar to this:
FOR LPAREN var_decl COLON expr RPAREN statement =
    {   with [ x = generateAutoName(); ]
        emit [ "Iterator $x = makeIterable($expr).iterator();"
               "while (${x}.hasNext()) {"
               "$var_decl = ${x}.next();"
               "$statement"
               "}"
        ]
    }

I don't know if this is a well known problem or not, I simply don't even know what to look for - the most similar question that I found is this one: Any software for pattern-matching and -rewriting source code? but it isn't anywhere close to what I need, since it is supposed to work as a separate step and not during compilation, so it doesn't qualify.
Any help will be appreciated.

A: Perhaps you are looking for something like ANTLR's tree-rewriting rules.
You could probably make your AST construction syntax more readable by defining some helper functions. To my eye, there is a lot of redundancy (why do you need both an enumeration and a character string for an operator?) but I'm not a Java programmer.
One approach you might take:
Start with your parser, which already produces an AST. Add a lexical syntax or two to handle template arguments and gensyms. Then write an AST walker which serializes the AST into the code (either Java or bytecode) needed to regenerate the AST. Using that, you can generate the macro templates functions using your own parser, which means that it will automatically stay in sync with any changes you might make to your AST.

A: I think you are trying to bend the parser too much. You can simply build
the tree with macro in it, and then post-process the tree to replace the macros with whatever substitution you want.
You can do this by walking the resulting tree, detecting the macro nodes (or places where you want to do substitutions), and simply splicing in replacements with procedural tree hackery.  Not pretty but workable. You should able to do this with the result of any parser generator/AST building machinery.
If you want a more structured approach, you could build your AST and then use source-to-source transformations to "rewrite" the macros to their content.
Out DMS Software Reengineering Toolkit can do this, you can read more details
about what the transforms look like.
Using the DMS approach, your concept:
expr POST_INCR -> "(tmp = expr; expr = expr + 1; tmp)"

requires that you parse the original text in the conventional
way with the grammar rule:
 term = expr POST_INCR ;

You would give all these grammar rules to DMS and let it
parse the source and build your AST according to the grammar.
Then you apply a DMS rewrite to the resulting tree:
domain MyToyLanguage; -- tells DMS to use your grammar to process the rule below

rule replace_POST_INCR(e: expr): term->term
  = "\e POST_INCR" -> " (tmp = \e; \e = \e + 1; tmp) ";

The quote marks here are "domain meta quotes" rather than string literal quotes.
The text outside the double-quotes is DMS rule-syntax.  The text inside the quotes is syntax from your language (MyToyLangauge), and is parsed using the parser you provided, some special escapes for pattern variables like \e.
(You don't have to do anything  to your grammar to get this pattern-parsing capability; DMS takes care of that).
By convention with DMS, we often name literal tokens like POST_INCR
with a quoted equivalent '++' in the lexer, rather than using such a name.
Instead of
#token POST_INCR "\+\+"

the lexer rule then looks like:
#token '++'  "\+\+"

If you do that, then your grammar rule reads like:
term = expr '++' ;

and your rewrite rule now looks like:
rule replace_POST_INCR(e: expr): term->term
  = "\e++" -> " (tmp = \e; \e = \e + 1; tmp) ";

Following this convention, the grammar (lexer and BNF)
is (IMHO) a lot more readable,
and the rewrite rules are more readable too, since they stay
extremely close to the actual language syntax.


text:
Q: Triangulations dual to braided graphs? Suppose I have a 3-manifold $M$, and I write down a triangulation $T$ of $M$. Then I can also create a graph $G$ dual to this triangulation, with a node of the graph for every tetrahedron of $T$, and an edge between two nodes in $G$ for every triangular face shared by two tetrahedra in $T$. If I require that the connections of the edges in $G$ have fixed locations on the nodes, then I can define moves acting on the nodes and edges of $G$ which are equivalent to the Pachner moves on $T$. From this, I can find new graphs $G'$ which are each dual to a new triangulation $T'$ of a manifold homeomorphic to $M$.
My questions relate to the extent you can go in the other direction -- from a 4-valent graph to a triangulation of a manifold. Specifically, suppose I have a graph with all nodes having four edges embedded in $\mathbb{R}^3$, so I can have at least some of the edges be part of non-trivial braids.

*

*Are there any such braided graphs that correspond to the triangulation of a 3-manifold?

*If so, what are the restrictions on the braids that allow the duality to work both ways?

*This question is vaguer, but I am also curious about what exactly "fails" for the braided graphs that do not correspond to a 3-manifold triangulation? In other words, what obstruction due to the braid is preventing the formation of the dual triangulation from a braided 4-valent graph?

Any input or references to these equations would be greatly appreciated.

A: This is not an answer as such, but just some ideas on where to go with this. Along with my co-authors, I have looked at a very similar problem. We took the dual graph and determined exactly how to "flesh it out" so that it fully encoded the information on a particular triangulation. That is, there is a 1-to-1 correspondence between triangulations and the graph setting that we devised.
Just with the wording, I tend to use arc to mean 'edge of the dual graph' and node to mean 'vertex of the dual graph' to make things a bit clearer when reading.
In the new setting, we replace each arc of the dual graph with a "triple arc" such that each individual arc represents two edges (of distinct tetrahedron faces) which are identified in the triangulation. Then various constraints (such as the 3-manifold constraints) can be converted into this new setting.
The paper is up on arXiv at http://arxiv.org/abs/1412.2169 if you want to read further.


text:
Q: how to multiply 2 matrices (Python) Can anyone help me with this? I believe it's easy, but I don't know how to do it?
Create two matrices with elements 1,2,3,4,5 and 2,3,4,5,6 and matrix is
multiply.
I have this, but I don't know how to multiply them:
import numpy as np
a=np.arange(5).reshape(1,5)
b=np.arange(6).reshape(1,6)
print a
print b

Thanks for help.

A: If you need mathematical matrix multiplication (dot product), use numpy.dot (see examples behind the link). Note that for numpy.dot, it DOES matter if the shape of your array is (5,1) or (1,5). You can transpose your array with a.T .

A: I think your problem is that your arrays aren't what you think they are:
>>> np.arange(5).reshape(1, 5)
array([[0, 1, 2, 3, 4]])
>>> np.arange(6).reshape(1, 6)
array([[0, 1, 2, 3, 4, 5]])

Instead, you probably want:
>>> np.arange(1, 6).reshape(1, 5)
array([[1, 2, 3, 4, 5]])
>>> np.arange(2, 7).reshape(1, 5)
array([[2, 3, 4, 5, 6]])

You can then multiply them directly:
>>> a = np.arange(1, 6).reshape(1, 5)
>>> b = np.arange(2, 7).reshape(1, 5)
>>> a*b
array([[ 2,  6, 12, 20, 30]])

Note that this is for element-wise multiplication. For the dot product, see leeladam's answer.


text:
Q: jQuery Date Picker Problem on Dynamic Created HTML Table Rows After Adding new Row in Table When I Focus on Date It Shows The Date Picker But When I Choose Date it Change the date in first row of the Table How to Overcome this Problem?

*

*First Date Before Adding New Row
First Date Before Adding New Row

*Second Row Date Before Date Picking 2nd img

*Third After date Select, it Change the First One Not the Row I Wanna Change enter image description here
I'm Trying These Things- I've Also Change 'body'->document
let datepickeropt = {
            dateFormat: 'dd-mm-yy',
                         changeMonth: true,
                         changeYear: true,
                         showAnim: 'slideDown',
                         duration: 'fast',
                         yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
        }
        //$(".date_pick").datepicker(datepickeropt);
        $('body').each(function (i, element) {
            $(this).on('focus','.date_pick', function () {
                $(this).datepicker(datepickeropt);
            });
        });


text:
Q: findstr command with pipe in batch file I have tried following command to get the list of text files.
   "%svn%" list "%Path%" -R | findstr /c:".txt" > TxtFile_List.txt

But it shows "'findstr' is not recognized as an internal or external command," Error...

A: With set Path=svn://127.0.0.1:6140/svn/MirrorDB_Dec25/trunk you are overwriting the system's PATH variable. Therefore findstr.exe is not found any longer. You should consider using a different variable name.


text:
Q: Max CPU on everything I just reinstalled windows 7 ultimate 32 bit on my desktop PC, and it seems like every program I try to run maxes one of my CPUs! its ridiculous! Every time I load a web page in any browser it maxes a core until its done loading.  Every time I start any application it maxes a core, when I launch google chrome (because its multi-threaded) it maxes three cores!  This thing is supposed to be my gaming rig, but I definitely can't run any games on it like this!
I've already gotten the latest service packs for windows 7, and my device manager doesn't show any missing drivers for anything. Here are my PC specs:
4X 2.66GHz processor
4.0 GB Memory
NVidia EVGA 660 Graphics Card
1.2 combined TB of HDD (20 GB free on C drive)
Is there anything I can try to diagnose or fix this?
~~~~~~~~Edit CPU-Z~~~~~~~~~~~

A: Alright well, my new video card was the only thing that changed since the last time it was working fine and in my opinion a graphics card shouldn't have anything to do with a processor spiking all of the time.
Against my best knoledge of computer hardware I decided to replace the new video card with my old one just to see if it fixed the problem.  To my suprise it has fixed the problem.  The old video card now performs perfectly and my processors no longer spike on everything as they did with the new video card.
Does this make any sense to anyone? 0_o


text:
Q: Loop a two dimensional array in Twig I searched A LOT to find an answer. But i couldn't use any of them.
So, i have an array
array (size=1)
  0 =>
    array (size=4)
      'id' => string '1' (length=1)
      'name' => string 'Category' (length=8)
      'totalposts' => string '0' (length=1)
      'description' => string 'Twig test 123456789123456789' (length=28)

But i can't get it to show on Twig.
Here is my Twig code:
{% for category in categories %}

{{  category[loop.index].name }}{{ category[2] }} {% trans " konu." %}

<?php echo $row['description']?>

        {% else %}

<?php echo _('Hiç bir kategori bulunamadı.') ?>

                <?php if ( isset($_SESSION['privledge']) && $_SESSION['privledge'] == 10) : ?>

<? echo _('Hemen yeni bir kategori yaratabilirsin!') ?>

                <?php endif;?>

        {% endfor %}

And here is my PHP code:
$catArray = array();
$index = 0;

$result = $connection->query('SELECT * FROM category ORDER BY id ASC;');

while ($row = $result->fetch_assoc()) {
    $catArray[$index] = $row;
    $index++;
}

echo $twig->render('index.twig', array(
    'categories' => $catArray));

What should i do to show the data on Twig

A: Have you tried dropping the loop.index piece and just reference category, which should be down to just the associative properties?
{{ category.name }}


text:
Q: Solution to Triangular Systems with Cholesky Factor The answer in this post describes the solution to this linear system
$$
\begin{aligned}
Ax &= b \\
L L^{T} x &= b
\end{aligned}
$$
as solving the two triangular systems.
$$
\left \{
    \begin{aligned}
     Ly &= b \\
     L^{T} x &= y
    \end{aligned}
\right.
$$
I use this solution often and was recently asked, "what is $y$?" I commonly brush this off as being just a vector serving the provisional values for step 1, but are not of substantive interest. What we really want is the solution to $x$.
My statement is true-ish, but lacks a mathematically rigorous answer for "what is $y$?"
What might be a more sophisticated and rigorous answer for explaining what $y$ is in this solution?


text:
Q: Variety of proofs of a simple proposition in arithmetic I have a couple of simple proofs of a simple proposition and I'm curious to see the variety of different approaches others would take to prove the same thing.
Definition: The dilation of a sequence $a_1, a_2, a_3,\ldots$ by a factor $n$ is the sequence $b_1,b_2,b_3,\ldots$ for which
$$
\begin{cases}
b_{kn} = a_k & \text{for } k=1,2,3,\ldots, \\
b_j = 0 & \text{if $j$ is not a multiple of $n$.}
\end{cases}
$$
Thus the dilation of $a_1,a_2,a_3,\ldots$ by a factor of $3$ is
$$
0,\ 0,\ a_1,\ 0,\ 0,\ a_2,\ 0,\ 0,\ a_3,\ 0,\ 0,\ a_4,\ \ldots
$$
(This is not standard terminology as far as I know, so tell me if there's some standard name for this.)
Now let $\{a_k\}_{k=1}^\infty$ consist of an infinite sequence of repetitions of $1,0,0,0,1,0$ (a $\text{"}1\text{''}$ in the $1$st and $5$th positions and $\text{"}0\text{''s}$ elsewhere).  In other words $a_k$ is just the indicator that $k$ is coprime to $6$.
Now start by letting $c$ be an infinite sequence of $0$s and proceed as follows:
1. Let $n$ be the smallest index for which $c_n=0$ (thus initially $n=1$);
2. Let the new value of $c$ be $(c + \text{the dilation of } a \text{ by } n)$ (where the occurrence of $c$ inside the round brackets is the value of $c$ we had at the end of step $1$.);
3. Go back to step $1$.
This goes on forever.
Proposition: This process converges to an infinite sequence of $1$s.  (Thus, we never add $1$ to any position that was not $0$.)
As I said, I have a couple of simple proofs and I am curious to see the variety of different approaches others would take to prove the same thing.

A: Alright, here's one way that I know of.
Suppose $N$ is an infinitely large integer (oh $\ldots$ um $\ldots$ TRIGGER WARNING: If you suffer pain and distress as a result of reading something whose rigorous definition has not been stated and might be problematic, then don't read the foregoing phrase) whose prime factorization contains infinitely many $2$s and infinitely many $3$s and nothing else.  Look at the sequence
$$
\frac 1 N, \frac 2 N, \frac 3 N,\ \ldots,\ \frac{N-3} N, \frac{N-2} N, \frac{N-1} N. \tag a
$$
The first time one comes to step 2. in the algorithm, one adds $1$ in every position in $(\mathbf a)$ in which the fraction is in lowest terms.
The second time one comes to step 2., one adds a $1$ in every position in which one reduces the fraction to lowest terms only by dividing the numerator and denominator by $2$ (not including those cases in which division by $2$ reduces the fraction incompletely).
The third time one comes to step 2., one adds a $1$ in every position in which one reduces the fraction to lowest terms only by dividing the numerator and denominator by $3$ (not including those cases in which division by $3$ reduces the fraction incompletely).
The fourth time one comes to step 2., one adds a $1$ in every position in which one reduces the fraction to lowest terms only by dividing the numerator and denominator by $4$ (not including those cases in which division by $4$ reduces the fraction incompletely).
The fifth time one comes to step 2., one adds a $1$ in every position in which one reduces the fraction to lowest terms only by dividing the numerator and denominator by $6$ (not including those cases in which division by $6$ reduces the fraction incompletely).
and so on.  One reduces by dividing by $2$, or $3$, or $4$, or $6$, or $8$, or $9$, or $12$, etc.  This sequence contains all integers that have no prime factors except $2$ and $3$.  This process will never reduce a fraction that's already reduced, so it never adds a $1$ to a position more than once.
\begin{align}
& \frac{2520}{2\times2\times2\times\cdots \times 3\times3\times3\times\cdots} \\[10pt]
= {} & \frac{\overbrace{2\times2\times2}\times\overbrace{3\times3}\times35}{2\times2\times2\times\cdots \times 3\times3\times3\times\cdots} \\[10pt]
= {} & \frac{35}{\not2\times\not2\times\not2\times2\times2\times\cdots \times \not3\times\not3\times3\times3\times\cdots}
\end{align}
(It is not hard to rephrase all this in a way that doesn't mention an infinitely large integer.)
In a comment above I asked "How would you write this same argument in a way intended to make it comprehensible to secondary-school pupils while still keeping it simple?".  This is how I would do that.  So a question remains: Are there other ways, in some essential way different?

A: Let $A$ be the set of numbers whose prime factors are in $\{2;3\}$ and $B$ be the set of numbers whose prime factors are not in $\{2;3\}$.
The fundamental theorem of arithmetic implies that (as multiplicative monoids) $\Bbb N = A \times B = \bigcup_{a \in A} aB$ and so $\Bbb N$ can be partitioned into dilations of $B$ (or into dilations of $A$ too but that's not the point here)
So we need to prove that with your procedure we obtain exactly those dilations, in the same order : that $a \in A$ if and only if $a$ is not in $a'B$ for some $a' < a$ but this is easy :
if $a \in A$ then $a$ is in the $aB$ piece and not any other piece.
If $a$ is not of the form $a'b$ with $b>1$ then since it also can't be $a'.b$ for $a'>a$, its decomposition has to be $a=a.1$ and so $a \in A$.

Interestingly, if $\Bbb N = A \times B$ for some submonoids $A$ and $B$ then this shows that $B$ is completely determined by $A$ (and vice-versa)

A: Let's see. The dilation of $a_n$ with a factor $k$ (we'll write $d(a_n,k,i)$ for this, where $i$ is the index) is the following:
\begin{equation}
d(a_n,k,i)=
\begin{cases}
1 & \text{if } i=6kN\pm k\text{ for some }N\in\mathbb{Z}\\
0 & \text{otherwise}
\end{cases}
\end{equation}
Now we pick any $x\in\mathbb{N}$ and we look at for what $k$ we have $d(a_n,k,x)=1$. We see that $x=6kN\pm k$ for some $N\in\mathbb{Z}$, so $k\mid x$, and that $\frac xk\equiv \pm 1\mod 6$. For a number to be $\pm1\mod6$, it needs to be composed of primes $\pm1\mod 6$ only - that is, not $2$ or $3$. So we know that $k$ must have all the factors $2$ and $3$ that $x$ has, and $k$ may also have some additional factors $\pm1\mod6$ that $x$ has.

So we found a bunch of $k$'s that would have $d(a_n,k,x)=1$. But we have to prove that there's only one! Well, in the steps we did to get $c$, we only deligated $a_n$ by a factor $n$ if $n$ was the smallest number with $c_n=0$. We'll now prove that those $n$ are always of the form $2^a3^b$, and that all numbers of that form will be reached by $n$. We split this up into two cases.

Lemma. A number $n$ that once will be the smallest number with $c_n=0$ cannot be divisile by a number $\pm1\mod6$.

Proof. Let's assume $n$ has a divisor $\pm1\mod6$, let's call the largest such divisor $s$. But then $d(a_n,\frac ns,n)=0$, otherwise $c_n=1$. So $n\neq 6\frac nsN\pm \frac ns$ for all $N\in\mathbb{Z}$, but clearly, an $N_0$ such that $s=6N_0\pm 1$ exists (by assumption), so that $n=6\frac nsN_0\pm \frac ns$, which is a contradiction. Thus, the lemma must be true.

Lemma. A number of the form $n=2^a3^b$ will once be the smallest number such that $c_n=0$

Proof. Let's assume the lemma is false. Then we have a number $x=2^a3^b$ such that $d(a_n,y,x)=1$ for $x>y$. This means that $x=2^a3^b=6yN\pm y$ for some $N\in\mathbb{Z}$. But this means that $6N\pm1\mid 2^a3^b$, but this is impossible. Thus, the lemma must be true.

Thus, of all those $k$ that we found that have $d(a_n,k,x)=1$, only one will actually be reached as "smallest $k$ such that $c_k=0$", and that is the one with only factors $2$ and $3$ (and no factors $\pm1\mod 6$, thus, we see that, when taking the limit to an infinite amount of steps, that $c_x=1$. Since we did no assumptions for $x$, we have $c_x=1$ for all $x\in\mathbb{N}$. This completes the proof.


text:
Q: python regex: expression to match number and letters The aim is to print everything which does not end with "_C[any number+letter]".
def regexer():

import re
name_list = ['chrome_PM', 'chrome_P', 'chromerocker_C', 'chromebike_P1',
                 'chromecar_CMale', 'chromeone_C1254']

for name in name_list:
    counts_tail = re.compile('_C\d*$')
    if not counts_tail.search(name):
        print name

Output:
chrome_PM
chrome_P
chromebike_P1
chromecar_CMale

How can I edit my code to avoid printing "chromecar_CMale"?

A: _C[\da-zA-Z]*$

This should do it.

A: Change your regex like below,
>>> import re
>>> name_list = ['chrome_PM', 'chrome_P', 'chromerocker_C', 'chromebike_P1',
                 'chromecar_CMale', 'chromeone_C1254']
>>> for name in name_list:
    if re.search(r'^(?!.*(?:_C\d+|_C)$)(?=.*_C)', name):
        print(name)

chromecar_CMale

Explanation:

*

*^ Asserts that we are at the start.

*(?!.*(?:_C\d+|_C)$) This negative lookahead asserts that there wouldn't be anything like _C one or more digits or _C immediately followed by an end of the line anchor.

*(?=.*_C) Asserts that there must be a substring like _C would present.

*Match the string starts ^ only if the above conditions are satisfied.

*The above regex would be written as ^(?!.*_C(\d+)?$)(?=.*_C)

A: I would extend the regexp to accept words ([0-9a-zA-Z_]):
re.compile('_C\w+$')

Of course, that will accept any combination of letters or numbers. If you want to restrict it to letters or numbers only, you can do the following:
re.compile('_C(\d+|[a-zA-Z]+)$')

A: Let's invert the logic here. You are searching for things you don't want, and filtering them out. Instead why not search for the things you want?
Your regexp could look like this: _C[A-Za-z]+[\D], where:

*

*_C is the starting C you need

*[A-Za-z]+ matches any lower/upper case letter more than once

*[\D] excludes there being digits after the letters, thus avoiding matching stuff like chromecar_CM123. Note: capital \D is the negation of the shorthand \d
So the Python code would become something like:
import re

def regexer():
    name_list = ['chrome_PM', 'chrome_P', 'chromerocker_C', 'chromebike_P1',
             'chromecar_CMale', 'chromeone_C1254']

    counts_tail = re.compile('_C[A-Za-z]+[\D]') # Build regexp here - no need to do it in the loop
    for name in name_list:
        if counts_tail.search(name):
            print name

Here is the regexp in action:


text:
Q: Backbone - copy paste url I've created a small website by using backbone.js. It's hosted in IIS 7.
The routing:
 routes: {
            "/": "index",
            "": "index",
            "detailedpage/:id": "detailedpage",
            '*notFound': 'index'
        }

I've a problem when I try to copy/paste an url.
If I want to access directly to

http://www.anydomain.com/detailedpage/1234

it's not working. I can see in the developper tools an internal server error for 1234, path "/detailedpage".
The strange thing is if I access first to

http://www.anydomain.com/

and after copy/paste the url

http://www.anydomain.com/detailedpage/1234

it's working.
Can you please tell me if I need to enable/disable any handler in IIS?
Thank you!

A: Since backbone is doing the routing, your browser has to have the right content before its loaded.  If you wish to use pushState with Backbone, you have to trick your webserver into serving the same html page for all possible routes. The way we do that in IIS is have the .NET routing setup in such a way that loads the required backbone assets so it can do routing directly.
Alternatively, you can disable pushState in Backbone.history.start() and use hash based routing. (myurl/#/myroute)

A: These are client routes, so you begin with a #.
http://www.anydomain.com/#detailedpage/1234

A: Include a hashtag is not a solution. It's just tell to the browser what is the root url.
The root cause is probably the redirection to the index page which is not correctly working.
The solution I did is to put the html into a view in a MVC application. All requests are redirect to the same controller, which return this new view. So I'm sure that all request are redirect to the index page.


text:
Q: How to make a number triangle I'm trying to make a triangle that appears like

1
12
123
1234
12345
This code causes it to just print 1 over and over
def line(n):
    print('1' *n)

def triangle(n):
    for i in range(1,n+1):
        line(i)

A: What about (assuming Python 3):
def line(n):
    for i in range(n):
        print(i+1, end='')
    print()

A: You start with an empty string, increment it, and print it through the range.
def line(n):
    triangle = ''
    for i in range(1, n+1):
        triangle = triangle + (str(i))
        print(triangle)
        i+=1

This renders:
>>> line(5)
    1
    12
    123
    1234
    12345
>>>

A: I actually came across same issue @ College :)
Here is my solution :) :
for n in range (1, n):
x = n
for x in range(0,x):
    print(x+1, end='')
print()

Produces exactly what you asked for using nested FOR loop:
1
12
123
1234
12345


text:
Q: nested foreach loop giving weird incremental result I am planning on building an html table filled with locations followed by 2 subcategories of things, all pulled from the database and stored in a PHP array. Something weird is going on with my foreach loop.
    $loc_query = "SELECT Location FROM Locations;";
    $loc_result = $mysqli->query($loc_query);

    while($row = $loc_result->fetch_assoc()){
    $loc_results[] = $row;
    }

    foreach($loc_results as $loc){
        echo '
+
         '.$loc['Location'].'
';

        $CC_query = "SELECT Cost_Center_Category.Cost_Center_Category_Name, Cost_Center_Name,
        Locations.Location_Abbrev, Locations.Location, LC,
        FX, RR_In_LC, Hours
        FROM Cost_Centers
        LEFT JOIN Cost_Center_Category
        ON Cost_Centers.Cost_Center_Category = Cost_Center_Category.Cost_Center_Category_ID
        LEFT JOIN Locations ON Cost_Centers.Location = Locations.Location_Abbrev;";

        $CC_result = $mysqli->query($CC_query);

        while($row = $CC_result->fetch_assoc()){
            $CC_results[] = $row;
        }

        foreach ($CC_results as $result){
            switch($result['Cost_Center_Category_Name'])
            {
                case 'Strategy & Performance' :
                    echo '
+
                     '.$result['Cost_Center_Category_Name'].'
';

                    break;

            }
        }
    }

It outputs all the locations fine, but once I try to populate each location with a cost center category, it outputs something like

*

*Nuremberg

*Strategy & Performance

*Regensburg

*Strategy & Performance

*Strategy & Performance

*Sibiu

*Strategy & Performance

*Strategy & Performance

*Strategy & Performance

and it grows each time. I know it must be something to do with my logic, I've tried things like break 2 and I think I've been staring at it too long, it's probably really obvious.
Is there something wrong with the way I set up the nested loops or is it something else?

A: Reset $CC_results to empty array on every iteration of foreach loop:
foreach($loc_results as $loc) {
    $CC_results = array();

    // all other code stays the same

}


text:
Q: Formula for some specific polynomials I have the following problem:

Given the polynomial $$ P_n (x_1, ..., x_k) = x_1 ^ n + \cdots + x_k ^ n $$ I would like to give an explicit formula (that depends on $ k, n $) to write to $ P_n (x_1, ..., x_k) $ in terms of $ \sigma_1 (x_1, ..., x_k), ..., \sigma_n (x_1, ..., x_k) $ (with $\sigma_i (x_1 ,. .., x_n)$ the $i$th-elementary symmetric polynomial on $ x_1, ..., x_n $), that is, I would like to find a formula for $ s_n $, where $$ P_n (x_1, ..., x_k) = s_n (\sigma_1 (x_1, ..., x_k), ..., \sigma_n (x_1, ..., x_k)) $$

For example:

*

*$s_1 (x_1,...,x_k) = \sigma_1 (x_1,...,x_n)$

*$s_2 (x_1,...,x_k) = \sigma_1^2 (x_1,...,x_n) - 2\sigma_2 (x_1,...,x_n)$

*$s_3 (x_1,...,x_k) = \sigma_1^3 (x_1,...,x_n) +3\sigma_3 (x_1,...,x_n) - 3 \sigma_1 (x_1,...,x_n) \sigma_2 (x_1,...,x_n)$
Does anyone know how to attack this problem or have any hint?
I already tried induction and recursion but I didn't get anywhere, I don't know if my calculations are wrong


text:
Q: Determining if $973$ is prime
Without a calculator, determine if $973$ is prime or not

I was given this question to solve. I know $973$ is not prime. I was told a strategy to solve whether a number is prime or not is to test all the numbers less than the square root of $973$
So I would have to test till $32$
and i find $1,7,139$ and $973$ are factors of this number.  Basically, what I want to find out is are there any other strategies to solve this question? then i wouldn't have to check till 1-32 to see if any of the numbers are factors.

A: Another method is $973 = 1000-27$ which can be represented as $(10)^3-(3)^3$
Therefore, applying the identity that $(a)^3-(b)^3=(a-b)(a^2+b^2+ab)$, we see that
$973=(10)^3-(3)^3=(10-3)(100+9+30)=7\cdot139$

A: Not a clean method though but I used Fermat's factorization to find that,
$(31)^2<973<(32)^2$
Now applying the fact that a perfect square should end only in 0,1,4,5,6,9
, concentrate only on those numbers the difference of whose square and $973$ give these digits in the last place. Therefore concentrate only on those number whose last digit is either $2,3,7$ as the difference of squares of such numbers and 973 would end in numbers whose digits either end with $1$ or $9$.
Concentrating on such numbers and with a little bit of trial, we find that $(73)^2 - 973 = 5329 - 973 = 4356 = (66)^2$
Therefore, $973=(73-66)(73+66)=7\cdot
139$
Hence $973$ is not a prime.

A: For small numbers, there is no much better strategy than trying all prime divisors up to the square root.
Use divisibility criteria for the tiny divisors.

*

*$2$: check the last digit even;

*$3$: compute the sum of the digits (e.g. $975\to21\to3$);

*$5$: last digit must be $0$ or $5$;

*$7$: subtract twice the unit digits from the rest of the number (e.g. $973\to91\to7$);

*$11$: subtract the unit digits from the rest of the number (e.g. $2585\to253\to22$).

A: Alternatively, we can apply Fermat's Little Theorem where in if $p$ is a prime number and $a$ is any integer not divisible by $p$ then
$a^{p-1} \equiv1 \mod p$
In this case, we can chose $a$ to be $2$ so as to keep things simple.
It's not hard to see that $(2)^{10}= 1024 \equiv51\mod973$
Therefore, on applying Fermat's Little Theorem
$(2^{10})^{97}$ . $2^2$ $\equiv(51)^{97}.2^2\mod 973$ $\not\equiv1\mod 973$
Hence, $973$ is not a prime number

A: Another way, $973 = 910+63$
This gives $973 = 7.(130+9) = 7 . 139$

A: If you're good at arithmetic, you can try this without a calculator $:)$
Wilson's theorem:
$p$ prime $\iff$ $(p-1)! \equiv -1 \pmod p$.
Else, pocklington's test could be fast.


text:
Q: Element-wise absolute value of a sparse matrix How can I get the element-wise absolute value of a sparse complex matrix? In general, is it possible to map a matrix to another using a user-defined function?

A: The sparse matrix objects in scipy implement the method __abs__().  That means you can use Python's built-in abs() function.  It will dispatch the call to the __abs__() method.  For example,
In [16]: from scipy.sparse import csr_matrix

In [17]: a = csr_matrix([[1+1j, 0, 0, 0], [0, -2, 0, 0], [0, 0, 0, 0], [3-4j, 0, -5j, 0]])

In [18]: a.A
Out[18]:
array([[ 1.+1.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j, -2.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 3.-4.j,  0.+0.j,  0.-5.j,  0.+0.j]])

In [19]: b = abs(a)

In [20]: b.A
Out[20]:
array([[ 1.41421356,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  2.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ],
       [ 5.        ,  0.        ,  5.        ,  0.        ]])

A: For me the following just works
import numpy as np
from scipy import sparse

a = sparse.identity(5).tocsr() * 1j
a[2,4] = 1-1j
b = np.absolute(a)
b.A
# array([[ 1.        ,  0.        ,  0.        ,  0.        ,  0.        ],
#        [ 0.        ,  1.        ,  0.        ,  0.        ,  0.        ],
#        [ 0.        ,  0.        ,  1.        ,  0.        ,  1.41421356],
#        [ 0.        ,  0.        ,  0.        ,  1.        ,  0.        ],
#        [ 0.        ,  0.        ,  0.        ,  0.        ,  1.        ]])

# general functions: use the data attribute to access nonzeros

b.data = np.exp(b.data)
b.A
# array([[ 2.71828183,  0.        ,  0.        ,  0.        ,  0.        ],
#        [ 0.        ,  2.71828183,  0.        ,  0.        ,  0.        ],
#        [ 0.        ,  0.        ,  2.71828183,  0.        ,  4.11325038],
#        [ 0.        ,  0.        ,  0.        ,  2.71828183,  0.        ],
#        [ 0.        ,  0.        ,  0.        ,  0.        ,  2.71828183]])


text:
Q: C# Put 0 into the position of an array using System;

namespace batesMotel
{

    class Motel
    {
        int[] rooms;
        const int MAX = 21;
        int roomNumber, guests, vacate;

        static void Main()
        {
            Motel BatesMotel = new Motel();
            BatesMotel.runMotel();
            BatesMotel.showAllRooms();

        }
        //*******************************************************
        public Motel()
        {
            rooms = new int[MAX + 1];        // allow rooms from 1 to MAX
        }
        //******************************************************
        public void runMotel()
        {
            string choice = "";
            do
            {
                Console.Clear();
                Console.WriteLine("The Bates Motel");
                Console.WriteLine("===============");
                Console.WriteLine("1. Book a room");
                Console.WriteLine("2. Vacate a room");
                Console.WriteLine("3. Display ALL Room Details");
                Console.WriteLine("4. Vacate ALL rooms");
                Console.WriteLine("5. Quit");
                Console.Write("Enter your choice : ");
                choice = Console.ReadLine();
                if (choice == "1")
                {
                    bookRoom();
                }
                else if (choice == "3")
                {

                    showAllRooms();
                }
                else if (choice == "2")
                {
                    vacateOneRoom();
                }
            }
            while (choice != "5");
        }
        //*******************************************************
        public void bookRoom()
        {

            Console.WriteLine("\nThe Bates Motel");
            Console.WriteLine("===============");
            Console.WriteLine("Book a room");
            Console.Write("Enter the room number : ");
            roomNumber = Convert.ToInt32(Console.ReadLine());
            Console.Write("How many guests : ");
            guests = Convert.ToInt32(Console.ReadLine());
            rooms[roomNumber] = guests;     // make the booking
            Console.WriteLine("Room " + roomNumber + " booked for " + guests + " people");

        }
        //*******************************************************
        public void showAllRooms()
        {

            for (int i = 1; i < MAX; i++)
            {
                Console.Write("Room " + (i) + "\t\t\t" + rooms[i] + " guests \n");
            }
            Console.ReadLine();

        }
        public void vacateOneRoom()

        {
            int[] nums = new int[21];

            Console.WriteLine("Which room is being vacated");

            Console.ReadLine();
        }
    }
}

Question- I am creating a Hotel project which books people in and also books them out when leaving. I'm struggling on a certain part which asks which room you need vacating and then puts a 0 into this position in the array. I am not going to beat around the bush i don't know where to start. This is my code so far.

A:
// int[] rooms; is defined at the top of the class

public void vacateOneRoom()
{
     Console.WriteLine("Which room is being vacated");

     // simple, error prone solution
     rooms[Convert.ToInt32(Console.ReadLine()) + 1] = 0;
}

A: you're mixing things up, you need to make the Motel class a standalone class, and leave the Main method inside the main class (which is Program by default). The point here is to make the startup class static and fixed, while the Motel would hold the business logic.
int[] rooms;
const int MAX = 21;
int roomNumber, guests, vacate; // unnecessary

the array and the constant should be initialized like this :
private const int MAX = 21;
private readonly int[] rooms = new int[MAX];

the MAX is unnecessary as well, you can just set the array directly, but if you need it for readability purpose, then it would be fine.
string choice = "";
do
{
    choice = Console.ReadLine();
    if (choice == "1")
    {
        bookRoom();
    }
    else if (choice == "3")
    {

        showAllRooms();
    }
    else if (choice == "2")
    {
        vacateOneRoom();
    }
}
while (choice != "5");

two things to consider here :

*

*You're expecting an integer, so you will need to validate the input, then convert it to integer.

*considering that if user enter anything except 5 would be true, this would accept all numbers, letters, and special characters as well. While you only have 5 fixed options (1-5), you need to strict that.

Naming Convention
runMotel, bookRoom, showAllRooms, vacateOneRoom ! always use Pascal naming convention for properties, methods, classes, and global variables.
For Booking and Vacating, when you asks the user which room number, any number that the user input, you should substitute 1 from it, because the array index starts with 0. For instance, If I need to book room number 21, and you just passed that number to the array index, it would book room 22, so you would need to take 1 from it to get the correct room.
For validating the integer input, you should use int.TryParse to validate the input, if it's an integer, it would return true, and the converted value would be out resulted.
I've modified your class :
public class Motel
{
    private const int MAX = 21;
    private readonly int[] rooms = new int[MAX];

    private int GetIntegerInput()
    {
        int result;
        while (!int.TryParse(Console.ReadLine(), out result))
        {
            Console.WriteLine("Only integers accepted, please try again.");
        }
        return result;
    }

    public void ShowMenu()
    {
        Console.Clear();
        Console.WriteLine("The Bates Motel");
        Console.WriteLine("===============");
        Console.WriteLine("1. Book a room");
        Console.WriteLine("2. Vacate a room");
        Console.WriteLine("3. Display ALL Room Details");
        Console.WriteLine("4. Vacate ALL rooms");
        Console.WriteLine("5. Quit");
        Console.Write("Enter your choice : ");
    }

    public void Run()
    {
        int choice;

        do
        {
            ShowMenu();

            choice = GetIntegerInput();

            switch (choice)
            {
                case 1:
                    BookRoom();
                    break;
                case 2:
                    VacateOneRoom();
                    break;
                case 3:
                    ShowAllRooms();
                    break;
                case 4:
                    VocateAllRooms();
                    break;
                case 5:
                    Environment.Exit(0);
                    break;
                default:
                    Console.WriteLine("Only 1 to 5 are allowed.");
                    Console.ReadLine();
                    break;
            }

        }
        while (true);
    }

    public void BookRoom()
    {
        Console.Clear();
        Console.WriteLine("\nThe Bates Motel");
        Console.WriteLine("===============");
        Console.WriteLine("Book a room");
        Console.Write("Enter the room number : ");
        var roomNumber = GetIntegerInput();
        Console.Write("How many guests : ");
        var guests = GetIntegerInput();

        rooms[roomNumber - 1] = guests;     // make the booking

        Console.WriteLine("Room " + roomNumber + " booked for " + guests + " people");

    }

    public void ShowAllRooms()
    {
        Console.Clear();

        for (int i = 0; i < rooms.Length; i++)
        {
            Console.Write("Room " + (i + 1) + "\t\t\t" + rooms[i] + " guests \n");
        }

        Console.Read();
    }

    public void VacateOneRoom()
    {
        Console.Clear();
        Console.WriteLine("Which room is being vacated");
        var roomNumber = GetIntegerInput();
        rooms[roomNumber - 1] = 0;
    }

    public void VocateAllRooms()
    {
        for (int i = 0; i < rooms.Length; i++)
        {
            rooms[i] = 0;
        }

    }
}

and then you call it from the main method :
class Program
{
    static void Main(string[] args)
    {

        Motel BatesMotel = new Motel();
        BatesMotel.Run();

        Console.ReadLine();
    }
}


text:
Q: Which Eclipse to download for Java EE (having support for Tomcat 8) I have had Eclipse Kepler version which did not support Tomcat 8. I have tried doing what this post said - How to use Tomcat 8 in Eclipse?.
But I could not get the Tomcat v8. Finally I also followed this post - Running tomcat with eclipse kepler but after doing what this guy said, my eclipse no longer opens!
I would like to install a completely new Eclipse version that supports Web Development tools and has support for Tomcat 8 by default. Which one should I go for? I know there is a Eclipse IDE for Java Developers and Eclipse IDE for Java EE Developers. I should choose the latter i guess, but which version should I install? Luna, Kepler, Indigo, etc.?? Please correct me if I'm wrong but these are the names given to different version that came at different times right?

A: You can use Eclipse Luna 4.4. It offers the following features:

*

*Java EE 7 Support

*Java SE 8 Support

*Apache Tomcat 8 Support (The one you desire)

*Split Editors

You may also see this SO answer.

A: I think you should go for Juno. I am using it these days with tomcat and having no problem. I do not exactly whether it support Tomcat 8 or not as Tomcat 8 is still under development and just few releases has been made.
You can download Juno from:
http://www.eclipse.org/downloads/packages/release/juno/sr2
Thanks


text:
Q: jQuery methods not working inside Owl Carousel I have an owl carousel with various boxes rotating.
When I click on a button within the box, I want to toggle a class to a div within the same box.
It works fine when until i wrap it in an owl carousel and initialise it. After that the toggleClass method (and any other method seemingly) seems to stop working.

$(document).ready(function() {

  $('.view-offer').click(function() {

    var linkID = $(this).data('id')
    var el = '#box-' + linkID
    $(el).toggleClass('test');

    console.log(el);

  });

  $(".offers-slider").owlCarousel({
    nav: false,
    autoPlay: false,
    navText: [
      "",
      ""
    ],
    loop: true,
    dots: false,
    items: 3
  });

});

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />

    View

      Box 1

    View

      Box 2

    View

      Box 3

linkID will log to the console fine but the class will not add to element. There are no errors at all.

A: Every element in the Carousel has the same list of the box that means if you have tree boxes each item in the Carousel while containing #box-1 and #box-2 and #box-3. So you need to get the closest box to your link:

$(document).ready(function() {

  $('.view-offer').click(function() {

    var linkID = $(this).data('id')
    var el = '#box-' + linkID
    $(this).siblings(el).toggleClass('test');

    console.log(el);

  });

  $(".offers-slider").owlCarousel({
    nav: false,
    autoPlay: false,
    navText: [
      "",
      ""
    ],
    loop: true,
    dots: false,
    items: 3
  });

});

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet" />

    View

      Box 1

    View

      Box 2

    View

      Box 3


text:
Q: Longtabu in the list of tables I am using longtabu package to span a large table to multiple pages but my problem is that I get the name of this table for all pages that it span in the list of tables. I need to eliminate this and get only the first page of the longtabu referenced in the list of tables. Since I use a template, I can not be sure about the structure of the list of tables and wanted to ask if I can do anything with longtabu package. Thanks in advance.

A: Instead of the tabu-package use the package longtable and adapt  the commands of your long table. The tabu package is unmaintained, see here: https://tex.stackexchange.com/a/121847/4736 .


text:
Q: Are "ergnomic" keyboards good for you? I currently own the Logitech Classic Keyboard 200 USB Keyboard:

It is pretty comfortable, keys are soft, pretty standard layout.
Only problem is that sometimes it feels like my fingers get a little cramped (only when I think about it).
Is getting an ergonomic keyboard a wise thing to do to maintain good hand-health for the future (10-20 years)? Or is it just a marketing scheme to make more expensive keyboards with no real health benefit?
The keyboard I had in mind is the Logitech Split Keyboard:

I played around with the Microsoft Natural but the space button seems flawed and I generally dislike the quality on Microsoft products.

A: I found that you either love it or hate it. Personally I hate it. Split keyboards might be best ergonomically, but I haven't had any issues at all and much prefer a flat keyboard layout.


text:
Q: reading json file python js = {"Alex":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}, "f_":{"ep_0":"[3,4,5]", "ep_1":"[3,4,5]"}},
      "Sam":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}},
      "Joe":{"b_":{"ep_0":"[1,2,3]"}, "g_":{"ep_0":"[3,4,5]"}, "f_":{"ep_1":"[31,44,56]"}}
      }

I need to read ep_0 and ep_1 for each user, here is my snipped code:
users = [i for i in js.keys()]
data = {}
final_data = {}
for key in users:
        for user in js[key].keys():
            if 'f_' not in key:
                continue
            for z in js[users]['f_']:
                if 'ep_0' not in z:
                    continue
                data['ep0'] = js[user]['f_']['ep_0']
                if 'ep_1' not in z:
                    continue
                data['ep1'] = js[user]['f_']['ep_1']
                final_data[user] = data

    print(final_data)

the output of my code is {} and desire output should be:
{'Alex': {'f_':{'ep_0':'[3,4,5]', 'ep_1':'[3,4,5]'}}, 'Joe': { 'f_':{'ep_1':'[31,44,56]'}} }

A: Here is my simple solution to your problem.
final_data = {}
for user in js.keys():
    if 'f_' not in js[user]:
        continue
    final_data[user] = { "f_": js[user]['f_']}

print(final_data)

Output
{'Alex': {'f_': {'ep_0': '[3,4,5]', 'ep_1': '[3,4,5]'}}, 'Joe': {'f_': {'ep_1': '[31,44,56]'}}}

A: I think that your most glaring problem is
users = [i for i in js.keys()]
...
        for z in js[users]['f_']:

users is a poorly-formed list of the keys in your dict.  Just what do you expect js[users] to mean?
However, your first problem is the combination
for key in users:
    for user in js[key].keys():
        if 'f_' not in key:

users is the list of names: Alex, Sam, Joe.  How do you expect to find f_ in that list?  You've incorrectly connected your variables.

I strongly recommend that you start over with your coding.  Employ incremental programming.  Write a couple of lines that do one step of your process.  Insert print statements to test that they do what you expect.  Only after you've proved that, do you add more lines.
The problem you're facing here is that you wrote too much code at once, making several mistakes, and you're now in a situation where a single fix cannot get you any reasonable output.
Been there, done that, and I have all too many t-shirts from my forays into my own creations.

A: I'm seeing js[users] in a few places in your code. You probably mean js[user], since users is just the list of keys from js, not a key itself. Try fixing that and see if it helps you.


text:
Q: How to sort the results by a relation Dynamic Laravel and Eloquent I know that to order the elements of a relation, we use with and pass a function to tell Eloquent to order by a specific column of the relation
$query->with(['relation' => function ($query) {
    $query->orderBy('columName', 'ASC');
}]);

I try to sort and filter dynamically for relationships between tables, since I sent the relation.fieldrelation format to order or to search, as I do to do this from eloquent or QueryBuilder, so that it works dynamically and for any model and any relationship?
This method I have in a trait so that it can work for any model and for any relationship, but it does not order and search correctly, that is, to sort and search the records of the base model by the field of its relation where('relation.campo','like','$data');  and  oderBy('relacion.campo','ASC'); How can it be done using Eloquent or would I have to use queryBuilder if or what?
From the controller I call well
return Model::with('relation')->GetDataTable($request);

In my Trait method GetDataTable
public function scopeGetDataTable($query,$request)
{

    $query = $query->searching($request->search);

    if ($request->per_page == -1 ) {
        $perPage  =  $query->count();
    }else{
        $perPage  =$request->per_page;
    }

    if ($request->sortBy == 'null' ) {
        $ordercolumn ='id';
    }else{
        $ordercolumn =$request->sortBy;
    }
    $order =$request->order;
    $pos = strpos($ordercolumn, '.');
    if ($pos !== false) {
        $column = explode(".", $ordercolumn);
        return $query->with([$column[0] => function ($query)  use ($column,$order){
            $query->orderBy($column[1],$order ?? 'ASC');
        }])->paginate($perPage);
    }else{
        return  $query->orderBy($ordercolumn ?? 'id', $order ?? 'ASC')
                ->paginate($perPage);
    }
 }

in my models I have a scope
 public function scopeSearching($query, $que)
 {

        $columns = ['id','','',....];
        foreach($columns as $column){
            $query->orWhere($column, 'LIKE', "%$que%");
        }
    }
 }

A: you can do something like this
$results = \App\Country::join('currencies', 'currencies.id', '=', 'countries.currency_id')->orderBy('currencies.name')->get();

If you only want the country data withouth the currency data yo add a select to the query
$results = \App\Country::join('currencies', 'currencies.id', '=', 'countries.currency_id')->select('countries.*')->orderBy('currencies.name')->get();

This will get you all the countries that have currencies order by the currency name.
You have to change the model to your model and the relation to your relation.

A: You can use nested relation ordering and relation existing query with Eloquent.
Check Documentation
Example:
$relation_sort = 'asc';
$nested_sort = 'desc';

$result = Model::with([
   'relation' => function($query) use($relation_sort){
      $query->orderBy('relation_column', $relation_sort);
   },
   'relation.nested' => function($query) use($nested_sort){
      $query->orderBy('nested_relation_column', $nested_sort);
   }
])->whereHas('relation', function($query){
    //Relation exists check.
    $query->where('price', '>', 100);

})->whereHas('relation.nested', function($query) use($search_param){
    //Nested Relation search.
    $query->where('search_column', 'LIKE', $search_param);
})->get();


text:
Q: Sum up array values This is the array: http://www.stylechica.de/array.rtf (I can't copy it here)
I need to sum up ["PriceInformation"]["PriceInformation"]["PriceDetails"]["Price"] and allready tryed all kind of stuff like
foreach ($output["PriceInformation"]["PriceDetails"]["Price"] as $product)

echo array_sum($product);

but it just won't work. Any ideas?

A: Because $product refers to each iteration of $output["PriceInformation"]["PriceDetails"]["Price"], you can't sum the entire array like this. The best way to do it would be to add it to a variable as you go:
$your_sum = 0;
foreach($output as $value) {
    $your_sum += $value['PriceInformation']['PriceDetails']['Price'];
}
echo 'Sum: ' . $your_sum;


text:
Q: Docker compose knex script error My docker compose file looks like:
version: '2'
services:
  web:
    build:
      context: .
    image: myimage
    environment:
      - AWS_REGION=region
      - NODE_ENV=development
    command: bash -c "sleep 10 && npm run knex migrate:latest --knexfile src/knexfile.js"
    depends_on:
      - db
  db:
    image: mysql
    ports:
      - 3306:3306
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_USER=root
      - MYSQL_PASSWORD=root
      - MYSQL_DATABASE=mydb

    volumes:
        - /var/lib

The idea is that when i do a docker-compose up it spins up mysql and the does the linking as well, my requirement is that when myImage is spinning up there is some knex migration i want to executed.
Tried 2 ways:

*

*Added Command in the docker compose file as shown above.

*Without command spin up the container and then bash to the container and try running the knex migrate command.

The application image has a dependency for knex in package json file and i can see knex module present in the node modules directory as well.
However in either case i get an error for missing knex script:
npm ERR! missing script: knex

Any suggestions on above are highly appreciated.

A: Are you in correct directory with your package.json when running it?
npm run missing-script gives an error npm ERR! missing script: missing-script, if the script doesn't exist.
Do you have knex script in your package.json ?
scripts: {
  knex: "knex"
}

Have you run npm install before trying to run migrations?
Probably not this one, but might be necessary if knex script is found correctly from package.json
You might need to add -- for being able to pass parameters to npm run script
npm run knex -- migrate:latest --knexfile src/knexfile.js