问:
Can I use Laravel's eloquent hasManyThrough relationship for my specific case?
I'm trying to retrieve data from a table that I don't have a direct relationship with from the model I am currently using.

My data structure:

Table: posts

id - integer

title - string

Table: post_stacks

id - integer

post_id - integer

stack_id - integer

Table: stacks

id - integer

body - string

url - string

My eloquent model is from the Post.php (posts table) and i'm trying to get all the stacks associated to my post (from the stacks table). I want to declare my relationships only on Post.php and not my pivot table (post_stacks). I tried using hasManyThrough but i can't get it to work?

```<code>public function img()
    {
        return $this->hasManyThrough(\App\Stack::class, \App\PostStack::class, 'post_id', 'stack_id', 'id');
    }
</code>```

Would anyone know how i can retrieve my desired data? Thanks!

答:
Can you try to put below relationships on your posts model.

```<code>public function stacks()
{
    return $this->hasManyThrough(
        'App\Stacks', 'App\PostStacks',
        'post_id', 'id', 'id'
    );
}
</code>```

Also have a look at this, https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

According to this doc, The third argument in hasManyThrough is the name of the foreign key on the intermediate model. In our case 'post_id' is the foreign key on post_stack that has direct relation to posts.

Fourth argument is the name of the foreign key on the final model. ie, 'id' on stacks. that has relationship to post_stacks ( 'post_id' ). Fifth argument is the local key. ie, id of posts

Body:
I'm trying to retrieve data from a table that I don't have a direct relationship with from the model I am currently using.

My data structure:

Table: posts

id - integer

title - string

Table: post_stacks

id - integer

post_id - integer

stack_id - integer

Table: stacks

id - integer

body - string

url - string

My eloquent model is from the Post.php (posts table) and i'm trying to get all the stacks associated to my post (from the stacks table). I want to declare my relationships only on Post.php and not my pivot table (post_stacks). I tried using hasManyThrough but i can't get it to work?

public function img()
    {
        return $this->hasManyThrough(\App\Stack::class, \App\PostStack::class, 'post_id', 'stack_id', 'id');
    }

Would anyone know how i can retrieve my desired data? Thanks!

Body:
Can you try to put below relationships on your posts model.

public function stacks()
{
    return $this->hasManyThrough(
        'App\Stacks', 'App\PostStacks',
        'post_id', 'id', 'id'
    );
}

Also have a look at this, https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

According to this doc, The third argument in hasManyThrough is the name of the foreign key on the intermediate model. In our case 'post_id' is the foreign key on post_stack that has direct relation to posts.

Fourth argument is the name of the foreign key on the final model. ie, 'id' on stacks. that has relationship to post_stacks ( 'post_id' ). Fifth argument is the local key. ie, id of posts


来源: stackexchange

问:
Popover inside on Table doesn't display data
I have this table component (sap.m.Table):

```<code><Table
    inset="false"
    items="{
        path: '/SelectExpenseDetails'
    }" >
    <headerToolbar>
        <Toolbar>
            <Button icon="sap-icon://cause" press="onBack" ariaLabelledBy="Atrás" />
            <Button icon="sap-icon://message-information" press="showInfoExpenseItem" ariaLabelledBy="Atrás" />
            <Title text="{i18n>GV.APROB.EXPENSES.detail.title}" level="H2"/>

        </Toolbar>
    </headerToolbar>
    <columns>
        <Column width="7em" >
            <Text text="{i18n>GV.APROB.EXPENSES.detail.concepto.pago}" />
        </Column>

        <Column
            width="4em"
            demandPopin="true"
            hAlign="Center">
            <Text text="{i18n>GV.APROB.EXPENSES.detail.monto}" />
        </Column>

        <Column width="1.5em"
            demandPopin="true"
            hAlign="Center">

        </Column>
    </columns>
    <items>
        <ColumnListItem>

            <ObjectAttribute text="{ExpensesCategory}" />

            <ObjectNumber
                number="{PlanAmount}"
                unit="{masterExpense>/CurrencySymbol}" />

            <Button icon="sap-icon://comment" press="showCommentsExpenseDetailItem" class="sapUiTinyMarginBegin"/>
        </ColumnListItem>
    </items>
</Table>
</code>```

Function showCommentsExpenseDetailItem display the popover. Popover component is opened but it doen's display data:

Here is code:

```<code>showCommentsExpenseDetailItem: function(event){
                var popover = sap.ui.xmlfragment("la.incloud.rva.aprobaciones.view.components.popover-comment-item-detail", this);
                this.getView().addDependent(popover);
                popover.openBy(event.getSource());
            }
</code>```

And this the XML fragment:

```<code><core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
    <Popover
        showHeader="false"
        placement="Bottom">
        <TextArea value="{Comments}" growing="true" growingMaxLines="4" width="100%"/>
    </Popover>
</core:FragmentDefinition>
</code>```

I supposed that "{Comments}" is the right way of calling poperty of list items.

It seems that I'm wrong...

答:
I assume that the Comments property belongs to an entity of the SelectExpenseDetails entity set. The problem that you are facing is in fact because of an incorrect binding path.

You have attached your popup as a dependent of the view itself. This means that all its relative bindings (like the one for the text area's value) will be resolved based on the binding context of the view. If the view is not bound to anything, the binding will not be resolved.

To go around this, you should bind the popup itself to the correct path, obtained from the item which was pressed. So you should adjust your event handler like so:

showCommentsExpenseDetailItem: function(event){
    var popover = sap.ui.xmlfragment("la.incloud.rva.aprobaciones.view.components.popover-comment-item-detail", this);
    this.getView().addDependent(popover);
    popover.bindElement(event.getSource().getBindingContext().getPath());
    popover.openBy(event.getSource());
}
```

Also, you are creating a new popup each time you press the button, you might want to reuse the popup instead (either create it declaratively in the view or store it as a property of the controller).

ContentLicense: CC BY-SA 3.0

Body:
I have this table component (sap.m.Table):

    <headerToolbar>
        <Toolbar>
            <Button icon="sap-icon://cause" press="onBack" ariaLabelledBy="Atrás" />
            <Button icon="sap-icon://message-information" press="showInfoExpenseItem" ariaLabelledBy="Atrás" />
            <Title text="{i18n>GV.APROB.EXPENSES.detail.title}" level="H2"/>

        </Toolbar>
    </headerToolbar>
    <columns>
        <Column width="7em" >
            <Text text="{i18n>GV.APROB.EXPENSES.detail.concepto.pago}" />
        </Column>

        <Column
            width="4em"
            demandPopin="true"
            hAlign="Center">
            <Text text="{i18n>GV.APROB.EXPENSES.detail.monto}" />
        </Column>

        <Column width="1.5em"
            demandPopin="true"
            hAlign="Center">

        </Column>
    </columns>
    <items>
        <ColumnListItem>

            <ObjectAttribute text="{ExpensesCategory}" />

            <ObjectNumber
                number="{PlanAmount}"
                unit="{masterExpense>/CurrencySymbol}" />

            <Button icon="sap-icon://comment" press="showCommentsExpenseDetailItem" class="sapUiTinyMarginBegin"/>
        </ColumnListItem>
    </items>

Function showCommentsExpenseDetailItem display the popover. Popover component is opened but it doen's display data:

Here is code:

showCommentsExpenseDetailItem: function(event){
                var popover = sap.ui.xmlfragment("la.incloud.rva.aprobaciones.view.components.popover-comment-item-detail", this);
                this.getView().addDependent(popover);
                popover.openBy(event.getSource());
            }

And this the XML fragment:

<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
    <Popover
        showHeader="false"
        placement="Bottom">
        <TextArea value="{Comments}" growing="true" growingMaxLines="4" width="100%"/>
    </Popover>
</core:FragmentDefinition>

I supposed that "{Comments}" is the right way of calling poperty of list items.

It seems that I'm wrong...

Body:
I assume that the Comments property belongs to an entity of the SelectExpenseDetails entity set. The problem that you are facing is in fact because of an incorrect binding path.

You have attached your popup as a dependent of the view itself. This means that all its relative bindings (like the one for the text area's value) will be resolved based on the binding context of the view. If the view is not bound to anything, the binding will not be resolved.

To go around this, you should bind the popup itself to the correct path, obtained from the item which was pressed. So you should adjust your event handler like so:

showCommentsExpenseDetailItem: function(event){
    var popover = sap.ui.xmlfragment("la.incloud.rva.aprobaciones.view.components.popover-comment-item-detail", this);
    this.getView().addDependent(popover);
    popover.bindElement(event.getSource().getBindingContext().getPath());
    popover.openBy(event.getSource());
}

Also, you are creating a new popup each time you press the button, you might want to reuse the popup instead (either create it declaratively in the view or store it as a property of the controller).


问:
How to make an activity not full screen
I use this code to make an activity full screen

```<code>requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_read);
</code>```

How to I make the activity not full screen again, by a press of a button??

答:
If u change the height and width replace the values u want .8 and .85 in this code

```<code>    DisplayMetrics dm=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width=dm.widthPixels;
    int height=dm.heightPixels;
    getWindow().setLayout((int)(width*.8),(int)(height*.85));
