问:
How to use two-column layout with reveal.js?
I use reveal.js and write my slides in Markdown code. Now I want to display my content (text, unordered list of bullet points or even an image) in a classical two-column text layout. I would prefer a solution which may be more complex in initial configuration as long as the actual writing of content in Markdown remains easy.

Since I prefer not to run a local server, I write my markdown within the main HTML file.

Update: As the first answer indicates this should be achieved with CSS. (I updated my question accordingly.) Still, I couldn't find any description how to do it with CSS.

答:
I am using CSS flex, it is working fine.

```<code><style>
.container{
    display: flex;
}
.col{
    flex: 1;
}
</style>

<div class="container">

<div class="col">
Column 1 Content
</div>

<div class="col">
Column 2 Content
</div>

</div>
</code>```

UPDATE:

Since pandoc supports fenced div,

```<code>::: {.container}
:::: {.col}
Column 1 Content
::::
:::: {.col}
Column 2 Content
::::
:::
</code>```

For the style, we can either use flex or grid, both work fine.

Using flex

```<code><style>
.container{
  display: flex;
}
.col {
  flex: 1;
}
</style>
</code>```

Using grid

```<code><style>
.container{
  display: grid;
  grid-auto-flow: column;
}
</style>
</code>```

Body:
I am using CSS flex, it is working fine.

<style>
.container{
    display: flex;
}
.col{
    flex: 1;
}
</style>

<div class="container">

<div class="col">
Column 1 Content
</div>

<div class="col">
Column 2 Content
</div>

</div>

UPDATE:

Since pandoc supports fenced div,

::: {.container}
:::: {.col}
Column 1 Content
::::
:::: {.col}
Column 2 Content
::::
:::

For the style, we can either use flex or grid, both work fine.

Using flex

<style>
.container{
  display: flex;
}
.col {
  flex: 1;
}
</style>

Using grid

<style>
.container{
  display: grid;
  grid-auto-flow: column;
}
</style>


来源: stackexchange

问:
Highcharts exporting className
How do you set a classname for an exported graph in Highcharts? I tried this but it did not work:</p>

```<code>exporting: {
   chartOptions: {
   chart: {
      className: 'negPos'
    }
  }
}
</code>```

答:
negativeColor add to plot options

Highcharts.chart(container, {
  chart: {
    //className: 'negPos',
    type: 'column',
    spacingBottom: 20,
    style: {
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontSize: '11px',
      fontWeight: 'lighter'
    }
  },
  title: {
    text: 'Highcharts',
    align: 'center',
    style: {
      fontSize: '15px',
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontWeight: 'lighter'
    }
  },
  xAxis: {
    categories: [1, 2, 3, 5, 6]
  },
  yAxis: {
    title: {
      text: '%'
    }
  },
  tooltip: {
    borderWidth: 0,
    style: {
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontSize: '11px',
      align: 'center'
    },
    formatter: function() {
      return '' + this.x + ':
' + Highcharts.numberFormat(this.y, 1) + '%'
    }
  },
  plotOptions: {
    column: {
      negativeColor: '#d9534f',
      threshold: 0,
    }
  },
  /* plotOptions: {
       bar: {
           dataLabels: {
               enabled: false
           }
       }
   },*/
  legend: {
    layout: 'vertical',
    verticalAlign: 'bottom',
    borderWidth: 1,
    backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
    shadow: true
  },
  series: [{
    showInLegend: false,
    color: '#5cb85c',
    data: [54, 21, -3, 18, 5, -11]
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div></code>```

ContentLicense: CC BY-SA 3.0

Title: Highcharts exporting className

Body:
How do you set a classname for an exported graph in Highcharts? I tried this but it did not work:

exporting: {
   chartOptions: {
   chart: {
      className: 'negPos'
    }
  }
}

Body:
negativeColor add to plot options

Highcharts.chart(container, {
  chart: {
    //className: 'negPos',
    type: 'column',
    spacingBottom: 20,
    style: {
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontSize: '11px',
      fontWeight: 'lighter'
    }
  },
  title: {
    text: 'Highcharts',
    align: 'center',
    style: {
      fontSize: '15px',
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontWeight: 'lighter'
    }
  },
  xAxis: {
    categories: [1, 2, 3, 5, 6]
  },
  yAxis: {
    title: {
      text: '%'
    }
  },
  tooltip: {
    borderWidth: 0,
    style: {
      fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
      fontSize: '11px',
      align: 'center'
    },
    formatter: function() {
      return '<b>' + this.x + ': </b><br>' + Highcharts.numberFormat(this.y, 1) + '%'
    }
  },
  plotOptions: {
    column: {
      negativeColor: '#d9534f',
      threshold: 0,
    }
  },
  /* plotOptions: {
       bar: {
           dataLabels: {
               enabled: false
           }
       }
   },*/
  legend: {
    layout: 'vertical',
    verticalAlign: 'bottom',
    borderWidth: 1,
    backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
    shadow: true
  },
  series: [{
    showInLegend: false,
    color: '#5cb85c',
    data: [54, 21, -3, 18, 5, -11]
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div>


问:
Is possible to call an overridden method from another plugin? [Is for a Minecraft plugin]
I'm coding two plugins for a program, one of this plugin is a "library plugin" and contains a lot of classes used by the other plugins, the other is one of the plugin based on this library. All works well except one thing. In my library plugin I wrote a socket class sintetized to this:

```<code>public class MServerSocket {
    public void initServer(int port) {
        //Code to receive message from client
        execute(input, clientOutput);
    }

    public void execute(String input, DataOutputStream clientOutput) {
        System.out.println(input);
        send(clientOutput, input);
    }

    public void send(DataOutputStream clientOutput, String output) {
        //Code to send message to client
    }
}
</code>```

In the other plugin I extend this class and override the execute method to do something, like this:

```<code>public class MySocketServer extends MServerSocket {
    @Override
    public void execute(String input, DataOutputStream clientOutput) {
        //Do something
        MServerSocket.send(clientOutput, input)
    }
}
</code>```

Now my second plugin should override my library plugin class but it doesn't. In the second plugin I call it in the main like this:

```<code>public class Main {
    public void onEnable() { //method called to load plugin
        private static MServerSocket socket = new MServerSocket();
        socket.initServer(12980);
    }
}
</code>```

When I send a socket message to my socket it is printed to the console as said in the library execute method.

So here I am, can someone give me an answer and possibly a solution? Thanks in advance.

答:
There are errors in the code you posted:

```<code>  MServerSocket.send(clientOutput, input);
</code>```

That is incorrect becausesend is not a static method.  It should be written as this:

```<code> this.send(clientOutput, input);
</code>```

or

```<code> super.send(clientOutput, input);
</code>```

or simply

```<code> send(clientOutput, input);
</code>```

But to answer your question, the reason that you are seeing the "print" is that you are calling the initServer method on an instance that is a MServerSocket instance rather than a MyServerSocket instance.  Since it is an MServerSocket instance, it doesn't have the override method.

Body:
I'm coding two plugins for a program, one of this plugin is a "library plugin" and contains a lot of classes used by the other plugins, the other is one of the plugin based on this library. All works well except one thing. In my library plugin I wrote a socket class sintetized to this:

public class MServerSocket {
    public void initServer(int port) {
        //Code to receive message from client
        execute(input, clientOutput);
    }

    public void execute(String input, DataOutputStream clientOutput) {
        System.out.println(input);
        send(clientOutput, input);
    }

    public void send(DataOutputStream clientOutput, String output) {
        //Code to send message to client
    }
}

In the other plugin I extend this class and override the execute method to do something, like this:

public class MySocketServer extends MServerSocket {
    @Override
    public void execute(String input, DataOutputStream clientOutput) {
        //Do something
        MServerSocket.send(clientOutput, input)
    }
}

Now my second plugin should override my library plugin class but it doesn't. In the second plugin I call it in the main like this:

public class Main {
    public void onEnable() { //method called to load plugin
        private static MServerSocket socket = new MServerSocket();
        socket.initServer(12980);
    }
}

When I send a socket message to my socket it is printed to the console as said in the library execute method.

So here I am, can someone give me an answer and possibly a solution? Thanks in advance.

Body:
There are errors in the code you posted:

  MServerSocket.send(clientOutput, input);

That is incorrect becausesend is not a static method.  It should be written as this:

 this.send(clientOutput, input);

or

 super.send(clientOutput, input);

or simply

 send(clientOutput, input);

But to answer your question, the reason that you are seeing the "print" is that you are calling the initServer method on an instance that is a MServerSocket instance rather than a MyServerSocket instance.  Since it is an MServerSocket instance, it doesn't have the override method.


问:
Interactive plotting of 3D data in a web app
I need to create a web app that allows the user to graphically analyze multivariate data. In my vision, the users will select three (out of the many available) variables that they want to see, and the app will plot them. After that the users will get the opportunity to interactively explore the graphs.

There is a site that demonstrates using JMol - an open-source Java viewer for chemical structures in 3D to plot data in 3d. The result is pretty neat, but I would feel more comfortable to use a tool that is dedicated to plotting data, as I suspect such a tool would be more easy to operate and would provide more options. Unfortunately, I  cannot find any alternative that will both work in 3D and will provide interactive access to the plot. Do you have any suggestions?

答: JMathPlot is what I need

ContentLicense: CC BY-SA 2.5

Body: JMathPlot is what I need


问:
Separation of concerns for DbContext
Now I use Entity Framework with the following DbContext class:

```<code>public class ItemDbContext : DbContext {
    ...
    public DbSet<Item1> Item1s { get; set; }
    public DbSet<Item2> Item2s { get; set; }
}
</code>```

There are some classes need DbContext with either Item11s or Item2s as dependencies. So my purpose is create a layer of abstraction for DbContext with that DbSet types (logically separate DbContext_Item1 and DbContext_Item2). It can be useful for implementation of abstract factory pattern (create either DbContext_Item1 or DbContext_Item2 instance) also.

My thoughts:

1) Interfaces

```<code>public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
}
public interface IDbContext_Item2 {
    DbSet<Item3> Item2s { get; set; }
}
</code>```

So my abstract factory is able to have API like that:

```<code>public abstract ItemFactory {
    public abstract IDbContext_Item1 GetItem1Context;
    public abstract IDbContext_Item2 GetItem2Context;
}
</code>```

It would be fine for me. However class which get IDbContext_ItemX instance doesn't treat it as DbContext instance (i.e. can not call method like SaveChanges() etc.). Unfortunately any interface can not be inherited from class like DbContext.

2) Extended interfaces with methods of DbContext

```<code>public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
    void SaveChanges;
    // etc
}
</code>```

In my opinion it's extremely not elegant.

3) Abstract classes for IDbContext_ItemX

But my current DbContext implementation, ItemDbContext, can not be inherited from multiple classes.

4) Just devide current ItemDbContext on DbContext_Item1 and DbContext_Item2 concrete classes.

Yes, it is the decision. But is it only way? It would be great if my concrete factories return instances of ItemDbContext under the hood. Can I achieve it?

答:
I think you need to create some base interface (lets call it IDatabaseContext):

```<code>public interface IDatabaseContext : IDisposable
{
  //base DbContext stuff like SaveChanges here
}
</code>```

Then you have nested interfaces:

```<code>IDbContext_Item1 : IDatabaseContext
IDbContext_Item2 : IDatabaseContext
</code>```

And your ItemDbContext implements both interfaces.

I agree that writing all DbContext methods in IDatabaseContext interface is not elegant, but you need to do it just one time

Title: Separation of concerns for DbContext

Body:
Now I use Entity Framework with the following DbContext class:

public class ItemDbContext : DbContext {
    ...
    public DbSet<Item1> Item1s { get; set; }
    public DbSet<Item2> Item2s { get; set; }
}

There are some classes need DbContext with either Item11s or Item2s as dependencies. So my purpose is create a layer of abstraction for DbContext with that DbSet types (logically separate DbContext_Item1 and DbContext_Item2). It can be useful for implementation of abstract factory pattern (create either DbContext_Item1 or DbContext_Item2 instance) also.

My thoughts:

1) Interfaces

public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
}
public interface IDbContext_Item2 {
    DbSet<Item3> Item2s { get; set; }
}

So my abstract factory is able to have API like that:

public abstract ItemFactory {
    public abstract IDbContext_Item1 GetItem1Context;
    public abstract IDbContext_Item2 GetItem2Context;
}

It would be fine for me. However class which get IDbContext_ItemX instance doesn't treat it as DbContext instance (i.e. can not call method like SaveChanges() etc.). Unfortunately any interface can not be inherited from class like DbContext.

2) Extended interfaces with methods of DbContext

public interface IDbContext_Item1 {
    DbSet<Item1> Item1s { get; set; }
    void SaveChanges;
    // etc
}

In my opinion it's extremely not elegant.

3) Abstract classes for IDbContext_ItemX

But my current DbContext implementation, ItemDbContext, can not be inherited from multiple classes.

4) Just devide current ItemDbContext on DbContext_Item1 and DbContext_Item2 concrete classes.

Yes, it is the decision. But is it only way? It would be great if my concrete factories return instances of ItemDbContext under the hood. Can I achieve it?

Body:
I think you need to create some base interface (lets call it IDatabaseContext):

public interface IDatabaseContext : IDisposable
{
  //base DbContext stuff like SaveChanges here
}

Then you have nested interfaces:

IDbContext_Item1 : IDatabaseContext
IDbContext_Item2 : IDatabaseContext

And your ItemDbContext implements both interfaces.

I agree that writing all DbContext methods in IDatabaseContext interface is not elegant, but you need to do it just one time


问:
calculate the number of years in a csv file using pandas
i have a csv file containing  years of data , and i am using pandas to read it.
my main request, is how to calculate the number of years from the max date and the min date .

```<code>timestamp,heure,lat,lon,impact,type
2007-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2007-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-01-02 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-01-03 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2007-01-03 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
</code>```

I am proceeding as below :

```<code>data['time'] = pd.to_datetime(data['time'])
DateMax = data.index.max()
DateMin = data.index.min()
NByears = (DateMax - DateMin).astype('datetime64[Y]')
</code>```

but it's not working, any ideas ?

答:
It seems you need first convert to DatetimeIndex.year, get min and max and last subtract:

```<code>DateMax = data.index.year.max()
DateMin = data.index.year.min()
NByears = (DateMax - DateMin)
</code>```

Body:
i have a csv file containing  years of data , and i am using pandas to read it.
my main request, is how to calculate the number of years from the max date and the min date .

timestamp,heure,lat,lon,impact,type
2007-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2007-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-01-02 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-01-03 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2007-01-03 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

I am proceeding as below :

data['time'] = pd.to_datetime(data['time'])
DateMax = data.index.max()
DateMin = data.index.min()
NByears = (DateMax - DateMin).astype('datetime64[Y]')

but it's not working, any ideas ?

Body:
It seems you need first convert to DatetimeIndex.year, get min and max and last subtract:

DateMax = data.index.year.max()
DateMin = data.index.year.min()
NByears = (DateMax - DateMin)


问:
Angular version 4.x Table Row Component
I'm trying to create a component that can be used as a row in a table.

```<code><table class="table">
  <tbody>
    <my-row *ngFor="let id of ids" [id]="id"></my-row>
  </tbody>
</table>
</code>```

When I do this, all of the rows appear on a single row.

Here's an example of what the problem is and what I'm expecting.

https://plnkr.co/edit/37fRFlMNVqoQTg4UKBcu?p=preview

答:
You can achieve desired result by using attribute selector

```<code><tr my-row *ngFor="let id of ids"  [id]="id"></tr>

@Component({
  selector: '[my-row]',
  template: `<td>{{ id }}</td>`,
})
export class Row {
  @Input() id;
}
</code>```

Forked Example

Title: Angular version 4.x Table Row Component

Body:
I'm trying to create a component that can be used as a row in a table.

    <my-row *ngFor="let id of ids" [id]="id"></my-row>

When I do this, all of the rows appear on a single row.

Here's an example of what the problem is and what I'm expecting.

https://plnkr.co/edit/37fRFlMNVqoQTg4UKBcu?p=preview

Body:
You can achieve desired result by using attribute selector

<tr my-row *ngFor="let id of ids"  [id]="id"></tr>

@Component({
  selector: '[my-row]',
  template: `<td>{{ id }}</td>`,
})
export class Row {
  @Input() id;
}

Forked Example


问:
How can I detect if a grouped result of the mySQL database has any related value?
```<code>animal    food
cat
cat       mouse
cat
dog
dog
bird      carrot
bird      herb
bird
</code>```

I have some animals in my mysql database. My problem is that I need to know, if any animal of a animal-group got food.

```<code> $pdo = $db->query('SELECT * FROM list GROUP BY animal');
 while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["food"]){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
  }
}
</code>```

My result is:

```<code>No cat got food.
No dog got food.
No bird got food.
</code>```

But I expect:

```<code>Some cat got food.
No dog got food.
Some bird got food.
</code>```

答:
We can make use of an aggregate function, e.g.

```<code> SELECT t.animal
      , MAX(t.food) AS food
   FROM list t
  GROUP BY t.animal
  ORDER BY t.animal
</code>```

or conditional aggregation, e.g.:

```<code> SELECT t.animal
      , COUNT(IF(t.food>'',1,NULL)) AS food
   FROM list t
  GROUP BY t.animal
  ORDER BY t.animal
</code>```

Body:
animal    food
cat
cat       mouse
cat
dog
dog
bird      carrot
bird      herb
bird

I have some animals in my mysql database. My problem is that I need to know, if any animal of a animal-group got food.

 $pdo = $db->query('SELECT * FROM list GROUP BY animal');
 while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["food"]){
       echo "Some ".$row["animal"]." got food.
";
    } else {
       echo "No " .$row["animal"]. " got food.
";
  }
}

My result is:

No cat got food.
No dog got food.
No bird got food.

But I expect:

Some cat got food.
No dog got food.
Some bird got food.

Body:
We can make use of an aggregate function, e.g.

 SELECT t.animal
      , MAX(t.food) AS food
   FROM list t
  GROUP BY t.animal
  ORDER BY t.animal

or conditional aggregation, e.g.:

 SELECT t.animal
      , COUNT(IF(t.food>'',1,NULL)) AS food
   FROM list t
  GROUP BY t.animal
  ORDER BY t.animal


问:
Angular Route for specific url
I'm currently working on a MEAN stack project and am trying to get a specific template to display on a specific url.

Currently if users goto www.myurl/catalog, it loads the catalog.html template, as it would with any /catalog?catagory=productType url.

I would like it so that when users go to /catalog?category=specificProductType that it loads the catalogSpecific.html template.  Currently, the catalog.html template supersedes the catalogSpecific.html template.  I can't find much about this specific issue so any help would be appreciated.

Currently my routes look like this:

app/front/app.js

```<code>angular.module('app', ['ngRoute',
                    'app.LandingModule.controller',
                    'app.CatalogModule.controller',
                    'app.ProductModule.controller',
                    'app.HeaderModule.directives',
                    'app.FooterModule.directives'
                    ])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