</code>```

Note: the values not exceed 1

Title: How to make an activity not full screen

Body:
I use this code to make an activity full screen

requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_read);

How to I make the activity not full screen again, by a press of a button??

Body:
If u change the height and width replace the values u want .8 and .85 in this code

    DisplayMetrics dm=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width=dm.widthPixels;
    int height=dm.heightPixels;
    getWindow().setLayout((int)(width*.8),(int)(height*.85));

Note: the values not exceed 1


问:
Is it more performant to cache a selector in a function if that function's called multiple times?
Ok I think I know the answer to this, looking to confirm. So I have a selector that's only used once, but it's used inside a function that's called several times. From a performance perspective, since that selector is re-searched-for each time the function is called, it's probably (albeit marginally) better to cache the selector?

In other words, the below...

```<code>function testFunction() {
  alert($("#input").val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})
</code>```

...is not as performant as the below

```<code>input = $("#input")

function testFunction() {
  alert(input.val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})
</code>```

答:
Yes you are right the second one is more efficient than the first one because

In the first one to select the input filled first it going to find the input
field then it select that input field,And this will happen each time of function call.

But in second case the selector is select once when the page is loaded the it refers that selector through the variable and will not go to find that input field in each call.That why 2nd one is more efficiency.

```<code>        <input value='Value' id='input'><br>
        <span id='tt'>dssd</span><br>
        <span id='t1'></span><br>
        <span id='t2'></span>
</code>```

And Jquery:-

```<code> function testFunction1() {
        var t=$("#input").val()
        $("#tt").html(t);
    }
    console.time("jQuery() object");
    var t1=performance.now();
    for (var i = 0; i < 50000; i++) {
        testFunction1()
    }
    console.timeEnd("jQuery() object");

    var t2=performance.now();
    t2=t2-t1;
    $("#t1").html('Without selector variable:- '+t2);
    var input = $("input");
    function testFunction2() {
        var t=input.val();
        $("#tt").html(t);
    }
     t1=performance.now();
    console.time("cached jQuery() object");
    for (var i = 0; i < 50000; i++) {
        testFunction2()
    }
     t2=performance.now();
    console.timeEnd("cached jQuery() object");
    t2=t2-t1;
    $("#t2").html('With selector variable:- '+t2);
</code>```

Just Check here:-click here

Body:
Ok I think I know the answer to this, looking to confirm. So I have a selector that's only used once, but it's used inside a function that's called several times. From a performance perspective, since that selector is re-searched-for each time the function is called, it's probably (albeit marginally) better to cache the selector?

In other words, the below...

function testFunction() {
  alert($("#input").val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})

...is not as performant as the below

input = $("#input")

function testFunction() {
  alert(input.val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})

Body:
Yes you are right the second one is more efficient than the first one because

In the first one to select the input filled first it going to find the input
field then it select that input field,And this will happen each time of function call.

But in second case the selector is select once when the page is loaded the it refers that selector through the variable and will not go to find that input field in each call.That why 2nd one is more efficiency.

        <input value='Value' id='input'><br>
        <span id='tt'>dssd</span><br>
        <span id='t1'></span><br>
        <span id='t2'></span>

And Jquery:-

 function testFunction1() {
        var t=$("#input").val()
        $("#tt").html(t);
    }
    console.time("jQuery() object");
    var t1=performance.now();
    for (var i = 0; i < 50000; i++) {
        testFunction1()
    }
    console.timeEnd("jQuery() object");

    var t2=performance.now();
    t2=t2-t1;
    $("#t1").html('Without selector variable:- '+t2);
    var input = $("input");
    function testFunction2() {
        var t=input.val();
        $("#tt").html(t);
    }
     t1=performance.now();
    console.time("cached jQuery() object");
    for (var i = 0; i < 50000; i++) {
        testFunction2()
    }
     t2=performance.now();
    console.timeEnd("cached jQuery() object");
    t2=t2-t1;
    $("#t2").html('With selector variable:- '+t2);

Just Check here:-click here


问:
Spark - Exception in task
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

```<code>val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")
</code>```

First Line of the RDD

```<code>textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE
</code>```

Created a RDD by extracting the 4th column

```<code>val countRDD = textRDD.map( line => line.split("\t")(3))
</code>```

Created a pair

```<code>val pairRDD = countRDD.map(x => (x,1))
</code>```

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

```<code>val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)
</code>```

The above step is returning the below error:

```<code>17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.
</code>```

Where could I have gone wrong?

答:
There were null values in some lines in the dataset.
So, i modified the code which gave the correct result without any error.</p>

```<code>val countRDD = textRDD.map(line => {val temp = line.split("\t"); if(temp.length >= 3)temp(3)})
</code>```

Title: Spark - Exception in task

Body:
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")

First Line of the RDD

textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE

Created a RDD by extracting the 4th column

val countRDD = textRDD.map( line => line.split("\t")(3))

Created a pair

val pairRDD = countRDD.map(x => (x,1))

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)

The above step is returning the below error:

17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.

Where could I have gone wrong?

Body:
There were null values in some lines in the dataset.
So, i modified the code which gave the correct result without any error.

val countRDD = textRDD.map(line => {val temp = line.split("\t"); if(temp.length >= 3)temp(3)})


问:
Adding values for missing rows based on a column value
I have a data frame:

```<code>things <- data.frame( category = c("A","B","A","B","B","A","B"),
               things2do = c("ball","ball","bat","bat","hockey","volley ball","foos ball"),
                  number = c(12,5,4,1,2,1,1))
</code>```

now I want to add "0" in number where the particular category and things2do is missing e.g. a new row for "A", "hockey" and "0" should be added, same for volleyball, and foos ball.

I hope I can get some help here.

答:
We can do this with expand.grid from base R

```<code>d1 <- merge(expand.grid(category = unique(things$category),
        things2do = unique(things$things2do)), things, all.x = TRUE)