.when('/', {
  templateUrl: 'html/landing.html',
  controller: 'LandingController'
})
.when('/catalog', {
  templateUrl: 'html/catalog.html',
  controller: 'CatalogController'
})
.when('/catalog?category=specificProductType', {
  templateUrl: 'html/catalogSpecific.html',
  controller: 'CatalogController'
})
.otherwise({
  redirectTo: '/'
});
}]);
</code>```

答:
I was able to figure this out following Hadi's example:</p>

```<code>    .when('/catalog', {
  templateUrl: function($location){
            if($location.category == "specificProductType") {
            return 'html/catalogSpecific.html';
        } else {
            return 'html/catalog.html';
       }
},
  controller: 'CatalogController'
})
</code>```

Title: Angular Route for specific url

Body:
I'm currently working on a MEAN stack project and am trying to get a specific template to display on a specific url.

Currently if users goto www.myurl/catalog, it loads the catalog.html template, as it would with any /catalog?catagory=productType url.

I would like it so that when users go to /catalog?category=specificProductType that it loads the catalogSpecific.html template.  Currently, the catalog.html template supersedes the catalogSpecific.html template.  I can't find much about this specific issue so any help would be appreciated.

Currently my routes look like this:

app/front/app.js

angular.module('app', ['ngRoute',
                    'app.LandingModule.controller',
                    'app.CatalogModule.controller',
                    'app.ProductModule.controller',
                    'app.HeaderModule.directives',
                    'app.FooterModule.directives'
                    ])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
.when('/', {
  templateUrl: 'html/landing.html',
  controller: 'LandingController'
})
.when('/catalog', {
  templateUrl: 'html/catalog.html',
  controller: 'CatalogController'
})
.when('/catalog?category=specificProductType', {
  templateUrl: 'html/catalogSpecific.html',
  controller: 'CatalogController'
})
.otherwise({
  redirectTo: '/'
});
}]);

Body:
I was able to figure this out following Hadi's example:

    .when('/catalog', {
  templateUrl: function($location){
            if($location.category == "specificProductType") {
            return 'html/catalogSpecific.html';
        } else {
            return 'html/catalog.html';
       }
},
  controller: 'CatalogController'
})


问:
SQL calculation based on another column
I am extracting data out of SQL database and need to calculate the opening balance of a stock item per project. I am getting the opening balance for the stock inclusive of all the projects.

```<code>item code | Project | Qty In | Qty Out
----------+---------+--------+---------
1234        1            0       90
1234        1           90        0
1234        2          431        0
1234        2            0       22
1234        3          925        0
1234        3            0      925
1234        3          925        0
1234        3            0       20
1234        3            0       40
1234        3            0       30
1234        3            0       40
1234        3            0       60
1234        3            0       50
1234        3            0       24
1234        3            0       40
1234        3            0       30
1234        3            0       17
1234        3            0       80
1234        3            0       30
1234        4           16        0
1234        4            0       16
1234        5           22        0
1234        5            0       23
</code>```

Query:

```<code>select OpeningBalanceQty = Qty_On_Hand +
(select case when ServiceItem = 0
             then IsNull(sum (QtyOut), 0)
             else 0
        end
 from table1
 where AccountLink=StockLink  and txdate>='2016-06-01' and project ='2' ) -
(select case when ServiceItem = 0
             then IsNull(sum (QtyIn), 0)
             else 0
        end from table1
 where AccountLink=StockLink  and txdate>='2016-06-01' and project ='2')
 from tablel join table2 on table1.AccountLink = table2.StockLink
</code>```

I have used project 2 as an example, it has two transactions(qty in:431)& (qty out:22)

My opening balance should be 409 but it is giving the total for the product item

My full code:

```<code>select Table1.TxDate,Table2.Pack,Table1.Reference,

OpeningBalanceQty=  (select case when ServiceItem = 0 then IsNull(sum
(QtyOut), 0) else 0 end from Table1 where AccountLink=StockLink  and
ProjectCode in('2')   ) - (select case when ServiceItem = 0 then IsNull(sum
(QtyIn), 0) else 0 end from Table1 where AccountLink=StockLink  and
ProjectCode  in('2'))

,ProjectCode,ProjectDescription, Code, Description_1, Sum(ActualQuantity)*-1
as [Qty Processed],Sum(Debit)-Sum(Credit) as [Value],Trcode

from Table1
join Table2
on Table1 .AccountLink = Table2.StockLink
where  ServiceItem = 0  and txdate>='2017-06-01 00:00:00' and txdate<='2017-
06-30 00:00:00' and Code='1234'
Group by Description_1, Code,ProjectCode, ProjectDescription, stocklink,
serviceitem,Qty_On_Hand,Table1.Reference,Table2.Pack,Table1.TxDate,trcode
</code>```

答:
Do you think this could be helpful for you?

```<code>SELECT PROJECT, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY
FROM yourtable
WHERE txdate>='2016-06-01'
GROUP BY PROJECT
</code>```

Output:

```<code>PROJECT OPEN_BAL_QTY
1   0
2   409
3   464
4   0
5   -1
</code>```

1° update: after your new information (pls, next time, try to give all the information in your initial post, and well formatted: see tour of stackoverflow to learn how to do).
If you are using MSSQL 2005 or later, you can try this:

```<code>SELECT TABLE1.TXDATE
    ,TABLE2.PACK
    ,TABLE1.REFERENCE
       , SUM(QTYIN-QTYOUT) OVER (PARTITION BY TABLE1.PROJECTCODE) AS OPEN_BAL_QTY
    ,PROJECTCODE
    ,PROJECTDESCRIPTION
    ,CODE
    ,DESCRIPTION_1
    ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED
    , SUM(DEBIT) - SUM(CREDIT) AS VALUE
    ,TRCODE
FROM TABLE1
JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK
WHERE SERVICEITEM = 0
    AND TXDATE >= '2017-06-01 00:00:00'
    AND TXDATE <= '2017-06-30 00:00:00'
    AND CODE = '1234'
GROUP BY DESCRIPTION_1
    ,CODE
    ,PROJECTCODE
    ,PROJECTDESCRIPTION
    ,STOCKLINK
    ,SERVICEITEM
    ,QTY_ON_HAND
    ,TABLE1.REFERENCE
    ,TABLE2.PACK
    ,TABLE1.TXDATE
    ,TRCODE
</code>```

2° update
If it doesn't work for you, you should try:

```<code> SELECT A.*
        ,B.OPEN_BAL_QTY
    FROM
        SELECT TABLE1.TXDATE
            ,TABLE2.PACK
            ,TABLE1.REFERENCE
            ,PROJECTCODE
            ,PROJECTDESCRIPTION
            ,CODE
            ,DESCRIPTION_1
            ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED
            , SUM(DEBIT) - SUM(CREDIT) AS VALUE
            ,TRCODE
        FROM TABLE1
        JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK
        WHERE SERVICEITEM = 0
            AND TXDATE >= '2017-06-01 00:00:00'
            AND TXDATE <= '2017-06-30 00:00:00'
            AND CODE = '1234'
        GROUP BY DESCRIPTION_1
            ,CODE
            ,PROJECTCODE
            ,PROJECTDESCRIPTION
            ,STOCKLINK
            ,SERVICEITEM
            ,QTY_ON_HAND
            ,TABLE1.REFERENCE
            ,TABLE2.PACK
            ,TABLE1.TXDATE
            ,TRCODE
    ) A
LEFT JOIN (SELECT PROJECTCODE, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY
            FROM TABLE1
            WHERE TXDATE>='2017-06-01'
                AND TXDATE <= '2017-06-30 00:00:00'
            GROUP BY PROJECT) B ON A.PROJECT_CODE = B.PROJECT_CODE
</code>```

Title: SQL calculation based on another column

Body:
I am extracting data out of SQL database and need to calculate the opening balance of a stock item per project. I am getting the opening balance for the stock inclusive of all the projects.

item code | Project | Qty In | Qty Out
----------+---------+--------+---------
1234        1            0       90
1234        1           90        0
1234        2          431        0
1234        2            0       22
1234        3          925        0
1234        3            0      925
1234        3          925        0
1234        3            0       20
1234        3            0       40
1234        3            0       30
1234        3            0       40
1234        3            0       60
1234        3            0       50
1234        3            0       24
1234        3            0       40
1234        3            0       30
1234        3            0       17
1234        3            0       80
1234        3            0       30
1234        4           16        0
1234        4            0       16
1234        5           22        0
1234        5            0       23

Query:

select OpeningBalanceQty = Qty_On_Hand +
(select case when ServiceItem = 0
             then IsNull(sum (QtyOut), 0)
             else 0
        end
 from table1
 where AccountLink=StockLink  and txdate>='2016-06-01' and project ='2' ) -
(select case when ServiceItem = 0
             then IsNull(sum (QtyIn), 0)
             else 0
        end from table1
 where AccountLink=StockLink  and txdate>='2016-06-01' and project ='2')
 from tablel join table2 on table1.AccountLink = table2.StockLink

I have used project 2 as an example, it has two transactions(qty in:431)& (qty out:22)

My opening balance should be 409 but it is giving the total for the product item

My full code:

select Table1.TxDate,Table2.Pack,Table1.Reference,

OpeningBalanceQty=  (select case when ServiceItem = 0 then IsNull(sum
(QtyOut), 0) else 0 end from Table1 where AccountLink=StockLink  and
ProjectCode in('2')   ) - (select case when ServiceItem = 0 then IsNull(sum
(QtyIn), 0) else 0 end from Table1 where AccountLink=StockLink  and
ProjectCode  in('2'))

,ProjectCode,ProjectDescription, Code, Description_1, Sum(ActualQuantity)*-1
as [Qty Processed],Sum(Debit)-Sum(Credit) as [Value],Trcode

from Table1
join Table2
on Table1 .AccountLink = Table2.StockLink
where  ServiceItem = 0  and txdate>='2017-06-01 00:00:00' and txdate<='2017-
06-30 00:00:00' and Code='1234'
Group by Description_1, Code,ProjectCode, ProjectDescription, stocklink,
serviceitem,Qty_On_Hand,Table1.Reference,Table2.Pack,Table1.TxDate,trcode

Body:
Do you think this could be helpful for you?

SELECT PROJECT, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY
FROM yourtable
WHERE txdate>='2016-06-01'
GROUP BY PROJECT

Output:

PROJECT OPEN_BAL_QTY
1   0
2   409
3   464
4   0
5   -1

1° update: after your new information (pls, next time, try to give all the information in your initial post, and well formatted: see tour of stackoverflow to learn how to do).
If you are using MSSQL 2005 or later, you can try this:

SELECT TABLE1.TXDATE
    ,TABLE2.PACK
    ,TABLE1.REFERENCE
       , SUM(QTYIN-QTYOUT) OVER (PARTITION BY TABLE1.PROJECTCODE) AS OPEN_BAL_QTY
    ,PROJECTCODE
    ,PROJECTDESCRIPTION
    ,CODE
    ,DESCRIPTION_1
    ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED
    , SUM(DEBIT) - SUM(CREDIT) AS VALUE
    ,TRCODE
FROM TABLE1
JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK
WHERE SERVICEITEM = 0
    AND TXDATE >= '2017-06-01 00:00:00'
    AND TXDATE <= '2017-06-30 00:00:00'
    AND CODE = '1234'
GROUP BY DESCRIPTION_1
    ,CODE
    ,PROJECTCODE
    ,PROJECTDESCRIPTION
    ,STOCKLINK
    ,SERVICEITEM
    ,QTY_ON_HAND
    ,TABLE1.REFERENCE
    ,TABLE2.PACK
    ,TABLE1.TXDATE
    ,TRCODE

2° update
If it doesn't work for you, you should try:

 SELECT A.*
        ,B.OPEN_BAL_QTY
    FROM
        SELECT TABLE1.TXDATE
            ,TABLE2.PACK
            ,TABLE1.REFERENCE
            ,PROJECTCODE
            ,PROJECTDESCRIPTION
            ,CODE
            ,DESCRIPTION_1
            ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED
            , SUM(DEBIT) - SUM(CREDIT) AS VALUE
            ,TRCODE
        FROM TABLE1
        JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK
        WHERE SERVICEITEM = 0
            AND TXDATE >= '2017-06-01 00:00:00'
            AND TXDATE <= '2017-06-30 00:00:00'
            AND CODE = '1234'
        GROUP BY DESCRIPTION_1
            ,CODE
            ,PROJECTCODE
            ,PROJECTDESCRIPTION
            ,STOCKLINK
            ,SERVICEITEM
            ,QTY_ON_HAND
            ,TABLE1.REFERENCE
            ,TABLE2.PACK
            ,TABLE1.TXDATE
            ,TRCODE
    ) A
LEFT JOIN (SELECT PROJECTCODE, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY
            FROM TABLE1
            WHERE TXDATE>='2017-06-01'
                AND TXDATE <= '2017-06-30 00:00:00'
            GROUP BY PROJECT) B ON A.PROJECT_CODE = B.PROJECT_CODE


问:
MySQL Storing Unlimited Data within Row
What is the best way to store data in this scenario:

ACCOUNT table stores id, username, password and a large set of data comprising of multiple rows. Example: multiple sessions stored with date and other information.

What I'm doing now is creating a new table called sessions_id# for each user, but there has to be a more efficient way.

答:
Instead of creating a new table for each user's sessions, create a table SESSION that holds sessions for all users at once. This satisfies a database design principle called "normalisation" that you should read up on. It is more scalable than creating a new table every time a new user signs up.</p>

```<code>CREATE TABLE SESSION (
    SessionID INT NOT NULL,
    AccountID INT NOT NULL,
    StartDate DATETIME,
    PRIMARY KEY (SessionID),
    CONSTRAINT Constr_SESSION_AccountID_fk
        FOREIGN KEY SESSION_AccountID_fk REFERENCES ACCOUNT (AccountID)
        ON DELETE RESTRICT ON UPDATE RESTRICT
)
</code>```

Title: MySQL Storing Unlimited Data within Row

Body:
Instead of creating a new table for each user's sessions, create a table SESSION that holds sessions for all users at once. This satisfies a database design principle called "normalisation" that you should read up on. It is more scalable than creating a new table every time a new user signs up.

CREATE TABLE SESSION (
    SessionID INT NOT NULL,
    AccountID INT NOT NULL,
    StartDate DATETIME,
    PRIMARY KEY (SessionID),
    CONSTRAINT Constr_SESSION_AccountID_fk
        FOREIGN KEY SESSION_AccountID_fk REFERENCES ACCOUNT (AccountID)
        ON DELETE RESTRICT ON UPDATE RESTRICT
)


问:
ASP NET MVC RAZOR Upload Multiple Images FileList
I'm new in asp net and I have a List of images and I want to send through javascript to the controller.

I'm using FileList and here is an example.
.Create.cshtml

```<code><div class="form-group">
    @Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" })
    <input id="files" type="file" name="files[]" />
    <br>
    <div id="preview"></div>
</div>
@section Scripts{
    <script type="text/javascript">
        function handleFileSelect(evt) {

            var files = evt.target.files;
            var f = files[0];
            //kiem tra co fai file anh
            if (f.type.match('image.*')) {
                var reader = new FileReader();

                reader.onload = (function(theFile) {
                    return function(e) {
                        var span = document.createElement('span');
                        span.innerHTML = [
                            '<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name),
                            '"/><span class="remove_img_preview"></span>'
                        ].join('');
                        document.getElementById('preview').insertBefore(span, null);
                    };
                })(f);

                reader.readAsDataURL(f);
            }
        }

        $('#files').change(function(evt) {
            handleFileSelect(evt);
        });
        $('#preview').on('click',
            '.remove_img_preview',
            function() {
                $(this).parent('span').remove();
            });

        $('#btnSave').click(function() {

            $.ajax({
                url: '/Dishes/Create',
                data: { files: files },
                type: "POST",
                cache: false,
                datatype: "html",
                success: function(data) {
                    console.log(data);
                },
                error: function(jqXhr, textStatus, errorThrown) {
                    //do your own thing
                    alert("fail");
                }
            });
        });

    </script>
}
</fieldset>
<div class="form-group">
    <div class="footer text-center">
        <button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button>
    </div>
</div>
</code>```

Controller.cs

```<code>public ActionResult Create()
    {
        ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name");
        return View();
    }

    // POST: Dishes/Create
    [HttpPost]
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
    {

        return View();

    }