d1$number[is.na(d1$number)] <- 0
d1
#   category   things2do number
#1         A        ball     12
#2         A         bat      4
#3         A   foos ball      0
#4         A      hockey      0
#5         A volley ball      1
#6         B        ball      5
#7         B         bat      1
#8         B   foos ball      1
#9         B      hockey      2
#10        B volley ball      0
</code>```

NOTE: Not used any external packages

Body:
I have a data frame:

things <- data.frame( category = c("A","B","A","B","B","A","B"),
               things2do = c("ball","ball","bat","bat","hockey","volley ball","foos ball"),
                  number = c(12,5,4,1,2,1,1))

now I want to add "0" in number where the particular category and things2do is missing e.g. a new row for "A", "hockey" and "0" should be added, same for volleyball, and foos ball.

I hope I can get some help here.

Body:
We can do this with expand.grid from base R

d1 <- merge(expand.grid(category = unique(things$category),
        things2do = unique(things$things2do)), things, all.x = TRUE)

d1$number[is.na(d1$number)] <- 0
d1
#   category   things2do number
#1         A        ball     12
#2         A         bat      4
#3         A   foos ball      0
#4         A      hockey      0
#5         A volley ball      1
#6         B        ball      5
#7         B         bat      1
#8         B   foos ball      1
#9         B      hockey      2
#10        B volley ball      0

NOTE: Not used any external packages


问:
Node JS Sequelize sql associations
So still trying to figure out how to work associations and work with sequelize. Iam trying to associate a game that has multiple teams.

Game:

```<code>"use strict"
module.exports = (sequelize, DataTypes) => {
    var game =  sequelize.define('game', {
            gameId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            awayTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            homeTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            awayTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            homeTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
        },
        {
            timestamps: false,
            tableName: 'game',
                associate: function (models) {
                /// trying to figure this out
            }
        }
    );
    return game;
};
</code>```

Team:

```<code>"use strict"
module.exports = (sequelize, DataTypes) => {
    var team = sequelize.define('team', {
            teamId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false
            },
            city: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            timestamps: false,
            tableName: 'team',
            associate: function(models){
                /// trying to figure this out
            }
        }
    );

    return team;
};
</code>```

Would it be team belongsToMany games and games hasMany teams?

答:
You need to use hasMany() function, inside associate() class method.

Game:

```<code>"use strict";

var game = {};
var classmethods = {};

module.exports = (sequelize, DataTypes) => {
    game =  sequelize.define('game', {
            gameId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            awayTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            homeTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            awayTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            homeTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
        },
        {
            timestamps: false,
            classmethods: classmethods
        }
    );
    return game;
};

classmethods.associate = function (models) {
  game.hasMany(models.team, {foreignKey: 'teamId'});
};
</code>```

For this to work, you will also need to setup Sequelize this way:
https://github.com/jklepatch/kangaroojs/blob/master/apps/web/models/index.js

If you also want to be able to use the association from the team model, you would need to use 'belongsTo()` in the team model

```<code>"use strict";

var team;
var classmethods;

module.exports = (sequelize, DataTypes) => {
    team = sequelize.define('team', {
            teamId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false
            },
            city: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            timestamps: false,
            tableName: 'team',
            classmethods: classmethods
        }
    );

    return team;
};

classmethods.associate = function (models) {
  game.belongsTo(models.game);
};
</code>```

Title: Node JS Sequelize sql associations

Body:
So still trying to figure out how to work associations and work with sequelize. Iam trying to associate a game that has multiple teams.

Game:

"use strict"
module.exports = (sequelize, DataTypes) => {
    var game =  sequelize.define('game', {
            gameId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            awayTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            homeTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            awayTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            homeTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
        },
        {
            timestamps: false,
            tableName: 'game',
                associate: function (models) {
                /// trying to figure this out
            }
        }
    );
    return game;
};

Team:

"use strict"
module.exports = (sequelize, DataTypes) => {
    var team = sequelize.define('team', {
            teamId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false
            },
            city: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            timestamps: false,
            tableName: 'team',
            associate: function(models){
                /// trying to figure this out
            }
        }
    );

    return team;
};

Would it be team belongsToMany games and games hasMany teams?

Body:
You need to use hasMany() function, inside associate() class method.

Game:

"use strict";

var game = {};
var classmethods = {};

module.exports = (sequelize, DataTypes) => {
    game =  sequelize.define('game', {
            gameId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            awayTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            homeTeam: {
                type: DataTypes.INTEGER,
                references: {
                    model: "team",
                    key: 'teamId',
                },
                allowNull: false
            },
            awayTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
            homeTeamScore: {
                type: DataTypes.INTEGER,
                allowNull: false
            },
        },
        {
            timestamps: false,
            classmethods: classmethods
        }
    );
    return game;
};

classmethods.associate = function (models) {
  game.hasMany(models.team, {foreignKey: 'teamId'});
};

For this to work, you will also need to setup Sequelize this way:
https://github.com/jklepatch/kangaroojs/blob/master/apps/web/models/index.js

If you also want to be able to use the association from the team model, you would need to use 'belongsTo()` in the team model

"use strict";

var team;
var classmethods;

module.exports = (sequelize, DataTypes) => {
    team = sequelize.define('team', {
            teamId: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false
            },
            city: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            timestamps: false,
            tableName: 'team',
            classmethods: classmethods
        }
    );

    return team;
};

classmethods.associate = function (models) {
  game.belongsTo(models.game);
};


问:
How to check the text box value that exist in the database after submit the form
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

```<code><tr height="50">
    <td valign="top"><label for="CINumber"><span style="color:red">*</span>CI Name:</label></td>
     <td><input type="text" id="CINumber" name="CINumber"></td>
</tr>
</code>```

I have this ``JavaScript function for sumbmit the form values:

```<code>function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}
</code>```

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

```<code>if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}
</code>```

After that I call the PHP function that connect with the database.

```<code>function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}
</code>```

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

答:
Change following code ...

```<code>                            url: 'PHPMethodCalls_AL.php',
                            type: 'post',
                            data: {'action':'AddNewCI', 'cNumber' : cNumber },

                            success: function(data) {

                            if(data == "success"){
                                alert("CI Name can be assigned");
                                alert("Successfully Register New CI Record.");
                            }
</code>```

no need to use json_encode , you can directly echo any value if you want.

```<code>if($_POST['action'] == "AddNewCI"){
$cNumber = $_POST['cNumber'];
$newCI = AddNewCI($cNumber);
echo $newCI;
}
</code>```

change you function return value...

```<code>function AddNewCI($cNumber){
    global $DB;

        if(!empty($cNumber)){

            $namequery="SELECT Name from Item where Name='$cNumber'";
            $namecheck=mysql_query($namequery);
            $row=mysql_num_rows($namecheck);
        if($row==0){
                $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
                $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
                return "success";
            }
        else
            {
                 return "error";
            }

        }
   }
</code>```

Body:
I have this HTML Code in a form, I would like to check whether this value that user input is already exist in the database or not.

    *CI Name:
     <input type="text" id="CINumber" name="CINumber">

I have this ``JavaScript function for sumbmit the form values:

function submit(){
    var cNumber = document.getElementById("CINumber").value;
     //many form value within this function but I showed this value only cause this value need to check when click submit button.
    $.ajax({
        url: 'PHPMethodCalls_AL.php',
        type: 'post',
        data: {'action':'AddNewCI', 'cNumber' : cNumber },
        success: function(data,status) {
            //alert(data);
            if(status == "success"){
                alert("CI Name can be assigned");
                alert("Successfully Register New CI Record.");
            } else {
                alert("CI Name is already present!");
                return ;
            }
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

And I call the PHPMethod Call in the 'PHPMethodCalls_AL.php' url..

if($_POST['action'] == "AddNewCI"){
    $cNumber = $_POST['cNumber'];
    $newCI = AddNewCI($cNumber);
    echo json_encode($newCI );
}

After that I call the PHP function that connect with the database.

function AddNewCI($cNumber){
    global $DB;
    if(!empty($cNumber)){
        $namequery="SELECT Name from Item where Name='$cNumber'";
        $namecheck=mysql_query($namequery);
        $row=mysql_num_rows($namecheck);

        if($row==0){
            echo "success";
            $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
            $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
        }
        else {
            echo "!success";
        }
    }
}

After click submit, I only got the (status == "success") then pop up 2 alert box  even the data is already exist in the database. However, the duplicate value don't save in the database cause I made the UNIQUE for this fields. Please suggest me how should I do to get the the right alert box if the data was exist, show "Alredy exist" if not " show the success alert box"...

Body:
Change following code ...

                            url: 'PHPMethodCalls_AL.php',
                            type: 'post',
                            data: {'action':'AddNewCI', 'cNumber' : cNumber },

                            success: function(data) {

                            if(data == "success"){
                                alert("CI Name can be assigned");
                                alert("Successfully Register New CI Record.");
                            }

no need to use json_encode , you can directly echo any value if you want.

if($_POST['action'] == "AddNewCI"){
$cNumber = $_POST['cNumber'];
$newCI = AddNewCI($cNumber);
echo $newCI;
}

change you function return value...

function AddNewCI($cNumber){
    global $DB;

        if(!empty($cNumber)){

            $namequery="SELECT Name from Item where Name='$cNumber'";
            $namecheck=mysql_query($namequery);
            $row=mysql_num_rows($namecheck);
        if($row==0){
                $strSql1 ="INSERT INTO Item (Name)VALUES('$cNumber')";
                $res1 = $DB->Query($strSql1, false, $err_mess.__LINE__);
                return "success";
            }
        else
            {
                 return "error";
            }

        }
   }


问:
Data gets garbled when writing to csv with fputcsv() / fgetcsv()
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

```<code>$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);
</code>```

Gives me this output:

```<code>BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)
</code>```

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

答:
Using your code with specific delimiters but changing the following line will work...

```<code>$enclosure = "'";
</code>```

I think it may be to do with thinking that the \ is escaping the following quote.

Body:
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);

Gives me this output:

BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

Body:
Using your code with specific delimiters but changing the following line will work...

$enclosure = "'";

I think it may be to do with thinking that the \ is escaping the following quote.


问:
Alternative to mcrypt_encrypt?
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

```<code>$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );
</code>```

Now we are getting

```<code>mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
</code>```

Any alternative to fix this warning?

答:
Use String length 16 or 24 or 32 for variable $strKey

```<code>$strKey = 'YOUR_STRING'; #This string length should be 16 or 24 or 32
</code>```

Example :

```<code>$strKey = '1234567890abcdef';                 #Length 16
$strKey = '1234567890abcdef76hgfrdg';         #Length 24
$strKey = '1234567890abcdef1234567890abcdef'; #Length 32
</code>```

Here is the details about mcrypt_encrypt()

Alternate Solutions :

One way Hashing : crypt()

OpenSSL : openssl_encrypt()

Title: Alternative to mcrypt_encrypt?

Body:
As per the php 7.0 mcrypt_decrypt is deprecated.

I have following code.

$intSize= mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$strSize = mcrypt_create_iv( $intSize, MCRYPT_RAND );
$strText = ( true == $boolTrimText ) ? trim( $strText ) : $strText;
$strResult = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, ( string ) $strKey, ( string ) $strText, MCRYPT_MODE_ECB, $strSize) );

Now we are getting

mcrypt_encrypt(): Key of size 0 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported

Any alternative to fix this warning?

Body:
Use String length 16 or 24 or 32 for variable $strKey

$strKey = 'YOUR_STRING'; #This string length should be 16 or 24 or 32

Example :

$strKey = '1234567890abcdef';                 #Length 16
$strKey = '1234567890abcdef76hgfrdg';         #Length 24
$strKey = '1234567890abcdef1234567890abcdef'; #Length 32

Here is the details about mcrypt_encrypt()

Alternate Solutions :

One way Hashing : crypt()

OpenSSL : openssl_encrypt()


问:
how random quiz image with array android?
Hay master i want to ask to make a random quiz with array of images how yes, i've tried but can not random the whole matter.

This is his coding if anything is wrong enter code here

```<code>  Random r = new Random();
  `enter code here`int n= r.nextInt(9);
  private int [] pertanyaan={R.drawable.hidung, R.drawable.rambut,
          R.drawable.leher, R.drawable.pundak, R.drawable.telinga, R.drawable.pergelangan_kaki, R.drawable.tangan,
          R.drawable.wajah, R.drawable.lengan, R.drawable.pundak};

  public String [] pilihanganda={
          "Perhatikan gambar tersebut gambar diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Apakah yang Harus diucapkan Pada Temanmu yang Sedang Galau?",
          "asdasdasldkasldkasldkasdas",
          "dfwwqdadafasdasd",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",

          };

 private int [] pilihan_a={R.drawable.wajah, R.drawable.hidung, R.drawable.rambut, R.drawable.pergelangan_kaki,
                    R.drawable.tangan, R.drawable.rambut, R.drawable.leher, R.drawable.lengan, R.drawable.pundak
                    , R.drawable.pundak};
 private int [] pilihan_b={R.drawable.hidung, R.drawable.wajah,R.drawable.pundak, R.drawable.tangan,
                    R.drawable.pergelangan_kaki, R.drawable.leher, R.drawable.rambut, R.drawable.lengan, R.drawable.telinga
                    , R.drawable.pundak};
 private  int [] pilihan_c={R.drawable.pundak, R.drawable.lengan, R.drawable.tangan, R.drawable.hidung, R.drawable.pergelangan_kaki
                    , R.drawable.telinga, R.drawable.pergelangan_kaki, R.drawable.wajah, R.drawable.leher,
                    R.drawable.rambut};
 private  int [] pilihan_d={R.drawable.pergelangan_kaki, R.drawable.tangan, R.drawable.hidung, R.drawable.pundak,
          R.drawable.rambut, R.drawable.pundak, R.drawable.lengan, R.drawable.leher, R.drawable.telinga, R.drawable.pergelangan_kaki};

  public static String [] jawaban ={"B","C","C","A","D","B","D","D","D","B"};

   @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.quiz_2);

          soal = (ImageView)findViewById(R.id.imageButton1);
          soalnya = (TextView)findViewById(R.id.Soal);
          soal.setImageResource(pertanyaan[n]);
          soalnya.setText(pilihanganda[n]);
          imgB=(ImageButton)findViewById(R.id.pilihan2);
          imgC=(ImageButton)findViewById(R.id.pilihan3);
          imgD=(ImageButton)findViewById(R.id.pilihan4);
          imgA=(ImageButton)findViewById(R.id.pilihan1);

          imgA.setImageResource(pilihan_a[n]);
          imgA.setOnClickListener(this);
          imgB.setImageResource(pilihan_b[n]);
          imgB.setOnClickListener(this);
          imgC.setImageResource(pilihan_c[n]);
          imgC.setOnClickListener(this);
          imgD.setImageResource(pilihan_d[n]);
          imgD.setOnClickListener(this);

          nomor = (TextView) findViewById(R.id.No);
          nomor.setText("Soal " + no++);

          salahbenar =(TextView)findViewById(R.id.salahbenar);
          salahbenar.setText("");

    }
</code>```

答:
Use following code to generate random number between 0 to n. Set generated index image on ImageView:

```<code>Random r = new Random();
int i1 = r.nextInt(n- 0) + 0;
</code>```

It will include 0 and exclude n.

Body:
Hay master i want to ask to make a random quiz with array of images how yes, i've tried but can not random the whole matter.

This is his coding if anything is wrong enter code here

  Random r = new Random();
  `enter code here`int n= r.nextInt(9);
  private int [] pertanyaan={R.drawable.hidung, R.drawable.rambut,
          R.drawable.leher, R.drawable.pundak, R.drawable.telinga, R.drawable.pergelangan_kaki, R.drawable.tangan,
          R.drawable.wajah, R.drawable.lengan, R.drawable.pundak};

  public String [] pilihanganda={
          "Perhatikan gambar tersebut gambar diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Apakah yang Harus diucapkan Pada Temanmu yang Sedang Galau?",
          "asdasdasldkasldkasldkasdas",
          "dfwwqdadafasdasd",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",
          "Perhatikan gambar tersebut diatas?",

          };

 private int [] pilihan_a={R.drawable.wajah, R.drawable.hidung, R.drawable.rambut, R.drawable.pergelangan_kaki,
                    R.drawable.tangan, R.drawable.rambut, R.drawable.leher, R.drawable.lengan, R.drawable.pundak
                    , R.drawable.pundak};
 private int [] pilihan_b={R.drawable.hidung, R.drawable.wajah,R.drawable.pundak, R.drawable.tangan,
                    R.drawable.pergelangan_kaki, R.drawable.leher, R.drawable.rambut, R.drawable.lengan, R.drawable.telinga
                    , R.drawable.pundak};
 private  int [] pilihan_c={R.drawable.pundak, R.drawable.lengan, R.drawable.tangan, R.drawable.hidung, R.drawable.pergelangan_kaki
                    , R.drawable.telinga, R.drawable.pergelangan_kaki, R.drawable.wajah, R.drawable.leher,
                    R.drawable.rambut};
 private  int [] pilihan_d={R.drawable.pergelangan_kaki, R.drawable.tangan, R.drawable.hidung, R.drawable.pundak,
          R.drawable.rambut, R.drawable.pundak, R.drawable.lengan, R.drawable.leher, R.drawable.telinga, R.drawable.pergelangan_kaki};

  public static String [] jawaban ={"B","C","C","A","D","B","D","D","D","B"};

   @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.quiz_2);

          soal = (ImageView)findViewById(R.id.imageButton1);
          soalnya = (TextView)findViewById(R.id.Soal);
          soal.setImageResource(pertanyaan[n]);
          soalnya.setText(pilihanganda[n]);
          imgB=(ImageButton)findViewById(R.id.pilihan2);
          imgC=(ImageButton)findViewById(R.id.pilihan3);
          imgD=(ImageButton)findViewById(R.id.pilihan4);
          imgA=(ImageButton)findViewById(R.id.pilihan1);

          imgA.setImageResource(pilihan_a[n]);
          imgA.setOnClickListener(this);
          imgB.setImageResource(pilihan_b[n]);
          imgB.setOnClickListener(this);
          imgC.setImageResource(pilihan_c[n]);
          imgC.setOnClickListener(this);
          imgD.setImageResource(pilihan_d[n]);
          imgD.setOnClickListener(this);

          nomor = (TextView) findViewById(R.id.No);
          nomor.setText("Soal " + no++);

          salahbenar =(TextView)findViewById(R.id.salahbenar);
          salahbenar.setText("");

    }