</code>```

In the controller, files are always null.
I'm using that example, http://jsfiddle.net/Lwczca6p/1/, I just adapt to my project.

答:
You've got a few problems. First, you're trying to use files with your AJAX, but that variable was defined in the scope of another function (i.e. you don't have access to it here). Second, when using jQuery's $.ajax to do a file upload, you need to set the processData option to false. Here's how I would handle it:

```<code>$('#MyForm').on('submit', function (e) {
    e.preventDefault();
    var formData = new FormData(this); // `this` is the form instance
    $.ajax({
        url: '/path/to/handler',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        success: function (data, textStatus, jqXHR) {
            // do something on success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // do something on error
        }
    });
});
</code>```

Body:
I'm new in asp net and I have a List of images and I want to send through javascript to the controller.

I'm using FileList and here is an example.
.Create.cshtml

    @Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" })
    <input id="files" type="file" name="files[]" />

@section Scripts{

}
</fieldset>

        <button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button>

Controller.cs

public ActionResult Create()
    {
        ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name");
        return View();
    }

    // POST: Dishes/Create
    [HttpPost]
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
    {

        return View();

    }

In the controller, files are always null.
I'm using that example, http://jsfiddle.net/Lwczca6p/1/, I just adapt to my project.

Body:
You've got a few problems. First, you're trying to use files with your AJAX, but that variable was defined in the scope of another function (i.e. you don't have access to it here). Second, when using jQuery's $.ajax to do a file upload, you need to set the processData option to false. Here's how I would handle it:

$('#MyForm').on('submit', function (e) {
    e.preventDefault();
    var formData = new FormData(this); // `this` is the form instance
    $.ajax({
        url: '/path/to/handler',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        success: function (data, textStatus, jqXHR) {
            // do something on success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // do something on error
        }
    });
});


问:
bazel build tensorflow/python/tools:strip_unused compilation failure
I am trying to run this bazel command from within my docker image

```<code>docker run -it  gcr.io/tensorflow/tensorflow:latest-devel
cd /tensorflow
bazel build tensorflow/python/tools:strip_unused
</code>```

However it fails with this error:

```<code>ERROR: /tensorflow/tensorflow/core/kernels/BUILD:1970:1: C++ compilation of rule '//tensorflow/core/kernels:svd_op' failed: gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -B/usr/bin -B/usr/bin -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG ... (remaining 107 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 4.
gcc: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.
Target //tensorflow/python/tools:strip_unused failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 609.363s, Critical Path: 456.46s
</code>```

答: This is probably because you ran out of RAM. Please post the output of dmesg | tail right after the build fails.

Body:
I am trying to run this bazel command from within my docker image

docker run -it  gcr.io/tensorflow/tensorflow:latest-devel
cd /tensorflow
bazel build tensorflow/python/tools:strip_unused

However it fails with this error:

ERROR: /tensorflow/tensorflow/core/kernels/BUILD:1970:1: C++ compilation of rule '//tensorflow/core/kernels:svd_op' failed: gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -B/usr/bin -B/usr/bin -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG ... (remaining 107 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 4.
gcc: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.
Target //tensorflow/python/tools:strip_unused failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 609.363s, Critical Path: 456.46s


问:
C++/CLI cli::array<double,2>, how to access from CS .NET?
I'll preface this with the fact I don't know either language besides tinkering with others' code.  But I'm modifying code to vectorize it and have the C++/CLI portion figured out as this structure:
cli::array<double,2>^% vols
Initialized like this:
vols = gcnew cli::array<double, 2>(2,dealIDs->Length);
So that all compiles fine and I have a 2D array with 2x (Length of dealsID) on the C++ side.  Now on the NET side I'm not sure the correct declaration. What is this the correct .NET CS format to access my 2xN structured C++/CLI array?  Much appreciated.

答:
```<code>gcnew cli::array<double, 2>(2,dealIDs->Length);
</code>```

would be in C# syntax

```<code>new double[2, deals.Length]
</code>```

A List<T> is not an array.

Body:
gcnew cli::array<double, 2>(2,dealIDs->Length);

would be in C# syntax

new double[2, deals.Length]

A List<T> is not an array.


问:
Yo-yo effect on animation don't work when repeat is indefinite and direction is alternate using A-frame
I'll make some indefinite animations inside my A-frame web application. My animation must play infinity and must have a yo-yo effect. Form an opacity of 0.25 to 0.75 an back each in 3000 millisecondes. For this I use next code:

let box = document.createElement('a-box');
box.setAttribute('src', '#outer');
box.setAttribute('position', '0 0 -5');
box.setAttribute('color', 'red');

let anim = document.createElement('a-animation');
anim.setAttribute('attribute', 'opacity');
anim.setAttribute('from', '0.25');
anim.setAttribute('to', '0.75');
anim.setAttribute('fill', 'both');
anim.setAttribute('repeat', 'indefinite');
anim.setAttribute('dur', '3000');
anim.setAttribute('direction', 'alternate');
box.appendChild(anim);

document.getElementsByTagName('a-scene')[0].appendChild(box);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>

<a-scene></a-scene></code>```

Like you can see this is not working. It goes from 0.25 to 0.75 in 3000 millisecondes and instantly back to 0.25 to repeat again. In the documentation of A-frame stand this:

When we define an alternating direction, the animation will go back and forth between the from and to values like a yo-yo. Alternating directions only take affect when we repeat the animation.

If I use an number (example the number x) instead of indefinite, the yo-yo effect works great but stops when it's x-times repeated.

What could I do for fix this issue?

答:
i think it's fixed by throwing out the fill attribute

```<code>anim.setAttribute('fill', 'both');
</code>```

Its supposed to handle the animation when its not playing, i guess when the replay is indefinite, its playing all the time and either tween.js or three.js don't like it.

Working demo based on Your code:
https://codepen.io/gftruj/pen/qjdZmw

I tried setting it to 'none' or whatever, but i only got it working while thrown out.

Body:
I'll make some indefinite animations inside my A-frame web application. My animation must play infinity and must have a yo-yo effect. Form an opacity of 0.25 to 0.75 an back each in 3000 millisecondes. For this I use next code:

let box = document.createElement('a-box');
box.setAttribute('src', '#outer');
box.setAttribute('position', '0 0 -5');
box.setAttribute('color', 'red');

let anim = document.createElement('a-animation');
anim.setAttribute('attribute', 'opacity');
anim.setAttribute('from', '0.25');
anim.setAttribute('to', '0.75');
anim.setAttribute('fill', 'both');
anim.setAttribute('repeat', 'indefinite');
anim.setAttribute('dur', '3000');
anim.setAttribute('direction', 'alternate');
box.appendChild(anim);

document.getElementsByTagName('a-scene')[0].appendChild(box);

Like you can see this is not working. It goes from 0.25 to 0.75 in 3000 millisecondes and instantly back to 0.25 to repeat again. In the documentation of A-frame stand this:

When we define an alternating direction, the animation will go back and forth between the from and to values like a yo-yo. Alternating directions only take affect when we repeat the animation.

If I use an number (example the number x) instead of indefinite, the yo-yo effect works great but stops when it's x-times repeated.

What could I do for fix this issue?

Body:
i think it's fixed by throwing out the fill attribute

anim.setAttribute('fill', 'both');

Its supposed to handle the animation when its not playing, i guess when the replay is indefinite, its playing all the time and either tween.js or three.js don't like it.

Working demo based on Your code:
https://codepen.io/gftruj/pen/qjdZmw

I tried setting it to 'none' or whatever, but i only got it working while thrown out.


问:
Laravel multiple databases PHPUnit
I am developing a application with multiple database access and I want to have PHPUnit tests with this. My current approache is to have in the config\databases.php multiple connections (mysql, mysql2, mysql3) so I can have in the env file a different access for all of them. Because of this, the models have the $connection variable defined. In my first feature test I want to access a page and just see the data that I am providing in my factory, so just to get things started. In my phpunit.xml file I have specified the DB_CONNECTION to be sqlite and for each of the MySql setting to have the value=":memory:".

LATER EDIT

```<code><php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE_1" value=":memory:"/>
    <env name="DB_DATABASE_2" value=":memory:"/>
    <env name="DB_DATABASE_3" value=":memory:"/>
</php>
</code>```

So above you can find the relevant code from PHPUnit.

.env

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db1
DB_USERNAME=xxx
DB_PASSWORD=xxx

DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=db2
DB_USERNAME_2=xxx
DB_PASSWORD_2=xxx

DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_3=db3
DB_USERNAME_3=xxx
DB_PASSWORD_3=xxx
</code>```

The problem that I have is the fact that when I run the tests, i have this error -> PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:'.

So somehow Laravel is not parsing the memory value. Any suggestion will be mush appreciated.
Thank you

答:
Hard to decode where you actually put the :memory: value.

In the phpunit.xml <php> section, this should be sufficient (assuming you haven't modified the sqlite connection):

```<code><php>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
</php>
</code>```

Title: Laravel multiple databases PHPUnit

Body:
I am developing a application with multiple database access and I want to have PHPUnit tests with this. My current approache is to have in the config\databases.php multiple connections (mysql, mysql2, mysql3) so I can have in the env file a different access for all of them. Because of this, the models have the $connection variable defined. In my first feature test I want to access a page and just see the data that I am providing in my factory, so just to get things started. In my phpunit.xml file I have specified the DB_CONNECTION to be sqlite and for each of the MySql setting to have the value=":memory:".

LATER EDIT

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE_1" value=":memory:"/>
    <env name="DB_DATABASE_2" value=":memory:"/>
    <env name="DB_DATABASE_3" value=":memory:"/>
</php>

So above you can find the relevant code from PHPUnit.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db1
DB_USERNAME=xxx
DB_PASSWORD=xxx

DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=db2
DB_USERNAME_2=xxx
DB_PASSWORD_2=xxx

DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_3=db3
DB_USERNAME_3=xxx
DB_PASSWORD_3=xxx

The problem that I have is the fact that when I run the tests, i have this error -> PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:'.

So somehow Laravel is not parsing the memory value. Any suggestion will be mush appreciated.
Thank you

Body:
Hard to decode where you actually put the :memory: value.

In the phpunit.xml <php> section, this should be sufficient (assuming you haven't modified the sqlite connection):

<php>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
</php>


问:
log10 of a Vector3f (Eigen Libs)
I need to calculate the log10 of a Vector3f.
I have tried:

```<code>Eigen::Vector3f valsingn = svd.singularValues()/svd.singularValues()(0);
valsingn = valsingn.log10();
</code>```

But it doesn't work.

```<code>main.cpp:145:27: error: ‘Eigen::Vector3f {aka class Eigen::Matrix<float, 3, 1>}’ has no member named ‘log10’; did you mean ‘log’?
     valsingn = valsingn.log10();
</code>```

Is there a way to calculate the log10 with this vector?

Thank you!

答:
You need to move to the array world for pure coefficient-wise functions:</p>

```<code>Vector3f v, w;
w = v.array().log10();
w = log10(v.array());
Arrayt3f a, b;
b = a.log10();
b = log10(a);
</code>```

Title: log10 of a Vector3f (Eigen Libs)

Body:
I need to calculate the log10 of a Vector3f.
I have tried:

Eigen::Vector3f valsingn = svd.singularValues()/svd.singularValues()(0);
valsingn = valsingn.log10();

But it doesn't work.

main.cpp:145:27: error: ‘Eigen::Vector3f {aka class Eigen::Matrix<float, 3, 1>}’ has no member named ‘log10’; did you mean ‘log’?
     valsingn = valsingn.log10();

Is there a way to calculate the log10 with this vector?

Thank you!

Body:
You need to move to the array world for pure coefficient-wise functions:

Vector3f v, w;
w = v.array().log10();
w = log10(v.array());
Arrayt3f a, b;
b = a.log10();
b = log10(a);


问:
Building an installer, to install dlls to the gac, with MSBuild
I have a dll project which I need to install into the GAC, on our Production machines.
(I wish I didn't have to use the GAC but SSIS insists)

gacutil.exe is not available on the target machines and using "Enterprise.Services" from PowerShell does not work (I don't know why)

My understanding is I should created a msi installer project.

However after installing the Setup and Deploy Extension to Visual Studio (2015 soon to be 2017), I discovered those projects cannot be built by our Build Server because it uses MSBuild, and MSBuild can't build vdproj project files.

What is the correct way, using a CI build pipeline (MSBuild), to create build artifacts, which can install dlls to the GAC, of a Production Environment?

Note: there are several partial answers on SO, but I could not find any, which were up to date/answer my whole question. Please keep that in mind when answering.

答:
You need to break this down into several user stories.   You aren't finding partial answers, you are finding actual answers for specific questions.  What you ask is more like an epic.

In general I would create an MSI using Windows Installer XML.  WiX/MSI can install files to the GAC without using GACUTIL.  If you use the WiX Visual Studio extension "Votive"  you can create a .SLN  / .WIXPROJ / .WXS  that can be built using MSBuild.  You can then put this into a source control system such as Git/TFVC/Subversion and use a build system such as VSTS V.Next Build, XAML Build, Concourse, Jenkins  to automation the pipeline to build the MSI.


问:
Android UI elements in unity
I'm designing an AR andorid application with Vufoira and Unity.Then; I want to add components like side bars in the camera view(Vuforia Scenes). But since I'm new on unity i don't know how to achieve since UI elements in Unity are pretty tough for me.

I bought this component to design easier my App views and also has build-ed views which you can modify quickly.Even though, Adding side bars on the camera views seems to be hard.

UI builder

Any advice,tutorials you can give me on programming android events for achieving side Bar effects  in Unity i'd be great.

答:
There is no way to use Android or iOS UI element directly in an Unity game/project. Unity has his own GUI abstraction, so you don't have worry about the code for a button in Android, iOS or PC game.

GUI in Unity (since Unity 5) are basically images that simulates buttons, bars, menus, etc... so, you can create beautiful ui if you have nice design skills.

If you wanna use Android style gui elements you must create every image that represent that component and you must create the code to achieve the behavior desired (so, this could be hard to complex android gui component like tabLayout o NavigationDrawer).

I found a project from a person who wants use iOS gui elements in unity, so he created the images and code for each component, still in beta but works nice for me:

https://forum.unity3d.com/threads/released-ios-for-unity-ui-ios-user-interface-design-for-unity.282399/

Title: Android UI elements in unity


问:
Extracting keyboard layouts from windows
OK, this is a slightly weird question.

We have a touch-screen application (i.e., no keyboard). When users need to enter text, the application shows virtual keyboard - hand-built in WinForms.

Making these things by hand for each new language is monkey work. I figure that windows must have this keyboard layout information hiding somewhere in some dll. Would there be anyway to get this information out of windows?

Other ideas welcome (I figure at least generating the thing from a xml file has got to be better than doing it by hand in VS).

(Note: having said all which, I note that there is a Japanese keyboard, state machine and all..., so XML might not be sufficient)

UPDATE: pretty good series on this subject (I believe) here

答:
I know where are these DLL files' path:

In your registry, you see:

```<code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts
</code>```

where each branch has some value like "Layout File"="KBDSP.dll". The root directory is

```<code>C:\Windows\System32
</code>```

and

```<code>C:\Windows\SystemWOW64
</code>```

Those are all the keyboard layout files are located. For example, KBDUS.dll means "keyboard for US".

I tried to substitute the DLL file with my custom DLL made by MSKLC, and I found it loads the layout mapping images automatically in the "Language" - "input method" - "preview":

So we know that the mapping is there in the DLL.

OwnerDisplayName: Benjol

LastEditorDisplayName: Benjol

Body:
I know where are these DLL files' path:

In your registry, you see:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts

where each branch has some value like "Layout File"="KBDSP.dll". The root directory is

C:\Windows\System32

and

C:\Windows\SystemWOW64

Those are all the keyboard layout files are located. For example, KBDUS.dll means "keyboard for US".

I tried to substitute the DLL file with my custom DLL made by MSKLC, and I found it loads the layout mapping images automatically in the "Language" - "input method" - "preview":

So we know that the mapping is there in the DLL.


问:
Round to Highest Factor with Variable Scale?
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

```<code>num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000
</code>```

答:
try this:</p>

```<code>function num_to_scale($number) {
    $num = (int) floor($number);
    $ln = strlen($num) - 1;

    return (int) floor($num / pow(10, $ln)) * pow(10, $ln);
}
</code>```

Body:
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000

Body:
try this:

function num_to_scale($number) {
    $num = (int) floor($number);
    $ln = strlen($num) - 1;

    return (int) floor($num / pow(10, $ln)) * pow(10, $ln);
}


问:
Get the first ocurrence of a string in a variable REGEX
I have the following variable in a database: PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT and I want to split it into two variables, the first will be PSC-CAMPO-GRANDE-I08 and the second V00-C09-H09-IPRMKT.

I'm trying the regex .*(\-I).*(\-V), this doesn't work. Then I tried .*(\-I), but it gets the last -IPRMKT string.

Then my question is: There a way of split the string PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT considering the first occurrence of -I?

答:
This should do the trick:

```<code>regex = "(.*?-I[\d]{2})-(.*)"
</code>```

Here is test script in Python

```<code>import re

regex = "(.*?-I[\d]{2})-(.*)"

match = re.search(regex, "PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT")
if match:
    print ("yep")
    print (match.group(1))
    print (match.group(2))
else:
    print ("nope")
</code>```

In the regex, I'm grabbing everything up to the first -I then 2 numbers.  Then match but don't capture a -.  Then capture the rest.  I can help tweak it if you have more logic that you are trying to do.

Body:
This should do the trick:

regex = "(.*?-I[\d]{2})-(.*)"

Here is test script in Python

import re

regex = "(.*?-I[\d]{2})-(.*)"

match = re.search(regex, "PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT")
if match:
    print ("yep")
    print (match.group(1))
    print (match.group(2))
else:
    print ("nope")

In the regex, I'm grabbing everything up to the first -I then 2 numbers.  Then match but don't capture a -.  Then capture the rest.  I can help tweak it if you have more logic that you are trying to do.


问:
Css selector: first/last-of-type and has another class
In a simple pager I'm building I need to apply specific style to the current page if the current page is the first or the last page. And I don't know how to use the :first-of-type/ :last-of-type selector in addition to the normal class selector.

```<code>   <div id="myPages">
      <div class="something-else"></div>
      <div class="page-number current-page">1</div>
      <div class="page-number">2</div>
      <div class="page-number">3</div>
      <div class="another-one"></div>
  </div>
</code>```

I'd like something like #myPages .page-number:first-of-type.current-page but it does not work because of the something-else and  another-one div.

In my jsFiddle for example, I'd like the '1' to be blue.

Thanks for your help.

[edit] I've updated the fiddle, I think it's the best way to get my idea :)

答:
UPDATE: As the post author has changed their question, I've updated my answer:

#explain {
  margin-bottom: 20px;
}

#myPages .something-else+.current-page {
  color: blue;
}

#myPages div:nth-last-child(2) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="explain">
  Please note:<br> - there will be only one 'page-number' with 'current-page' in my app<br> - I don't know in advance how many pages there will be (so nth-child cannot work)
</div>
<div id="myPages">
  <div class="something-else"></div>
  <div class="page-number current-page">1 - Should be blue because it is the first page-number <strong>and</strong> it has the current-page class</div>
  <div class="page-number">2</div>
  <div class="page-number current-page">3 - Nothing should happen</div>
  <div class="page-number current-page">4 - Should be red because it is the last page-number <strong>and</strong> it has the current-page class</div>
  <div class="another-one"></div>
</div></code>```

Body:
In a simple pager I'm building I need to apply specific style to the current page if the current page is the first or the last page. And I don't know how to use the :first-of-type/ :last-of-type selector in addition to the normal class selector.

1

2

3

I'd like something like #myPages .page-number:first-of-type.current-page but it does not work because of the something-else and  another-one div.

In my jsFiddle for example, I'd like the '1' to be blue.

Thanks for your help.

[edit] I've updated the fiddle, I think it's the best way to get my idea :)