Body:
Use following code to generate random number between 0 to n. Set generated index image on ImageView:

Random r = new Random();
int i1 = r.nextInt(n- 0) + 0;

It will include 0 and exclude n.


问:
Build FFMPEG under Cygwin in Windows OS for Android
For the past couple days, I have been trying hard to build FFMPEG for a Android project on Windows Operating System using android-ndk-14d using Cygwin.
I have followed many tutorials out there, and I ahve encountered so many errors while building FFMPEG using build_android.sh.

Here are the steps that I have taken so far.

I downloaded Cygwin and configured all the dependencies that I need for building FFMPEG.

I opened ffmpeg-3.3.1/configure file with a text editor, and changed to the following lines.

```<code>SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
LIB_INSTALL_EXTRA_CMD='$$(RANLIB) "$(LIBDIR)/$(LIBNAME)"'
SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
SLIB_INSTALL_LINKS='$(SLIBNAME)'
</code>```

my build_android.sh is as below

```<code>#!/bin/bash
NDK=C:/~/ndk-bundle
SYSROOT=$NDK/platforms/android-21/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64
function build_one
{
./configure \
    --prefix=$PREFIX \
    --enable-shared \
    --disable-static \
    --disable-doc \
    --disable-ffmpeg \
    --disable-ffplay \
    --disable-ffprobe \
    --disable-ffserver \
    --disable-avdevice \
    --disable-doc \
    --disable-symver \
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi-\
    --target-os=android \
    --arch=arm \
    --cpu=armv7-a \
    --enable-cross-compile \
    --sysroot=$SYSROOT \
    --extra-cflags="-Os -fpic $ADDI_CFLAGS" \
    --extra-ldflags="$ADDI_LDFLAGS" \
    $ADDITIONAL_CONFIGURE_FLAG
make clean
make
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
build_one
</code>```

I ran these commands

```<code>dos2unix build_android.sh
chmod +x build_android.sh
./build_android.sh
</code>```

and,,,currently getting this error

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so:1:1: syntax error,
  unexpected '!', exp         ecting $end

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so: not an object or
  archive collect2.exe: error: ld returned 1 exit status
  make: *** [library.mak:94: libswscale/libswscale-4.so] Error 1 LD

libswscale/libswscale-4.so
  c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so:1:1: syntax error,
  unexpected '!', exp         ecting $end

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux->androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so: not an object or
  archive collect2.exe: error: ld returned 1 exit status make: ***
  [library.mak:94: libswscale/libswscale-4.so] Error 1

How to compile ffmpeg-2.5.3 on windows with android-ndk-r10d

From the comments that were commented on the above link, it seems like it is
easier to build FFMPEG in Linux/Unix OS. My first can be a dumb question. But If there is anyone who can guide me through this, i will be really appreciated it.

If I build FFMPEG on Linux for Android, could I possibly copy or move those
  resulted output (The arm/lib folder contains the shared libraries, while arm/include folder contains the header files for libavcodec, libavformat, libavfilter, libavutil, libswscale etc.) to Windows OS and utilize them for
  my Android project?

Since my company only provides Windows OS for a project, I have to utilize them on Windows OS.

Thank you for your time, and if there is any feedback that you can provide it will definitely be helpful.

For the reference, here is my config.log

END c:/ffmpegtmp/ffconf.qoBF6X98.c
  C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -c -o c:/ffmpegtmp/ffconf.8joa74tC.o

c:/ffmpegtmp/ffconf.qoBF6X98.c
  check_cflags -fdiagnostics-color=auto test_cflags
  -fdiagnostics-color=auto check_cc -fdiagnostics-color=auto BEGIN c:/ffmpegtmp/ffconf.qoBF6X98.c
      1 int x; END c:/ffmpegtmp/ffconf.qoBF6X98.c C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -fdiagnostics-color=auto -c -o c:/ffmpegtmp/ffconf.8joa74tC.o c:/ffmpegtmp/ffconf.qoBF6X98.c test_cflags -Wmaybe-uninitialized check_cc -Wmaybe-uninitialized BEGIN

c:/ffmpegtmp/ffconf.qoBF6X98.c
      1 int x; END c:/ffmpegtmp/ffconf.qoBF6X98.c C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -fdiagnostics-color=auto -Wmaybe-uninitialized -c -o c:/ffmpegtmp/ffconf.8joa74tC.o c:/ffmpegtmp/ffconf.qoBF6X98.c

答:
If you use the same compiler version with the same ABI (application binary interface) then it should be no problem. I have done so with RISC-V libraries before and I imagine it's no different with ARM. </p>

<p>In fact that's exactly what you're doing on Windows with the Android NDK, compiling ARM binaries to run on Linux! Whether you crosscompile FFMPEG on Windows or Linux you still end up with the same binaries that are able to run on the same Android system. </p>

Body:
For the past couple days, I have been trying hard to build FFMPEG for a Android project on Windows Operating System using android-ndk-14d using Cygwin.
I have followed many tutorials out there, and I ahve encountered so many errors while building FFMPEG using build_android.sh.

Here are the steps that I have taken so far.

I downloaded Cygwin and configured all the dependencies that I need for building FFMPEG.

I opened ffmpeg-3.3.1/configure file with a text editor, and changed to the following lines.

SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
LIB_INSTALL_EXTRA_CMD='$$(RANLIB) "$(LIBDIR)/$(LIBNAME)"'
SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
SLIB_INSTALL_LINKS='$(SLIBNAME)'

my build_android.sh is as below