Body:
UPDATE: As the post author has changed their question, I've updated my answer:

#explain {
  margin-bottom: 20px;
}

#myPages .something-else+.current-page {
  color: blue;
}

#myPages div:nth-last-child(2) {
  color: red;
}

<div id="explain">
  Please note:<br> - there will be only one 'page-number' with 'current-page' in my app<br> - I don't know in advance how many pages there will be (so nth-child cannot work)
</div>
<div id="myPages">
  <div class="something-else"></div>
  <div class="page-number current-page">1 - Should be blue because it is the first page-number <strong>and</strong> it has the current-page class</div>
  <div class="page-number">2</div>
  <div class="page-number current-page">3 - Nothing should happen</div>
  <div class="page-number current-page">4 - Should be red because it is the last page-number <strong>and</strong> it has the current-page class</div>
  <div class="another-one"></div>
</div>


问:
Controller does't work in Spring web error 404
I do this lesson  but my controller don't work error 404, before it worked well. jsp files work well. does't work only controller. The console has no errors.
What happened?

Controller:

```<code>@Controller
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String printHello(ModelMap model) {
        model.addAttribute("message", "Hello Spring MVC Framework!");
        return "hello";
    }
}
</code>```

web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
  <display-name>Servlets</display-name>
   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>*.jsp</url-pattern>
   </servlet-mapping>
</web-app>
</code>```

HelloWeb-servlet.xml:

```<code><beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.tutorialspoint" />

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>

</beans>
</code>```

hello.jsp

```<code><html>
   <head>
      <title>Hello Spring MVC</title>
   </head>

   <body>
      <h2>${message}</h2>
   </body>
</html>
</code>```

Folder structure

答:
A couple of things I'm noticing.

1) An <?xml tag declaration within a web.xml file is actually not allowed.  Your JSP editor within Eclipse should have indicated an error.  Please remove <?xml version="1.0" encoding="UTF-8"?>

2) I think you are running into issues between default servlet container handlers and mappings for the Dispatcher servlet.  Can you change the servlet mapping in your web.xml file from

```<code><servlet-mapping>
  <servlet-name>HelloWeb</servlet-name>
  <url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</code>```

to

```<code><servlet-mapping>
  <servlet-name>HelloWeb</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

which is the default handling for Spring dispatcher.

I would perform those changes, perform a rebuild of your project, redeploy to your container and try hitting your controller mapping http://<yourhost_root>/HelloWeb/hello/

Body:
I do this lesson  but my controller don't work error 404, before it worked well. jsp files work well. does't work only controller. The console has no errors.
What happened?

Controller:

@Controller
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String printHello(ModelMap model) {
        model.addAttribute("message", "Hello Spring MVC Framework!");
        return "hello";
    }
}

web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
  <display-name>Servlets</display-name>
   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>*.jsp</url-pattern>
   </servlet-mapping>
</web-app>

HelloWeb-servlet.xml:

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.tutorialspoint" />

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>

</beans>

hello.jsp

      <title>Hello Spring MVC</title>

${message}

Folder structure

Body:
A couple of things I'm noticing.

1) An <?xml tag declaration within a web.xml file is actually not allowed.  Your JSP editor within Eclipse should have indicated an error.  Please remove <?xml version="1.0" encoding="UTF-8"?>

2) I think you are running into issues between default servlet container handlers and mappings for the Dispatcher servlet.  Can you change the servlet mapping in your web.xml file from

<servlet-mapping>
  <servlet-name>HelloWeb</servlet-name>
  <url-pattern>*.jsp</url-pattern>
</servlet-mapping>

to

<servlet-mapping>
  <servlet-name>HelloWeb</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

which is the default handling for Spring dispatcher.

I would perform those changes, perform a rebuild of your project, redeploy to your container and try hitting your controller mapping http://<yourhost_root>/HelloWeb/hello/


问:
How to loop over form field choices and display associated model instance fields
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

```<code>#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}
</code>```

答:
I think, you can define own widget class inherited from CheckboxSelectMultiple with your own render() method and customize html output.
See source code, line 690

It'll be reusable in any template as well.

Body:
I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How  do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}


问:
Exception Handling SQL
I created a user defined function that calculates the quantity in stock for a product

```<code>CREATE OR REPLACE FUNCTION function_quantityInStock(
    oldProductQuantity IN INTEGER,
    orderedQuan IN INTEGER)
    RETURN INTEGER
IS
    v_newQuantity INTEGER;
    v_oldQuantity INTEGER;
    v_orderedQuan INTEGER;
BEGIN
    v_newquantity := oldProductQuantity - orderedQuan;
    RETURN v_newquantity;
EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('Please check your data.');
END function_quantityInstock;
</code>```

I then create a trigger that updates the table by calling the function

```<code>CREATE OR REPLACE TRIGGER TRIGGER_QUANTITY AFTER INSERT ON ordered_product
FOR EACH ROW
DECLARE
    v_oldQuantity INTEGER;
BEGIN
    SELECT PRODUCT_QUANTITYINSTOCK INTO v_oldQuantity
    FROM   product
    WHERE  product_id = :NEW.product_id;

    UPDATE PRODUCT
    SET    product_quantityinstock =
             function_quantityINSTOCK(v_oldQuantity, :NEW.ORDERED_PRODUCTQUANTITY)
    WHERE product_id = :NEW.product_id;
END;
</code>```

I want to display a message when the user enters invalid data but my exception block doesnt do that.

I use the following anonyomus block to test the function:

```<code>SET SERVEROUTPUT ON;

DECLARE
    v_productID    ordered_product.product_id%TYPE:= &ProductID;
    v_orderID      ordered_product.order_id%TYPE:=&OrderID;
    v_orderedQuan  ordered_product.ordered_productQuantity%TYPE := &OrderedProductQuantity;
    v_totalCost    ordered_product.ordered_productTotalCost%TYPE := '&TotalCost';
BEGIN
    INSERT INTO ordered_product VALUES
    (v_orderID, v_productID, v_orderedQuan, v_totalCost);

    dbms_output.put_line('A new record has been inserted.');
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('Invalid data!');
    WHEN VALUE_ERROR THEN
        dbms_output.put_line('Error! Please check your values.'|| SQLERRM);
END;
</code>```