#!/bin/bash
NDK=C:/~/ndk-bundle
SYSROOT=$NDK/platforms/android-21/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64
function build_one
{
./configure \
    --prefix=$PREFIX \
    --enable-shared \
    --disable-static \
    --disable-doc \
    --disable-ffmpeg \
    --disable-ffplay \
    --disable-ffprobe \
    --disable-ffserver \
    --disable-avdevice \
    --disable-doc \
    --disable-symver \
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi-\
    --target-os=android \
    --arch=arm \
    --cpu=armv7-a \
    --enable-cross-compile \
    --sysroot=$SYSROOT \
    --extra-cflags="-Os -fpic $ADDI_CFLAGS" \
    --extra-ldflags="$ADDI_LDFLAGS" \
    $ADDITIONAL_CONFIGURE_FLAG
make clean
make
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
build_one

I ran these commands

dos2unix build_android.sh
chmod +x build_android.sh
./build_android.sh

and,,,currently getting this error

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so:1:1: syntax error,
  unexpected '!', exp         ecting $end

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so: not an object or
  archive collect2.exe: error: ld returned 1 exit status
  make: *** [library.mak:94: libswscale/libswscale-4.so] Error 1 LD

libswscale/libswscale-4.so
  c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so:1:1: syntax error,
  unexpected '!', exp         ecting $end

c:/users/sonic/appdata/local/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/p
  rebuilt/windows-x86_64/bin/../lib/gcc/arm-linux->androideabi/4.9.x/../../../../arm-linux-an
  droideabi/bin/ld.exe: error: libavutil/libavutil.so: not an object or
  archive collect2.exe: error: ld returned 1 exit status make: ***
  [library.mak:94: libswscale/libswscale-4.so] Error 1

How to compile ffmpeg-2.5.3 on windows with android-ndk-r10d

From the comments that were commented on the above link, it seems like it is
easier to build FFMPEG in Linux/Unix OS. My first can be a dumb question. But If there is anyone who can guide me through this, i will be really appreciated it.

If I build FFMPEG on Linux for Android, could I possibly copy or move those
  resulted output (The arm/lib folder contains the shared libraries, while arm/include folder contains the header files for libavcodec, libavformat, libavfilter, libavutil, libswscale etc.) to Windows OS and utilize them for
  my Android project?

Since my company only provides Windows OS for a project, I have to utilize them on Windows OS.

Thank you for your time, and if there is any feedback that you can provide it will definitely be helpful.

For the reference, here is my config.log

END c:/ffmpegtmp/ffconf.qoBF6X98.c
  C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -c -o c:/ffmpegtmp/ffconf.8joa74tC.o

c:/ffmpegtmp/ffconf.qoBF6X98.c
  check_cflags -fdiagnostics-color=auto test_cflags
  -fdiagnostics-color=auto check_cc -fdiagnostics-color=auto BEGIN c:/ffmpegtmp/ffconf.qoBF6X98.c
      1 int x; END c:/ffmpegtmp/ffconf.qoBF6X98.c C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -fdiagnostics-color=auto -c -o c:/ffmpegtmp/ffconf.8joa74tC.o c:/ffmpegtmp/ffconf.qoBF6X98.c test_cflags -Wmaybe-uninitialized check_cc -Wmaybe-uninitialized BEGIN

c:/ffmpegtmp/ffconf.qoBF6X98.c
      1 int x; END c:/ffmpegtmp/ffconf.qoBF6X98.c C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-gcc --sysroot=C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/

-isysroot C:/Users/sonic/AppData/Local/Android/sdk/ndk-bundle/platforms/android-9/arch-arm/
  -D_ISOC99_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -Dstrtod=avpriv_strtod -DPIC -Os -fpic -marm -march=armv7-a -std=c11 -fomit-frame-pointer -fPIC -marm -pthread -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -fno-tree-vectorize -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -fdiagnostics-color=auto -Wmaybe-uninitialized -c -o c:/ffmpegtmp/ffconf.8joa74tC.o c:/ffmpegtmp/ffconf.qoBF6X98.c

Body:
If you use the same compiler version with the same ABI (application binary interface) then it should be no problem. I have done so with RISC-V libraries before and I imagine it's no different with ARM.

In fact that's exactly what you're doing on Windows with the Android NDK, compiling ARM binaries to run on Linux! Whether you crosscompile FFMPEG on Windows or Linux you still end up with the same binaries that are able to run on the same Android system.


问:
How to loop input type name in php
I have 2 different dynamic input type which is name[], id[]
now i want to get all the data to update all the values into the database

Here is my code:

```<code>    $data = $_POST['name'];
$data1 = $_POST['id'];
print_r($data);
echo "<br>";

echo $data[0];
</code>```

Result:

```<code>    Array ( [0] => Array ( [81] => 3 ) [1] => Array ( [82] => 3 ) [2] => Array ( [83] => 3 ) )
</code>```

Now how to get the 81 which is the id and 3 which is the value an so on for a single loop?

Any suggestion

答:
try this dude

```<code>foreach($data as $row) {
   foreach($row[0] as $k) {
         echo $k;
   }
</code>```

}

but if you need to get all the datas use this

```<code>foreach($data as $row) {
   foreach($row as $k) {
         echo $k;
   }
    UPDATE Query here
}
</code>```

Title: How to loop input type name in php

Body:
I have 2 different dynamic input type which is name[], id[]
now i want to get all the data to update all the values into the database

Here is my code:

    $data = $_POST['name'];
$data1 = $_POST['id'];
print_r($data);
echo "
";

echo $data[0];

Result:

    Array ( [0] => Array ( [81] => 3 ) [1] => Array ( [82] => 3 ) [2] => Array ( [83] => 3 ) )

Now how to get the 81 which is the id and 3 which is the value an so on for a single loop?

Any suggestion

Body:
try this dude

foreach($data as $row) {
   foreach($row[0] as $k) {
         echo $k;
   }

}

but if you need to get all the datas use this

foreach($data as $row) {
   foreach($row as $k) {
         echo $k;
   }
    UPDATE Query here
}


问:
Using variables to specify a part of a file name in CMD
I'm trying to move files from one portion a system to another using an inputted variable but for some reason xcopy won't use wildcards or variables. </p>

```<code>set /p EIID = "Enter Aircraft EI_ID:"

xcopy C:\ULLSA\Data\ARCHIVE\IN\"%EIID%.LogbookData.qep" E:\ULLS_MEDIA\Data\3rdParty\ARCHIVE

xcopy C:\ULLSA\Data\ARCHIVE\IN\"%EIID%.LogbookData.qep" "E:\ULLS_MEDIA\Data\MigOut\%EIID%"
</code>```

答:
Have a go at this one mate. No need to quotations unless you believe there will be spaces in the file path. Also close your file path otherwise it wont work bud.</p>

```<code>set /p EIID=Enter Aircraft EI_ID:

xcopy C:\ULLSA\Data\ARCHIVE\IN\%EIID%.LogbookData.qep E:\ULLS_MEDIA\Data\3rdParty\ARCHIVE\

xcopy C:\ULLSA\Data\ARCHIVE\IN\%EIID%.LogbookData.qep E:\ULLS_MEDIA\Data\MigOut\%EIID%\
</code>```

Body:
I'm trying to move files from one portion a system to another using an inputted variable but for some reason xcopy won't use wildcards or variables.

set /p EIID = "Enter Aircraft EI_ID:"

xcopy C:\ULLSA\Data\ARCHIVE\IN\"%EIID%.LogbookData.qep" E:\ULLS_MEDIA\Data\3rdParty\ARCHIVE

xcopy C:\ULLSA\Data\ARCHIVE\IN\"%EIID%.LogbookData.qep" "E:\ULLS_MEDIA\Data\MigOut\%EIID%"

Body:
Have a go at this one mate. No need to quotations unless you believe there will be spaces in the file path. Also close your file path otherwise it wont work bud.

set /p EIID=Enter Aircraft EI_ID:

xcopy C:\ULLSA\Data\ARCHIVE\IN\%EIID%.LogbookData.qep E:\ULLS_MEDIA\Data\3rdParty\ARCHIVE\

xcopy C:\ULLSA\Data\ARCHIVE\IN\%EIID%.LogbookData.qep E:\ULLS_MEDIA\Data\MigOut\%EIID%\


问:
How to connect to an RDS database from Yii2?
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. However I received this error: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known"

All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

```<code>'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],
</code>```

What could be wrong? Thanks.

答:
I am guessing that you want pass db information through environment variables. You may want to try to revise the code as below.

```<code>'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=',
        'dsn' => 'mysql:host='.$_SERVER['RDS_HOSTNAME'].':'.$_SERVER['RDS_PORT'].';dbname='.$_SERVER['RDS_DB_NAME'],
        'username' => $_SERVER['RDS_USERNAME'],
        'password' => $_SERVER['RDS_PASSWORD'],
        'charset' => 'utf8',
    ],
</code>```

You can reference http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.RDS.html#rds-external-ec2classic in To configure environment properties section to configure your environment variables. Hope this works.

Body:
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. However I received this error: "SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known"