答:
If I were you, I wouldn't rely on dbms_output.put_line to pass information around. Instead, rely on the standard exception handling, e.g. RAISE or RAISE_APPLICATION_ERROR. Also, given that you're trying to find the new quantity, I'd move the select on the product table into the function, something like:

```<code>CREATE OR REPLACE FUNCTION function_quantityinstock(p_product_id IN product.product_product_id p_orderedquan IN INTEGER)
  RETURN INTEGER IS
  v_newquantity INTEGER;

  e_not_enough_stock EXCEPTION;
  e_not_enough_stock_num INTEGER := -20001;

  e_no_product_exists_num INTEGER := -20002;

  PRAGMA EXCEPTION_INIT(e_not_enough_stock, -20001);
BEGIN
  SELECT product_quantityinstock - orderedquan
  INTO   v_newquantity
  FROM   product
  WHERE  product_id = :new.product_id;

  IF v_newquantity < 0
  THEN
    RAISE e_not_enough_stock;
  END IF;

  RETURN v_newquantity;

EXCEPTION
  WHEN no_data_found THEN
    raise_application_error(-e_no_product_exists_num,
                    'No product exists for product_id = ' || product_id);

  -- no need to check for TOO_MANY_ROWS if product_id is the primary/unique key on the product table.
  WHEN e_not_enough_stock THEN
    raise_application_error(e_not_enough_stock_num,
                    'Not enough stock present to fulfil the order for product_id = ' ||
                    product_id);

  WHEN OTHERS THEN
    raise_application_error(SQLCODE,
                    'Unexpected error occurred whilst finding new quantity for product_id = ' ||
                    product_id || ': ' || SQLERRM);

END function_quantityinstock;
/
</code>```

You'd need to change the function name though, to reflect the action that it's doing, since it's returning the new quantity in stock...

Title: Exception Handling SQL

Body:
I created a user defined function that calculates the quantity in stock for a product

CREATE OR REPLACE FUNCTION function_quantityInStock(
    oldProductQuantity IN INTEGER,
    orderedQuan IN INTEGER)
    RETURN INTEGER
IS
    v_newQuantity INTEGER;
    v_oldQuantity INTEGER;
    v_orderedQuan INTEGER;
BEGIN
    v_newquantity := oldProductQuantity - orderedQuan;
    RETURN v_newquantity;
EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('Please check your data.');
END function_quantityInstock;

I then create a trigger that updates the table by calling the function

CREATE OR REPLACE TRIGGER TRIGGER_QUANTITY AFTER INSERT ON ordered_product
FOR EACH ROW
DECLARE
    v_oldQuantity INTEGER;
BEGIN
    SELECT PRODUCT_QUANTITYINSTOCK INTO v_oldQuantity
    FROM   product
    WHERE  product_id = :NEW.product_id;

    UPDATE PRODUCT
    SET    product_quantityinstock =
             function_quantityINSTOCK(v_oldQuantity, :NEW.ORDERED_PRODUCTQUANTITY)
    WHERE product_id = :NEW.product_id;
END;

I want to display a message when the user enters invalid data but my exception block doesnt do that.

I use the following anonyomus block to test the function:

SET SERVEROUTPUT ON;

DECLARE
    v_productID    ordered_product.product_id%TYPE:= &ProductID;
    v_orderID      ordered_product.order_id%TYPE:=&OrderID;
    v_orderedQuan  ordered_product.ordered_productQuantity%TYPE := &OrderedProductQuantity;
    v_totalCost    ordered_product.ordered_productTotalCost%TYPE := '&TotalCost';
BEGIN
    INSERT INTO ordered_product VALUES
    (v_orderID, v_productID, v_orderedQuan, v_totalCost);

    dbms_output.put_line('A new record has been inserted.');
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('Invalid data!');
    WHEN VALUE_ERROR THEN
        dbms_output.put_line('Error! Please check your values.'|| SQLERRM);
END;

Body:
If I were you, I wouldn't rely on dbms_output.put_line to pass information around. Instead, rely on the standard exception handling, e.g. RAISE or RAISE_APPLICATION_ERROR. Also, given that you're trying to find the new quantity, I'd move the select on the product table into the function, something like:

CREATE OR REPLACE FUNCTION function_quantityinstock(p_product_id IN product.product_product_id p_orderedquan IN INTEGER)
  RETURN INTEGER IS
  v_newquantity INTEGER;

  e_not_enough_stock EXCEPTION;
  e_not_enough_stock_num INTEGER := -20001;

  e_no_product_exists_num INTEGER := -20002;

  PRAGMA EXCEPTION_INIT(e_not_enough_stock, -20001);
BEGIN
  SELECT product_quantityinstock - orderedquan
  INTO   v_newquantity
  FROM   product
  WHERE  product_id = :new.product_id;

  IF v_newquantity < 0
  THEN
    RAISE e_not_enough_stock;
  END IF;

  RETURN v_newquantity;

EXCEPTION
  WHEN no_data_found THEN
    raise_application_error(-e_no_product_exists_num,
                    'No product exists for product_id = ' || product_id);

  -- no need to check for TOO_MANY_ROWS if product_id is the primary/unique key on the product table.
  WHEN e_not_enough_stock THEN
    raise_application_error(e_not_enough_stock_num,
                    'Not enough stock present to fulfil the order for product_id = ' ||
                    product_id);

  WHEN OTHERS THEN
    raise_application_error(SQLCODE,
                    'Unexpected error occurred whilst finding new quantity for product_id = ' ||
                    product_id || ': ' || SQLERRM);

END function_quantityinstock;
/

You'd need to change the function name though, to reflect the action that it's doing, since it's returning the new quantity in stock...


问:
OData filter is not working in my web api
I didn't create OData controller, instead, I just installed OData package and add EnableQuery attribute to the IQueryable action method. Here is my method

```<code>    [HttpGet]
    [Route("WoundLocations")]
    [EnableQuery]
    public IQueryable<WoundLocation> GetWoundArea()
    {
        return _lookupService.GetWoundLocation().AsQueryable();
    }
</code>```

And I call the action with the following url

```<code>  http://dev-xxx.xxxx.com/lookup/WoundLocations?filter=Side eq '0'
</code>```

The returned result still has all the records in that table. Any thoughts?

答:
You are missing a $ before the filter keyword, it should be like this:

```<code>http://dev-xxx.xxxx.com/lookup/WoundLocations?$filter=Side eq '0'
</code>```

Body:
I didn't create OData controller, instead, I just installed OData package and add EnableQuery attribute to the IQueryable action method. Here is my method

    [HttpGet]
    [Route("WoundLocations")]
    [EnableQuery]
    public IQueryable<WoundLocation> GetWoundArea()
    {
        return _lookupService.GetWoundLocation().AsQueryable();
    }

And I call the action with the following url

  http://dev-xxx.xxxx.com/lookup/WoundLocations?filter=Side eq '0'

The returned result still has all the records in that table. Any thoughts?

Body:
You are missing a $ before the filter keyword, it should be like this:

http://dev-xxx.xxxx.com/lookup/WoundLocations?$filter=Side eq '0'


问:
Get key from JSON for API request
```<code>[
  {
    "docId": "58d8f38cd2f554fdfca4fd18",
    "__v": 8,
    "clinicDetails": {
      "5908e342236dee7e7364698e": {
        "appointmentSlots": {
          "sat": {
            "5908e342236dee7e73646a44": {
              "bookFlag": true,
              "endTime": "07:00PM",
              "startTime": "06:30PM"
            },
            "5908e342236dee7e73646a43": {
              "bookFlag": true,
              "endTime": "06:30PM",
              "startTime": "06:00PM"
            },
.......
</code>```

full file :
https://docs.google.com/document/d/1FK1NEY1Vmjzv2gBtleFquA0VMpfYGf9FaMyblPr8vws/edit?usp=sharing

I need to access these appointment slot ids like 5908e342236dee7e73646a44, so that I can send it in an API request

I am using angular.

答:
Try to use

var jsonObject = angular.fromJson(yourJsonString)

That will transform your Json to an object. Then you can iterate over any field of the object an get keys or values.

```<code>angular.forEach(jsonObject.whatever, function(value, key) {
  console.log('key : ', key);
  console.log('value : ', value);
});
</code>```

Title: Get key from JSON for API request