All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=',
            'dsn' => 'mysql:host=RDS_HOSTNAME:RDS_PORT;dbname=RDS_DB_NAME',
            'username' => 'RDS_USERNAME',
            'password' => 'RDS_PASSWORD',
            'charset' => 'utf8',
        ],

What could be wrong? Thanks.

Body:
I am guessing that you want pass db information through environment variables. You may want to try to revise the code as below.

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=',
        'dsn' => 'mysql:host='.$_SERVER['RDS_HOSTNAME'].':'.$_SERVER['RDS_PORT'].';dbname='.$_SERVER['RDS_DB_NAME'],
        'username' => $_SERVER['RDS_USERNAME'],
        'password' => $_SERVER['RDS_PASSWORD'],
        'charset' => 'utf8',
    ],

You can reference http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.RDS.html#rds-external-ec2classic in To configure environment properties section to configure your environment variables. Hope this works.


问:
Expression result unused when incrementing counter
```<code>void insert(size_t node, queue_t* queue) {
    *queue->count++;
    queue->elements[++(*queue->rear)] = node;
}
void remve(queue_t* queue) {
    *queue->front++;
    *queue->count--;
}
</code>```

<p>I am passing a queue and a node I wish to add to it into these helper functions. However, all the lines which involve an increment throw a "expression result unused" error. I would like to perform operations on this queue in helper functions without this error occuring. </p>

答:
An expression like

```<code>  *queue->front++;
</code>```

get parsed as

```<code>  *( queue->front++) ;
</code>```

due to operator precedence, so the final result (obtained by applying the dereference operator) is unused. That is what compiler is complaining about and my hunch is, it is correct.

Most probably, what you want is

```<code>       (*(queue->front) )++ ;
</code>```

Body:
void insert(size_t node, queue_t* queue) {
    *queue->count++;
    queue->elements[++(*queue->rear)] = node;
}
void remve(queue_t* queue) {
    *queue->front++;
    *queue->count--;
}

I am passing a queue and a node I wish to add to it into these helper functions. However, all the lines which involve an increment throw a "expression result unused" error. I would like to perform operations on this queue in helper functions without this error occuring.

Body:
An expression like

  *queue->front++;

get parsed as

  *( queue->front++) ;

due to operator precedence, so the final result (obtained by applying the dereference operator) is unused. That is what compiler is complaining about and my hunch is, it is correct.

Most probably, what you want is

       (*(queue->front) )++ ;


问:
It's Possible To Render HTML Inside a SQL Server Reporting Services 2008's Report?
I've read, that is possible to render HTML inside a SSRS 2008 report making use of the HTML Markup type of the textbox control.

I'm trying to render a simple link like:

```<code><a href="/destination">My Link</a>
</code>```

So the value of the placeholder would be:

```<code>="<a href=\"destination\">"My link</a>"
</code>```

But it seems like the \" is causing problems. there is a runtime error for using such expression: The Value expression for the textrun ‘Numbers1.Paragraphs[0].TextRuns[0]’ contains an error: [BC30205] End of statement expected. (rsCompilerErrorInExpression)

How do you escape the " character inside a expression?

Is it possible to render HTML?

答: \" is how you escape a quote in C#.  SSRS uses VB.NET I believe, so using "" should work.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've read, that is possible to render HTML inside a SSRS 2008 report making use of the HTML Markup type of the textbox control.

I'm trying to render a simple link like:

My Link

So the value of the placeholder would be:

=""My link"

But it seems like the \" is causing problems. there is a runtime error for using such expression: The Value expression for the textrun ‘Numbers1.Paragraphs[0].TextRuns[0]’ contains an error: [BC30205] End of statement expected. (rsCompilerErrorInExpression)

How do you escape the " character inside a expression?

Is it possible to render HTML?


问:
Get list of categories in specific Outlook folder/inbox
I am trying to extract a list of categories in a specific Outlook folder with Python.

For example I am connected to the following inboxes "Personal" and "Work".

The following code will return the list of categories in the master list for my Personal inbox:

```<code>outlook = win32com.client.Dispatch("Outlook.Application")
myfolder = outlook.GetNamespace("MAPI").Folders["Work"]
for cat in myfolder.session.categories:
    print cat
</code>```

So how do I get that list for my Work inbox?

答:
try iterating over the folder items.</p>

```<code>myfolder = outlook.GetNamespace("MAPI").Folders['Work']
for messages in myfolder.Items:
    print(messages)
</code>```

Body:
I am trying to extract a list of categories in a specific Outlook folder with Python.

For example I am connected to the following inboxes "Personal" and "Work".

The following code will return the list of categories in the master list for my Personal inbox:

outlook = win32com.client.Dispatch("Outlook.Application")
myfolder = outlook.GetNamespace("MAPI").Folders["Work"]
for cat in myfolder.session.categories:
    print cat

So how do I get that list for my Work inbox?

Body:
try iterating over the folder items.

myfolder = outlook.GetNamespace("MAPI").Folders['Work']
for messages in myfolder.Items:
    print(messages)


问:
Android Intent Filter on tablet
I'm encountering some problem in Android Intent Filter.

```<code>    <activity android:name=".view.SampleActivity" >
        <intent-filter android:label="@string/app_name" >
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="sample.test.com.my"
                android:pathPrefix="/resetPassword"
                android:scheme="test" />
        </intent-filter>
    </activity>
</code>```

This is the one I put in AndroidManifest.xml. It works in phone but however I realized it does not work in tablet.

What could be the problem since it works on phone but not tablet?

UPDATE: Found the issue. The root cause is related to the link provided is different for tablet and phone. There is nothing to do with Android.

答:
Your AndroidManifest file should contain a default activity.
In the Intent filter, you may add the following code.

```<code><intent-filter>
<action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />

 </intent-filter>
</code>```

It should contain a MAIN and LAUNCHER category.

Title: Android Intent Filter on tablet

Body:
I'm encountering some problem in Android Intent Filter.

    <activity android:name=".view.SampleActivity" >
        <intent-filter android:label="@string/app_name" >
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="sample.test.com.my"
                android:pathPrefix="/resetPassword"
                android:scheme="test" />
        </intent-filter>
    </activity>

This is the one I put in AndroidManifest.xml. It works in phone but however I realized it does not work in tablet.

What could be the problem since it works on phone but not tablet?

UPDATE: Found the issue. The root cause is related to the link provided is different for tablet and phone. There is nothing to do with Android.

Body:
Your AndroidManifest file should contain a default activity.
In the Intent filter, you may add the following code.

<intent-filter>
<action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />

 </intent-filter>

It should contain a MAIN and LAUNCHER category.


问:
Updating trigger frequency of Azure Logic App using API
I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message

Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
  None of the fields inside the properties object can be patched.

Here is a code snippet showing what I am trying to do.

```<code>    var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);

    dynamic workflowDefinition = workflow.Definition;
    workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });

    await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);
</code>```

where _client is Lazy<LogicManagementClient>.

Here is the definition of the trigger I am trying to update (got using Fiddler):

```<code>  "triggers": {
    "When_a_new_email_arrives": {
      "recurrence": {
        "frequency": "Hour",
        "interval": 2
      },
      "splitOn": "@triggerBody()?.value",
      "type": "ApiConnection",
      "inputs": {
        "host": {
          "api": {
            "runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
          },
          "connection": {
            "name": "@parameters('$connections')['office365']['connectionId']"
          }
        },
        "method": "get",
        "path": "/Mail/OnNewEmail",
        "queries": {
          "folderPath": "Inbox",
          "importance": "Any"
        }
      }
    }
  }
</code>```

Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?

UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.

答:
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.

I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.

```<code>string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);

string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
    subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");

dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });

string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);

message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);
</code>```

Body:
I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message

Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
  None of the fields inside the properties object can be patched.

Here is a code snippet showing what I am trying to do.

    var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);

    dynamic workflowDefinition = workflow.Definition;
    workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });

    await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);

where _client is Lazy<LogicManagementClient>.

Here is the definition of the trigger I am trying to update (got using Fiddler):

  "triggers": {
    "When_a_new_email_arrives": {
      "recurrence": {
        "frequency": "Hour",
        "interval": 2
      },
      "splitOn": "@triggerBody()?.value",
      "type": "ApiConnection",
      "inputs": {
        "host": {
          "api": {
            "runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
          },
          "connection": {
            "name": "@parameters('$connections')['office365']['connectionId']"
          }
        },
        "method": "get",
        "path": "/Mail/OnNewEmail",
        "queries": {
          "folderPath": "Inbox",
          "importance": "Any"
        }
      }
    }
  }

Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?

UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.

Body:
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.

I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.

string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);

string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
    subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");

dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });

string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);

message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);


问:
Firebase Storage/Bucket public upload with node.js
Code:

```<code>var storage = require('@google-cloud/storage');
var gcs = storage({
    projectId: config.google.projectId,
    keyFilename: config.google.keyFilenameFirebase
});

var bucket = gcs.bucket('project-id.appspot.com');
var destination = 'uploads/12345/full.jpg';

bucket.upload(myFile, { public: true, destination: destination }, function(err, file) {
    if (err) {
        console.log(err);
    }
});
</code>```

My file is successfully uploaded to my firebase storage, but:

The file is now publicly accessible through the url:
https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg. Can I use this fixed URL in my App or is it likely, that it will change or expire?

public: true seems to break the Firebase Storage UI:

The preview of the image on the right side is not showing and I'm unable to download the image via the download button. Also, there is no download url (which I don't mind, cause I can access it via the link above) and when clicking "Create new download URL" Firebase yields

Error generating download URL

When removing public: true the preview is shown correctly and I can also generate a download URL. But the public url  https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg won't work anymore, which is necessary for me.

So my plan is to stick to public: true, but it still bugs me, that the preview/download button is not working and it looks like a bug in Firebase to me. Can anyone confirm that?

答:
Your URLs shouldn't change or expire, and they should be valid until revoked which can happen through an object update or explicitly through revoking a url in the firebase web console. At least to the best of my knowledge.

First thing that comes to my mind is that : have you configured CORS on the bucket? This could be one reason. Check this out

Second thing that I can think of is storage rules. If you have something like allow read: if request.auth.uid == userId; you might want to remove those to make files publicly accessible. You can use something like this to make all files in a path public:

```<code> service firebase.storage {
  match /b/XXXXXX.appspot.com/o {
    match /{allPaths=**} {
      allow read;
    }
  }
</code>```

If you've already done these two things, then unfortunately it might actually be a firebase bug too. Best of luck!

Body:
Code:

var storage = require('@google-cloud/storage');
var gcs = storage({
    projectId: config.google.projectId,
    keyFilename: config.google.keyFilenameFirebase
});

var bucket = gcs.bucket('project-id.appspot.com');
var destination = 'uploads/12345/full.jpg';

bucket.upload(myFile, { public: true, destination: destination }, function(err, file) {
    if (err) {
        console.log(err);
    }
});

My file is successfully uploaded to my firebase storage, but:

The file is now publicly accessible through the url:
https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg. Can I use this fixed URL in my App or is it likely, that it will change or expire?

public: true seems to break the Firebase Storage UI:

The preview of the image on the right side is not showing and I'm unable to download the image via the download button. Also, there is no download url (which I don't mind, cause I can access it via the link above) and when clicking "Create new download URL" Firebase yields

Error generating download URL

When removing public: true the preview is shown correctly and I can also generate a download URL. But the public url  https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg won't work anymore, which is necessary for me.

So my plan is to stick to public: true, but it still bugs me, that the preview/download button is not working and it looks like a bug in Firebase to me. Can anyone confirm that?

Body:
Your URLs shouldn't change or expire, and they should be valid until revoked which can happen through an object update or explicitly through revoking a url in the firebase web console. At least to the best of my knowledge.

First thing that comes to my mind is that : have you configured CORS on the bucket? This could be one reason. Check this out

Second thing that I can think of is storage rules. If you have something like allow read: if request.auth.uid == userId; you might want to remove those to make files publicly accessible. You can use something like this to make all files in a path public:

 service firebase.storage {
  match /b/XXXXXX.appspot.com/o {
    match /{allPaths=**} {
      allow read;
    }
  }

If you've already done these two things, then unfortunately it might actually be a firebase bug too. Best of luck!


问:
Tensorflow: all items in training batch have same predicted label
I am trying to solve classic MNIST task with convolutional NN at Tensorflow.
My input is data from Kaggle: https://www.kaggle.com/c/digit-recognizer/data

I am new to machine learning, so my code is basically a mix of copy-pastes from various sources + my own hacking around.

Currently my code is following: https://gist.github.com/arodiss/90ea76e5f5545af6b11e7f1dcfee01b5

Notice that currently instead of outputting accuracy I output only predicted labels (argmax of softmax of model output)

And here is what output looks like:

```<code>[8 6 4 2 6 8 7 6 6 7 6 6 4 7 0 6]
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4]
[7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7]
[4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3]

( ... and so on)
</code>```

So basically in every minibatch except the first (random) one all examples have the same label, which is clearly wrong. When instead I output probabilities themself, I get something like this:

```<code>[[  4.38091134e-30   1.28820540e-15   1.00000000e+00   1.73298234e-28
  7.69853474e-13   2.90028703e-19   9.43878135e-12   5.07752279e-17
  3.48896642e-33   3.62770106e-26]
[  0.00000000e+00   2.62364278e-33   3.19788233e-34   0.00000000e+00
  3.95365081e-34   1.00000000e+00   1.16309332e-11   0.00000000e+00
  5.20279699e-38   0.00000000e+00]
[  3.01065546e-22   3.79994231e-11   3.48180471e-08   1.23861001e-14
  4.11970850e-31   1.00000000e+00   4.88898765e-25   0.00000000e+00
  4.25802429e-18   0.00000000e+00]

(... and so on)
</code>```

Any advice how to fix this particular issue?
Any advice overall? (as a newbie I probably did a lot of things in a wrong way)

ANSWER FOUND: I encoded my data as "channels first" but treated it as "channels last".
With convolutions this leads to specified result, ie all items in batch have same label

答:
MNIST is a classical example and actually part of the official tensorflow tutorial (https://www.tensorflow.org/get_started/mnist/beginners).

What I think the problem here is that you did not shuffle the dataset and trained only on minibatches using the same label and you kinda learned that using batch normalization. It is also possible that your samples have the same label for every minibatch. You should give an accuracy metric to judge your program.

Body:
I am trying to solve classic MNIST task with convolutional NN at Tensorflow.
My input is data from Kaggle: https://www.kaggle.com/c/digit-recognizer/data

I am new to machine learning, so my code is basically a mix of copy-pastes from various sources + my own hacking around.

Currently my code is following: https://gist.github.com/arodiss/90ea76e5f5545af6b11e7f1dcfee01b5

Notice that currently instead of outputting accuracy I output only predicted labels (argmax of softmax of model output)

And here is what output looks like:

[8 6 4 2 6 8 7 6 6 7 6 6 4 7 0 6]
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4]
[7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7]
[4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3]

( ... and so on)

So basically in every minibatch except the first (random) one all examples have the same label, which is clearly wrong. When instead I output probabilities themself, I get something like this:

[[  4.38091134e-30   1.28820540e-15   1.00000000e+00   1.73298234e-28
  7.69853474e-13   2.90028703e-19   9.43878135e-12   5.07752279e-17
  3.48896642e-33   3.62770106e-26]
[  0.00000000e+00   2.62364278e-33   3.19788233e-34   0.00000000e+00
  3.95365081e-34   1.00000000e+00   1.16309332e-11   0.00000000e+00
  5.20279699e-38   0.00000000e+00]
[  3.01065546e-22   3.79994231e-11   3.48180471e-08   1.23861001e-14
  4.11970850e-31   1.00000000e+00   4.88898765e-25   0.00000000e+00
  4.25802429e-18   0.00000000e+00]

(... and so on)

Any advice how to fix this particular issue?
Any advice overall? (as a newbie I probably did a lot of things in a wrong way)

ANSWER FOUND: I encoded my data as "channels first" but treated it as "channels last".
With convolutions this leads to specified result, ie all items in batch have same label