Body:
[
  {
    "docId": "58d8f38cd2f554fdfca4fd18",
    "__v": 8,
    "clinicDetails": {
      "5908e342236dee7e7364698e": {
        "appointmentSlots": {
          "sat": {
            "5908e342236dee7e73646a44": {
              "bookFlag": true,
              "endTime": "07:00PM",
              "startTime": "06:30PM"
            },
            "5908e342236dee7e73646a43": {
              "bookFlag": true,
              "endTime": "06:30PM",
              "startTime": "06:00PM"
            },
.......

full file :
https://docs.google.com/document/d/1FK1NEY1Vmjzv2gBtleFquA0VMpfYGf9FaMyblPr8vws/edit?usp=sharing

I need to access these appointment slot ids like 5908e342236dee7e73646a44, so that I can send it in an API request

I am using angular.

Body:
Try to use

var jsonObject = angular.fromJson(yourJsonString)

That will transform your Json to an object. Then you can iterate over any field of the object an get keys or values.

angular.forEach(jsonObject.whatever, function(value, key) {
  console.log('key : ', key);
  console.log('value : ', value);
});


问:
How do you set only certain bits of a byte in C without affecting the rest?
Say I have a byte like this 1010XXXX where the X values could be anything. I want to set the lower four bits to a specific pattern, say 1100, while leaving the upper four bits unaffected. How would I do this the fastest in C?</p>

答:
In general:

```<code>value = (value & ~mask) | (newvalue & mask);
</code>```

mask is a value with all bits to be changed (and only them) set to 1 - it would be 0xf in your case. newvalue is a value that contains the new state of those bits - all other bits are essentially ignored.

This will work for all types for which bitwise operators are supported.

Body:
In general:

value = (value & ~mask) | (newvalue & mask);

mask is a value with all bits to be changed (and only them) set to 1 - it would be 0xf in your case. newvalue is a value that contains the new state of those bits - all other bits are essentially ignored.

This will work for all types for which bitwise operators are supported.


问:
How can I detect if a grouped result of the mySQL database has any related value?
```<code>animal    food
cat
cat       mouse
cat
dog
dog
bird      carrot
bird      herb
bird
</code>```

I have some animals in my mysql database. My problem is that I need to know, if any animal of a animal-group got food.

```<code> $pdo = $db->query('SELECT * FROM list GROUP BY animal');
 while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["food"]){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
  }
}
</code>```

My result is:

```<code>No cat got food.
No dog got food.
No bird got food.
</code>```

But I expect:

```<code>Some cat got food.
No dog got food.
Some bird got food.
</code>```

答:
Please try this code

```<code>$pdo = $db->query("SELECT animal,sum(if(food<>'',1,0)) AS count_of_food FROM
list GROUP BY animal");
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["count_of_food"]>0){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
    }
}
</code>```

edit 1

by checking food<>'',1,0. Let's take the example of cat. for first row it will return 0 because the food column is blank hence 0, for second it will return 1 and third row it will return 0.

And your second question, What if you want check for all animal had food. Just take the count of all animal.

```<code>$pdo = $db->query("SELECT animal,sum(if(food<>'',1,0)) AS count_of_food,count(1) AS total_cnt FROM list GROUP BY animal");
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["count_of_food"]==$row["total_cnt"]){
       echo "All ".$row["animal"]." got food.<br>";
    }else if($row["count_of_food"]>0){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
    }
}
</code>```

Output of second query will be

Body:
animal    food
cat
cat       mouse
cat
dog
dog
bird      carrot
bird      herb
bird

I have some animals in my mysql database. My problem is that I need to know, if any animal of a animal-group got food.

 $pdo = $db->query('SELECT * FROM list GROUP BY animal');
 while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["food"]){
       echo "Some ".$row["animal"]." got food.
";
    } else {
       echo "No " .$row["animal"]. " got food.
";
  }
}

My result is:

No cat got food.
No dog got food.
No bird got food.

But I expect:

Some cat got food.
No dog got food.
Some bird got food.

Body:
Please try this code

$pdo = $db->query("SELECT animal,sum(if(food<>'',1,0)) AS count_of_food FROM
list GROUP BY animal");
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["count_of_food"]>0){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
    }
}

edit 1

by checking food<>'',1,0. Let's take the example of cat. for first row it will return 0 because the food column is blank hence 0, for second it will return 1 and third row it will return 0.

And your second question, What if you want check for all animal had food. Just take the count of all animal.

$pdo = $db->query("SELECT animal,sum(if(food<>'',1,0)) AS count_of_food,count(1) AS total_cnt FROM list GROUP BY animal");
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
    if($row["count_of_food"]==$row["total_cnt"]){
       echo "All ".$row["animal"]." got food.<br>";
    }else if($row["count_of_food"]>0){
       echo "Some ".$row["animal"]." got food.<br>";
    } else {
       echo "No " .$row["animal"]. " got food.<br>";
    }
}

Output of second query will be


问:
Ruby on Rails having more than 1 different column foreign keyed to same table
I am very new to Ruby on Rails but I am decent with SQL. I am currently looking at trying to make an association for two tables... well actually more but this one example should answer my question for all. These are fictional but represent my issue so don't mind if they wouldn't follow best practices...

Tables: USER, LOCA   --- They had once limited table name characters back in the day.

-LOCA

LOCATIONID - PK

-USER

USERID - PK; LIVES_LOCATION - FK (LOCATIONID); WORKS_LOCATION - FK (LOCATIONID); MANAGERID....... etc

How do in Ruby on Rails, make the class with belongs_to and has_many with the correct foreign_key names to the correct columns?

答:
```<code>class User
  belongs_to :lives, class_name: 'Loca', foreign_key: 'lives_location'
  belongs_to :works, class_name: 'Loca', foreign_key: 'works_location'

  ...
end

class Loca
  has_many :users

  ...
end
</code>```


问:
Angular 2 : what make a service to be "Outside" angular zone?
After having same issues as many people on StackOverflow i didn't manage to understand what is an  "Outside angular zone" Service ?

I've checks all existing questions  around this subject, and it's exactly why i needer to ask this one :

https://github.com/angular/angular/issues/5150

Angular2: view is not updated from inside a subscription

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

http://blog.assaf.co/angular-2-change-detection-zones-and-an-example/

Code Example in any component with default ChangeDetectionStrategy :
(considering this.value referenced in view)

```<code>this.myService.method().subscribe(e => {
    this.value = e;
  });
</code>```

Is the given service is not "Outside angular zone", the view is refreshed, on the other hand, if it's "Outside angular zone", the view is not refreshed, unless we call ChangeDetectorRef.detectChanges().

So the question is : what the condition to know if a service is Inside or Outside "Angular Zone" ?

答: As far as I know, it is not possible to check whether something runs "Inside" or "Outside" angular zone. If you use zone.runOutsideAngular it runs outside your zone. Second comes to my mind: Why would you want to know?

Body:
After having same issues as many people on StackOverflow i didn't manage to understand what is an  "Outside angular zone" Service ?

I've checks all existing questions  around this subject, and it's exactly why i needer to ask this one :

https://github.com/angular/angular/issues/5150

Angular2: view is not updated from inside a subscription

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

http://blog.assaf.co/angular-2-change-detection-zones-and-an-example/

Code Example in any component with default ChangeDetectionStrategy :
(considering this.value referenced in view)

this.myService.method().subscribe(e => {
    this.value = e;
  });

Is the given service is not "Outside angular zone", the view is refreshed, on the other hand, if it's "Outside angular zone", the view is not refreshed, unless we call ChangeDetectorRef.detectChanges().

So the question is : what the condition to know if a service is Inside or Outside "Angular Zone" ?


问:
Run time Error 1004: Method 'Select' of Object 'Sheets' failed
I don't know why this is making a run time error. It is supposed to select the sheets in workbook 1 to copy them in workbook 2. Can anyone help me?
Debugging shows that the error is in the line: "ActiveWorkbook.Sheets.Select"</p>

```<code>Private Sub CommandButton1_Click()
'On Error GoTo ErrorHandler
If cef.path = "" Then
    MsgBox ("PATH of pictures is required")
Else
    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Dim num As Double

    Set WB1 = ActiveWorkbook
    ActiveWorkbook.Sheets("Item_number").Visible = True
    ActiveWorkbook.Sheets("CODES").Visible = True
    ActiveWorkbook.Sheets("Item_Number_Hydro").Visible = True
    ActiveWorkbook.Sheets.Select
    ActiveWindow.SelectedSheets.Copy
    Set WB2 = ActiveWorkbook
    Dim nombreHoja As String
</code>```

答:
You must have some hidden sheets in the workbook. You cannot select hidden worksheets, and so you cannot Activeworkbook.Sheets.Select which attempts to select all the sheets.

You don't actually need to use Select. But you can copy all the sheets without selecting them, including hidden ones:

```<code>ActiveWorkbook.Sheets.copy
</code>```

Or, copy an array of specific sheets (without Select):

```<code>ActiveWorkbook.Sheets(Array("Item_number","CODES","Item_Number_Hydro")).Copy
</code>```

Body:
I don't know why this is making a run time error. It is supposed to select the sheets in workbook 1 to copy them in workbook 2. Can anyone help me?
Debugging shows that the error is in the line: "ActiveWorkbook.Sheets.Select"

Private Sub CommandButton1_Click()
'On Error GoTo ErrorHandler
If cef.path = "" Then
    MsgBox ("PATH of pictures is required")
Else
    Dim WB1 As Workbook
    Dim WB2 As Workbook

    Dim num As Double

    Set WB1 = ActiveWorkbook
    ActiveWorkbook.Sheets("Item_number").Visible = True
    ActiveWorkbook.Sheets("CODES").Visible = True
    ActiveWorkbook.Sheets("Item_Number_Hydro").Visible = True
    ActiveWorkbook.Sheets.Select
    ActiveWindow.SelectedSheets.Copy
    Set WB2 = ActiveWorkbook
    Dim nombreHoja As String

Body:
You must have some hidden sheets in the workbook. You cannot select hidden worksheets, and so you cannot Activeworkbook.Sheets.Select which attempts to select all the sheets.

You don't actually need to use Select. But you can copy all the sheets without selecting them, including hidden ones:

ActiveWorkbook.Sheets.copy

Or, copy an array of specific sheets (without Select):

ActiveWorkbook.Sheets(Array("Item_number","CODES","Item_Number_Hydro")).Copy


问:
Angular JS: Failed to instantiate module myApp
i was testing a small angular directives code then i got the error by firebug console that Failed to instantiate module myApp

see and tell me what is wrong in the above code

```<code>  <div ng-app="myApp">
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
  </div>

var myApp = angular.module('myApp', []);

myApp.directive('log', function() {

  return {
    controller: function( $scope, $attrs ) {
      console.log( $attrs.log + ' (controller)' );
    },
    compile: function compile( tElement, tAttributes ) {
      console.log( tAttributes.log + ' (compile)'  );
      return {
        pre: function preLink( scope, element, attributes ) {
          console.log( attributes.log + ' (pre-link)'  );
        },
        post: function postLink( scope, element, attributes ) {
          console.log( attributes.log + ' (post-link)'  );
        }
      };
    }
  };

});
</code>```

答:
Where it says
compile: function compile( tElement, tAttributes ) {

I think it should say
compile: function( tElement, tAttributes ) {

Same difference at the pre: and post: functions a bit further down.

Edit: Your real issue is that your last line needs to invoke the function like so:
})();

Body:
i was testing a small angular directives code then i got the error by firebug console that Failed to instantiate module myApp

see and tell me what is wrong in the above code

Have a look at you console!

var myApp = angular.module('myApp', []);

myApp.directive('log', function() {

  return {
    controller: function( $scope, $attrs ) {
      console.log( $attrs.log + ' (controller)' );
    },
    compile: function compile( tElement, tAttributes ) {
      console.log( tAttributes.log + ' (compile)'  );
      return {
        pre: function preLink( scope, element, attributes ) {
          console.log( attributes.log + ' (pre-link)'  );
        },
        post: function postLink( scope, element, attributes ) {
          console.log( attributes.log + ' (post-link)'  );
        }
      };
    }
  };

});