问:
read file from SFTP and dump to local folder using mulesoft
Can someone provide me an mulesoft xml where the flow is reading files from SFTP location and dumping it to the local directory.

I have written following code but it does not work:
subflow :

```<code>    <sub-flow name="loadFtpFile">
    <logger message="Load FTP File: #[flowVars.fileName]" level="INFO" doc:name="Load FTP File"/>
    <logger message="#[payload]" level="DEBUG" doc:name="Log Payload"/>
</sub-flow>
</code>```

And the flow is :

```<code><flow name="readFTP">
     <logger message="Read FTP file" level="INFO" doc:name="Read FTP file"/>
    <set-variable variableName="sftpEndpoint" value="sftp://{someUser}:{password}@{host}:22/incoming/test" doc:name="Set SFTP Endpoint"/>
    <set-variable variableName="fileName" value="debug.log" doc:name="Set File Name"/>
    <flow-ref name="loadFtpFile" doc:name="loadFtpFile"/>
   <file:outbound-endpoint path="C:\Users\Vikas\home\product" responseTimeout="10000" doc:name="Templocation" />
</code>```

答:
here is a example from the official documentation.

configuation:

```<code><mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"
      xmlns:file="http://www.mulesoft.org/schema/mule/file"
      xmlns:spring="http://www.springframework.org/schema/beans"
      xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
          http://www.mulesoft.org/schema/mule/sftp http://www.mulesoft.org/schema/mule/sftp/current/mule-sftp.xsd
          http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
          http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">

    <!-- This placeholder bean lets you import the properties from the sftp.properties file. -->
    <spring:bean id="property-placeholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <spring:property name="location" value="classpath:sftp.properties"/>
    </spring:bean>

    <flow name="sftp2file">
        <sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
                    <file:filename-wildcard-filter pattern="*.txt,*.xml"/>
                </sftp:inbound-endpoint>
        <file:outbound-endpoint path="/tmp/incoming" outputPattern="#[message.inboundProperties.originalFilename]"/>
    </flow>
</mule>
</code>```

and here the references properties file:

```<code>sftp.user=memyselfandi
sftp.host=localhost
sftp.port=8081
sftp.password=icannottellyou
</code>```

try it out and feel free to ask more precise queation.

Body:
Can someone provide me an mulesoft xml where the flow is reading files from SFTP location and dumping it to the local directory.

I have written following code but it does not work:
subflow :

    <logger message="Load FTP File: #[flowVars.fileName]" level="INFO" doc:name="Load FTP File"/>
    <logger message="#[payload]" level="DEBUG" doc:name="Log Payload"/>

And the flow is :

<flow name="readFTP">
     <logger message="Read FTP file" level="INFO" doc:name="Read FTP file"/>
    <set-variable variableName="sftpEndpoint" value="sftp://{someUser}:{password}@{host}:22/incoming/test" doc:name="Set SFTP Endpoint"/>
    <set-variable variableName="fileName" value="debug.log" doc:name="Set File Name"/>
    <flow-ref name="loadFtpFile" doc:name="loadFtpFile"/>
   <file:outbound-endpoint path="C:\Users\Vikas\home\product" responseTimeout="10000" doc:name="Templocation" />

Body:
here is a example from the official documentation.

configuation:

<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"
      xmlns:file="http://www.mulesoft.org/schema/mule/file"
      xmlns:spring="http://www.springframework.org/schema/beans"
      xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
          http://www.mulesoft.org/schema/mule/sftp http://www.mulesoft.org/schema/mule/sftp/current/mule-sftp.xsd
          http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
          http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">

    <!-- This placeholder bean lets you import the properties from the sftp.properties file. -->
    <spring:bean id="property-placeholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <spring:property name="location" value="classpath:sftp.properties"/>
    </spring:bean>

    <flow name="sftp2file">
        <sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
                    <file:filename-wildcard-filter pattern="*.txt,*.xml"/>
                </sftp:inbound-endpoint>
        <file:outbound-endpoint path="/tmp/incoming" outputPattern="#[message.inboundProperties.originalFilename]"/>
    </flow>
</mule>

and here the references properties file:

sftp.user=memyselfandi
sftp.host=localhost
sftp.port=8081
sftp.password=icannottellyou

try it out and feel free to ask more precise queation.


来源: stackexchange

问:
How to retrieve specific value of key in json?
this is my json content.

```<code> [
  {
    "sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
     "commit":{
     "author":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "committer":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "message":"Merge branch '1.5.x'",

   }
 }
 ]
</code>```

and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.

```<code>    NSMutableArray *CommitArray = [[NSMutableArray alloc] init];

    for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        commitDictObj.message = [CommitDictionary objectForKey:@"message"];

        for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:@"committer"]) {
            Committer *author = [[Committer alloc] init];
            author.name = [CommitterDictionary objectForKey:@"name"];
            author.email = [CommitterDictionary objectForKey:@"email"];
            author.date = [CommitterDictionary objectForKey:@"date"];
        }

        [CommitArray addObject:commitDictObj];
    }

    for (int i =0 ; i < [CommitArray count] ; i++){
        CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
        NSLog(@"Commit Message: %@", commitDictObj.message);

    }

     return 0;
}

}
</code>```

i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?

答:
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:

```<code>for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
</code>```

With that:

```<code>for (NSDictionary *shaCommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:@"commit"];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is my json content.

 [
  {
    "sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
     "commit":{
     "author":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "committer":{
        "name":"Madhura Bhave",
        "email":"mbhave@pivotal.io",
        "date":"2017-03-23T23:14:32Z"
     },
     "message":"Merge branch '1.5.x'",

   }
 }
 ]

and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.

    NSMutableArray *CommitArray = [[NSMutableArray alloc] init];

    for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        commitDictObj.message = [CommitDictionary objectForKey:@"message"];

        for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:@"committer"]) {
            Committer *author = [[Committer alloc] init];
            author.name = [CommitterDictionary objectForKey:@"name"];
            author.email = [CommitterDictionary objectForKey:@"email"];
            author.date = [CommitterDictionary objectForKey:@"date"];
        }

        [CommitArray addObject:commitDictObj];
    }

    for (int i =0 ; i < [CommitArray count] ; i++){
        CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
        NSLog(@"Commit Message: %@", commitDictObj.message);

    }

     return 0;
}

}

i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?

Body:
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:

for (NSDictionary *CommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];

With that:

for (NSDictionary *shaCommitDictionary in CommitJson) {
        CommitDict *commitDictObj = [[CommitDict alloc] init];
        NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:@"commit"];


问:
How to set up and using GeoIP Lite
I need to be able to use the MaxMind GeoLite version to find the users Country, City and Longitude/Latitude. The databases are an obvious for which ones I need, apart from the one needed for the longitude/latitude.

Databases needed;

GeoLite Country

GeoLite City

What other one do I need or can the longitude/latitude be found via the above databases?

There are multiple versions you can download. Below is a list of ones you can download;

Binary / gzip

Binary / xz

CSV / gzip

CSV / zip

CSV / xz

I do not understand what these mean and would like some help to determine which one I will need to download.

Although I'm able to on my 1and1 business account, I have not yet done anything to do with databases. Could anyone give me insights in how I set up a database and upload these files to it?

Lastly, where can I find help on using my new database, reading from it, echoing the users location and whatnot to the page?

Thank you fro your time and any help in advanced.

Best Regards,
Tim

答:
Many Ways to use GeoIP

There are (at least) three approaches to using GeoIP:

Install GeoIP as a PHP PECL extension (for Apache or NginX), and access it via PHP (there are other languages, this is just one of the more common. Requires root and access to the command line.

Use an analytics package that uses GeoIP (installed as above), such as the open source Piwik.

If you are using something like Wordpress, there is at least one plugin (GeoIP Detect) that does not require root.

In general, the database of geographic data is not something you would access directly, but use some kind of application to do lookups (against IP addresses).

Here are some instructions for installing GeoIP Lite database and having it available to PHP. This assumes CentOS/RHEL and Apache

Installing GeoIP Lite on CentOS/RHEL and Apache

```<code>sudo mkdir /usr/share/GeoIP
sudo cd /usr/share/GeoIP
sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoIP.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo yum update -y
sudo yum install -y geoip geoip-devel
sudo pecl channel-update pecl.php.net
sudo pecl install geoip
sudo nano /etc/php.d/geoip.ini
</code>```

Add the following to the geoip.ini file

```<code>extension=geoip.so
geoip.custom_directory = /usr/share/GeoIP/
</code>```

Restart the web server

Geographic Variables Available under GeoIP for PHP

The following variables are available via GeoIP PHP functions:

Country

Region (province, state)

City

Post code

Latitude

Longitude

DMA (US/CA)

Telephone area code (PSTN/NA only)

Time zone

Title: How to set up and using GeoIP Lite

Body:
Many Ways to use GeoIP

There are (at least) three approaches to using GeoIP:

Install GeoIP as a PHP PECL extension (for Apache or NginX), and access it via PHP (there are other languages, this is just one of the more common. Requires root and access to the command line.

Use an analytics package that uses GeoIP (installed as above), such as the open source Piwik.

If you are using something like Wordpress, there is at least one plugin (GeoIP Detect) that does not require root.

In general, the database of geographic data is not something you would access directly, but use some kind of application to do lookups (against IP addresses).

Here are some instructions for installing GeoIP Lite database and having it available to PHP. This assumes CentOS/RHEL and Apache

Installing GeoIP Lite on CentOS/RHEL and Apache

sudo mkdir /usr/share/GeoIP
sudo cd /usr/share/GeoIP
sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoIP.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo yum update -y
sudo yum install -y geoip geoip-devel
sudo pecl channel-update pecl.php.net
sudo pecl install geoip
sudo nano /etc/php.d/geoip.ini

Add the following to the geoip.ini file

extension=geoip.so
geoip.custom_directory = /usr/share/GeoIP/

Restart the web server

Geographic Variables Available under GeoIP for PHP

The following variables are available via GeoIP PHP functions:

Country

Region (province, state)

City

Post code

Latitude

Longitude

DMA (US/CA)

Telephone area code (PSTN/NA only)

Time zone


问:
Bootstrap 3 - Vertically Algn Row Content
I have a row in Bootstrap. Within this row, I have three columns. The first column has an input field. The second column has some text. The third column has another input field. You can see this layout in this Bootply, which includes this code:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-6">
<div class="row">
  <div class="col-xs-5">
    <div class="form-group">
      <label for="Minimum">Minimum</label>
      <div class="input-group">
        <input class="form-control" data-val="true" id="Minimum" name="Minimum" type="text" value="0">
      </div>
    </div>
  </div>

  <div class="col-xs-2 text-center"><p>Up To</p></div>

  <div class="col-xs-5">
    <div class="form-group">
      <label for="Maximum">Maximum</label>
      <div class="input-group">
        <input class="form-control" data-val="true" id="Maximum" name="Maximum" type="text" value="100">
      </div>
    </div>
  </div>
</div>
    </div>
  </div>
</div>
</code>```

I'm am trying to figure out how to vertically align the "Up To" text in the middle column. I want to vertically align the text against the bottom of the row. How can I do that?

答: The line height for the table rows is 34px, so setting your line height for that element to 68px would vertically align it.</p>

Body:
I have a row in Bootstrap. Within this row, I have three columns. The first column has an input field. The second column has some text. The third column has another input field. You can see this layout in this Bootply, which includes this code:

      Minimum

        <input class="form-control" data-val="true" id="Minimum" name="Minimum" type="text" value="0">

Up To

      Maximum

        <input class="form-control" data-val="true" id="Maximum" name="Maximum" type="text" value="100">

I'm am trying to figure out how to vertically align the "Up To" text in the middle column. I want to vertically align the text against the bottom of the row. How can I do that?


问:
Converting temptable column (Decimal) to Decimal but still getting "Arithmetic overflow error converting varchar to data type numeric"
I have a issue where I am selecting from a temp table but I do a convert to a float to ensure that value is correct. but when I run the query I get the following error

Arithmetic overflow error converting varchar to data type numeric

even though I am not selecting a varchar column here is the statement:

```<code>declare @AccountNumber varchar(25)
declare @FromDate datetime
declare @ToDate datetime

set @AccountNumber='ROSECALL'
set @FromDate='1980/01/01'
set @ToDate='2017/01/01'

Create table #TransF(RowId int NOT NULL identity(1,1), ValueDate datetime, MovementType varchar(50), Remarks varchar(100), Dr Decimal(19,2),
     Cr Decimal(19,2), Balance float)

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
values (@FromDate, 'Opening Balance', '',0,0);

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
Select MoveF.ValueDate, MCodeF.Description,

MoveF.Comment,
(select (
           case (MoveF.Action)
             when 'W' then MoveF.MoveAmount
               else 0
           end
         )),
(select (
           case (MoveF.Action)
             when 'D' then -MoveF.MoveAmount
               else 0
           end
         ))
From CashMovements as MoveF,
     MovementCodes as MCodeF
Where
     ( MoveF.AccountNumber=@AccountNumber) and
        MCodeF.MovementCode=MoveF.MovementCode and
      MoveF.ValueDate>=@FromDate and
      MoveF.ValueDate<=@ToDate
Order By MoveF.ValueDate

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
values (@ToDate, 'Closing Balance','',0,0);

Update #TransF set Balance=
(select (isnull((Select SUM(MoveF.MoveAmount)
From CashMovements as MoveF
Where
      MoveF.AccountNumber=@AccountNumber and
      MoveF.ValueDate<@FromDate and
      MoveF.DebitCredit='W'),0)
-
isnull((Select SUM(MoveF.MoveAmount)
From CashMovements as MoveF
Where (MoveF.AccountNumber=@AccountNumber) and
      MoveF.ValueDate<@FromDate and
      MoveF.DebitCredit='DC'),0)))
where RowId=1

SELECT 2 AS RowId INTO #RowID
while ((SELECT TOP 1 RowId FROM #RowID)<=(select count(1) from #TransF))
begin
  Update #TransF set Balance=((select Balance from #TransF where RowId=(SELECT TOP 1 RowId FROM #RowID)-1)+Dr-Cr) where RowId=(SELECT TOP 1 RowId FROM #RowID)
  UPDATE #RowID SET RowId = (SELECT TOP 1 RowId FROM #RowID) +1;
end;

Select TransF.ValueDate as 'Value Date',
       TransF.MovementType as 'Movement Type',
       TransF.Remarks as 'Remarks',
       Case when ((replace(CONVERT(Decimal(19,2) , TransF.DR, 1),',',' ') = 0.00))then 0 else (replace(CONVERT(Decimal(19,2), TransF.Dr, 1),',',' ')) end  as 'Debit',
         Case when ((replace(CONVERT(Decimal(19,2), TransF.CR, 1),',',' ') = 0.00))then 0 else (replace(CONVERT(Decimal(19,2),TransF.CR, 1),',',' ')) end  as 'Credit',

          Cast(TransF.Balance as decimal)as 'Balance'
            From #TransF as TransF
                Order By TransF.RowId
                Drop table #TransF
                DROP TABLE #RowID
</code>```

The error I am getting:

Msg 8115, Level 16, State 8, Line 67

  Arithmetic overflow error converting varchar to data type numeric.

The magic happens in the last select but its bugging on the second case statement, I know I could use IIF, but I only have SQL Server 2008

答:
You are might try converting to decimal or float after the replace() on the varchar value.

```<code> , case
  when CONVERT(decimal(16, 2),replace(TransF.DR, ',', ' ')) = 0.00
   then 0
  else  CONVERT(decimal(16, 2),replace(TransF.DR, ',', ' '))
  end as 'Debit'
 , case
  when  CONVERT(float,replace(TransF.CR, ',', ' '))= 0.00
   then 0
  else CONVERT(float,replace(TransF.CR, ',', ' '))
  end as 'Credit'
 ,
</code>```

You might need to use a larger decimal. Try decimal(19,2), decimal(28,2), or decimal(38,2)

rextester demo: http://rextester.com/HUNUF16216

```<code>declare @f float = '123456789012345.123';

select convert(decimal(19,2),@f); -- works

select convert(decimal(16,2),@f); -- overflow error
</code>```

reference:

decimal and numeric (Transact-SQL)

Body:
I have a issue where I am selecting from a temp table but I do a convert to a float to ensure that value is correct. but when I run the query I get the following error

Arithmetic overflow error converting varchar to data type numeric

even though I am not selecting a varchar column here is the statement:

declare @AccountNumber varchar(25)
declare @FromDate datetime
declare @ToDate datetime

set @AccountNumber='ROSECALL'
set @FromDate='1980/01/01'
set @ToDate='2017/01/01'

Create table #TransF(RowId int NOT NULL identity(1,1), ValueDate datetime, MovementType varchar(50), Remarks varchar(100), Dr Decimal(19,2),
     Cr Decimal(19,2), Balance float)

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
values (@FromDate, 'Opening Balance', '',0,0);

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
Select MoveF.ValueDate, MCodeF.Description,

MoveF.Comment,
(select (
           case (MoveF.Action)
             when 'W' then MoveF.MoveAmount
               else 0
           end
         )),
(select (
           case (MoveF.Action)
             when 'D' then -MoveF.MoveAmount
               else 0
           end
         ))
From CashMovements as MoveF,
     MovementCodes as MCodeF
Where
     ( MoveF.AccountNumber=@AccountNumber) and
        MCodeF.MovementCode=MoveF.MovementCode and
      MoveF.ValueDate>=@FromDate and
      MoveF.ValueDate<=@ToDate
Order By MoveF.ValueDate

insert into #TransF (ValueDate, MovementType, Remarks, Dr, Cr)
values (@ToDate, 'Closing Balance','',0,0);

Update #TransF set Balance=
(select (isnull((Select SUM(MoveF.MoveAmount)
From CashMovements as MoveF
Where
      MoveF.AccountNumber=@AccountNumber and
      MoveF.ValueDate<@FromDate and
      MoveF.DebitCredit='W'),0)
-
isnull((Select SUM(MoveF.MoveAmount)
From CashMovements as MoveF
Where (MoveF.AccountNumber=@AccountNumber) and
      MoveF.ValueDate<@FromDate and
      MoveF.DebitCredit='DC'),0)))
where RowId=1

SELECT 2 AS RowId INTO #RowID
while ((SELECT TOP 1 RowId FROM #RowID)<=(select count(1) from #TransF))
begin
  Update #TransF set Balance=((select Balance from #TransF where RowId=(SELECT TOP 1 RowId FROM #RowID)-1)+Dr-Cr) where RowId=(SELECT TOP 1 RowId FROM #RowID)
  UPDATE #RowID SET RowId = (SELECT TOP 1 RowId FROM #RowID) +1;
end;

Select TransF.ValueDate as 'Value Date',
       TransF.MovementType as 'Movement Type',
       TransF.Remarks as 'Remarks',
       Case when ((replace(CONVERT(Decimal(19,2) , TransF.DR, 1),',',' ') = 0.00))then 0 else (replace(CONVERT(Decimal(19,2), TransF.Dr, 1),',',' ')) end  as 'Debit',
         Case when ((replace(CONVERT(Decimal(19,2), TransF.CR, 1),',',' ') = 0.00))then 0 else (replace(CONVERT(Decimal(19,2),TransF.CR, 1),',',' ')) end  as 'Credit',

          Cast(TransF.Balance as decimal)as 'Balance'
            From #TransF as TransF
                Order By TransF.RowId
                Drop table #TransF
                DROP TABLE #RowID

The error I am getting:

Msg 8115, Level 16, State 8, Line 67

  Arithmetic overflow error converting varchar to data type numeric.

The magic happens in the last select but its bugging on the second case statement, I know I could use IIF, but I only have SQL Server 2008

Body:
You are might try converting to decimal or float after the replace() on the varchar value.

 , case
  when CONVERT(decimal(16, 2),replace(TransF.DR, ',', ' ')) = 0.00
   then 0
  else  CONVERT(decimal(16, 2),replace(TransF.DR, ',', ' '))
  end as 'Debit'
 , case
  when  CONVERT(float,replace(TransF.CR, ',', ' '))= 0.00
   then 0
  else CONVERT(float,replace(TransF.CR, ',', ' '))
  end as 'Credit'
 ,

You might need to use a larger decimal. Try decimal(19,2), decimal(28,2), or decimal(38,2)

rextester demo: http://rextester.com/HUNUF16216

declare @f float = '123456789012345.123';

select convert(decimal(19,2),@f); -- works

select convert(decimal(16,2),@f); -- overflow error

reference:

decimal and numeric (Transact-SQL)


问:
Give me some awesome Web2py Tip & Tricks which makes you more productive
I have been working with web2py following its official web2py book and got to learn too many things. But a book never teaches a productive workflow. I would like to know what workflow you people use to increase you productivity and understanding of the framework as a whole.

Ex:
 I often use Web2py interactive shell to play with database objects and understand how they work.

答:
I use Komodo Edit for development and Google App Engine for hosting.

To better understand web2py have a look at the files in gluon/ - for example tools.py is fairly straightforward.

ContentLicense: CC BY-SA 2.5


问:
I want to display the output with full string
```<code>Connect-VIServer XXXX

[System.Collections.ArrayList]$Result=@()
$vms = Get-VM | Where-Object {$_.Name -like 'XXX*'}
try{
 ForEach ($v in $vms)
  {
   foreach ($d in $v.ExtensionData.Guest.Disk)
    {
    $usedSpace = $d.Capacity - $d.FreeSpace
    $percentUsed =  [math]::Round(($usedSpace / $d.Capacity) * 100)

    $List = New-Object -TypeName PSObject -Property @{
        SERVER_NAME = $v.Name | Out-String
            "Total_Capacity(GB)" = [math]::round([int]($d.Capacity/1GB), 1)
            "Free_Space(GB)" = [math]::round([int]($d.FreeSpace/1GB), 1)
            PercentFull = "$percentUsed%"
                        }
                #Write-Host "$ErrorList"
            $Result+=$List
    }
  }
}
catch [Exception]
{
write-host "OD-VM-Monitor: $v : FATAL SCRIPT ERROR" $_.Exception.Message
}
</code>```

I have executed the above script. but while trying to display the result, it is showing with dot like below . I tried the below two.

```<code>$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Out-String -Width 4096 | ft -auto
$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Format-Table -AutoSize

SERVER_NAME     Total_Capacity(GB) Free_Space(GB) PercentFull
-----------     ------------------ -------------- -----------
XXXXXXX...                200            113 43%
XXXXXXX...                150             50 67%
XXXXXXX...                150             31 79%
XXXXXXX...                100             32 68%
XXXXXXX...                500             87 83%
XXXXXXX...                100             43 57%
XXXXXXX...                100             36 64%
XXXXXXX...                150             37 75%
</code>```

Any idea how to get rid out of the dots.
Thanks in advance.

答: Format-Table can take a hash table specifying column widths.</p>

Body:
Connect-VIServer XXXX

[System.Collections.ArrayList]$Result=@()
$vms = Get-VM | Where-Object {$_.Name -like 'XXX*'}
try{
 ForEach ($v in $vms)
  {
   foreach ($d in $v.ExtensionData.Guest.Disk)
    {
    $usedSpace = $d.Capacity - $d.FreeSpace
    $percentUsed =  [math]::Round(($usedSpace / $d.Capacity) * 100)

    $List = New-Object -TypeName PSObject -Property @{
        SERVER_NAME = $v.Name | Out-String
            "Total_Capacity(GB)" = [math]::round([int]($d.Capacity/1GB), 1)
            "Free_Space(GB)" = [math]::round([int]($d.FreeSpace/1GB), 1)
            PercentFull = "$percentUsed%"
                        }
                #Write-Host "$ErrorList"
            $Result+=$List
    }
  }
}
catch [Exception]
{
write-host "OD-VM-Monitor: $v : FATAL SCRIPT ERROR" $_.Exception.Message
}

I have executed the above script. but while trying to display the result, it is showing with dot like below . I tried the below two.

$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Out-String -Width 4096 | ft -auto
$Result | Select-Object SERVER_NAME, 'Total_Capacity(GB)', 'Free_Space(GB)', PercentFull | Format-Table -AutoSize

SERVER_NAME     Total_Capacity(GB) Free_Space(GB) PercentFull
-----------     ------------------ -------------- -----------
XXXXXXX...                200            113 43%
XXXXXXX...                150             50 67%
XXXXXXX...                150             31 79%
XXXXXXX...                100             32 68%
XXXXXXX...                500             87 83%
XXXXXXX...                100             43 57%
XXXXXXX...                100             36 64%
XXXXXXX...                150             37 75%

Any idea how to get rid out of the dots.
Thanks in advance.


问:
isConsecutiveStraightFlush consecutive array check
The assignment I have is to return true if a deck of cards is a consecutive straight flush, which means an entire deck that consists of a sequence of  cards of the same suit with consecutive ranks. Since these are cards, this would mean that a card with rank 14 (A) would go BEFORE a card with rank 2.

How would I go about establishing that the order of cards goes 12,13,14,2,3 for example?

This is the Card class

```<code>public class Card {
    private String suit;
    private int rank;

    public Card(String suit, int rank) {
        super();
        this.suit = suit;
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "[" + rank  + "," + suit + "]";
    }

    @Override
    public boolean equals(Object c2) {
        if (!(c2 instanceof Card)) {
            throw new RuntimeException("Illegal argument to Card.equals()");
        }
        Card card2 = (Card) c2;
        return ((this.getSuit().equals(card2.getSuit())) &&
                (this.getRank() == card2.getRank()));
    }

    public String getSuit() {
        return suit;
    }

    public int getRank() {
        return rank;
    }

    public boolean sameSuitAs(Card card2) {
        return (this.getSuit().equals(card2.getSuit()));
    }

    public boolean sameRankAs(Card card2) {
        return (this.getRank() == card2.getRank());
    }

    public boolean isAnA() {
        if (getRank() != 14) {
            return false;
        }
        return true;
    }

    public boolean isPair(Card c) {
        int rank = getRank();
        if (rank == c.getRank()) {
            return true;
        }
        return false;
    }

    public boolean isTrio(Card c1, Card c2) {
        if (c1.isPair(c2) == true ) {
            if (isPair(c1) == true) {
                return true;
            }
        }
        return false;
    }

    public boolean isFourTuple(Card c1, Card c2, Card c3) {
        if (c1.isPair(c2) == true ) {
            if (c2.isPair(c3) == true) {
                if (isPair(c1) == true) {
                    return true;
                }
            }
        }
        return false;
    }

    public static long countCardsBySuit(Card[] deck, Card target) {
        long result = 0;
        String suit = target.getSuit();
        for (int i = 0; i < deck.length; i++) {
            if (suit == deck[i].getSuit()) {
                result ++;
            }
        }
        return result;
    }

     public static boolean cardExists(Card[] deck, Card target) {
         String targetsuit = target.getSuit();
         int targetrank = target.getRank();
         for (int i = 0; i < deck.length; i++) {
             if (targetsuit == deck[i].getSuit() && targetrank == deck[i].getRank()) {
                 return true;
             }
         }
         return false;
     }

     public static boolean consecutivePairExists(Card[] deck) {
         int pairs = 0;
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             for (int j = 0 + i + 1; i < deck.length - 3; j ++) {
                 if (targetrank == deck[j].getRank()) {
                     pairs++;
                     if (pairs > 1) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean pairExists(Card[] deck) {
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             if (i == 0) {
                 for (int k = 1 ; k <deck.length; k++) {
                     if (targetrank == deck[k].getRank()) {
                         return true;
                     }
                 }
             }
             else {
                 for (int j = i + 1 ; j <deck.length; j++) {
                     if (targetrank == deck[j].getRank()) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean isConsecutiveStraightFlush(Card[] deck) {
         if (deck.length > 1) {
             long result = 0;
             String suit = deck[0].getSuit();
                for (int i = 1; i < deck.length; i++) {
                    if (suit == deck[i].getSuit()) {
                        result ++;
                    }
                }
                if (result == deck.length - 1) {
                    int count = 0;
                    int rank = deck[0].getRank();
                    for (int j = 1; j < deck.length; j++) {
                        if (rank - deck[j].getRank() == -1) {
                            count++;
                            rank = deck[j].getRank();
                            if (count == deck.length - 1) {
                                return true;
                            }
                        }
                    }
                }
         }
         return false;
     }
}
</code>```

and this is the JUnit Test Case CardTest

```<code>import static org.junit.Assert.*;
import org.junit.Test;

public class CardTest {

    Card diamond1 = new Card("Diamond", 1);
    Card diamond2 = new Card("Diamond", 2);
    Card spade1 = new Card("Spade", 1);
    Card spade2 = new Card("Spade", 2);
    Card spadeA = new Card("Spade", 14);

        Card card2C = new Card("Club", 2);
        Card card2S = new Card("Spade", 2);
        Card card2D = new Card("Diamond", 2);
        Card card2H = new Card("Heart", 2);

        Card card3C = new Card("Club", 3);
        Card card4C = new Card("Club", 4);
        Card card5C = new Card("Club", 5);
        Card card6C = new Card("Club", 6);
        Card card7C = new Card("Club", 7);
        Card card8C = new Card("Club", 8);
        Card card9C = new Card("Club", 9);
        Card card10C = new Card("Club", 10);
        Card cardJC = new Card("Club", 11);
        Card cardQC = new Card("Club", 12);
        Card cardKC = new Card("Club", 13);
        Card cardAC = new Card("Club", 14);

        Card[] deck1 = { card2C, card2S, card2D, card3C };

        Card[] deck2 = { card2C, card3C, card2D};

        Card[] deck3 = { card2C, card3C, spadeA};

        Card[] straightFlush1 = { card2C, card3C, card4C, card5C, card6C};
        Card[] straightFlush2 = { cardQC, cardKC, cardAC, card2C, card3C};

        Card[] emptyDeck = {};

    @Test
    public void testToString() {
        assertTrue("Card.toString: generates incorrect String", diamond1.toString().equals("[1,Diamond]"));
        assertTrue("Card.toString: generates incorrect String", spade2.toString().equals("[2,Spade]"));
    }

    @Test
    public void testEquals() {
        assertTrue("Card.equals: Yields false incorrectly", diamond1.equals(diamond1));
        assertFalse("Card.equals: Yields true incorrectly", diamond1.equals(diamond2));
    }

    @Test
    public void testSameSuitRank() {
        assertTrue("Card.sameRankAs: Yields false incorrectly", diamond1.sameRankAs(spade1));
        assertTrue("Card.sameSuitAs: Yields false incorrectly", diamond1.sameSuitAs(diamond2));
        assertFalse("Card.sameRankAs: Yields true incorrectly", spade1.sameRankAs(spade2));
        assertFalse("Card.sameSuitAs: Yields true incorrectly", spade2.sameSuitAs(diamond1));
    }

    @Test
    public void testIsConsecutiveStraightFlush() {
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(emptyDeck));
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(deck1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush2));
    }
}
</code>```

Any help would be appreciated

答:
I'm not going to write any code examples towards the assignment for you, as the point is for you to write the code yourself, but I do want to give you some advice and pointers to help you along your way.

Work smarter, not harder

For a problem like this, it's generally much easier to tell if the condition is false than to tell if it is true.  Here is your method:

```<code>public static boolean isConsecutiveStraightFlush(Card[] deck) {
    if (deck.length > 1) {
        long result = 0;
        String suit = deck[0].getSuit();
           for (int i = 1; i < deck.length; i++) {
               if (suit == deck[i].getSuit()) {
                   result ++;
               }
           }
           if (result == deck.length - 1) {
               int count = 0;
               int rank = deck[0].getRank();
               for (int j = 1; j < deck.length; j++) {
                   if (rank - deck[j].getRank() == -1) {
                       count++;
                       rank = deck[j].getRank();
                       if (count == deck.length - 1) {
                           return true;
                       }
                   }
               }
           }
    }
    return false;
}
</code>```

Your spending quite a lot of effort to keep track of everything so you can return true once every single check passes.  If you flipped it round so that you assume it is a straight flush and return false as soon as one check fails, this method become a lot simpler.

String equality

It is a very rare case you want to use the == operator to test string equality in Java.  Use string1.equals(string2) instead.  For more information on this, see this answer

Experiment with operators

You're approach to use the difference in rank to test if the cards are in sequential order is fine and worked great... Until you found the requirement that the sequence is allowed to wrap back around to the start.  The modulo operator (%) can be used to constrain numbers to a given range.  For example, the following snippet will print keep cycling through the values, even though i will get much larger than the length of the array:

```<code>String[] values = { "one", "two", "three" };
for (int i = 0; i <= 10; i++) {
    System.out.println(values[i % 3]);
}
</code>```

There is a solution (not the only solution) to the wrapping rank requirement that can make use of this (hint: rank is sequential if "current rank" + 1 == "next rank").

Be careful not to turn assumptions into requirements

Does the assignment specify that the sequence Q, K, A, 2, 3 is a valid straight flush, or are you using your own understanding of poker hands?

According to Wikipedia (reliable, I know), "Q♣ K♣ A♣ 2♣ 3♣ is an ace-high flush, not a straight flush", so you might be making the assignment harder than it needs to be.

Hopefully I have given you something helpful in here.  Good luck with the assignment.

Body:
The assignment I have is to return true if a deck of cards is a consecutive straight flush, which means an entire deck that consists of a sequence of  cards of the same suit with consecutive ranks. Since these are cards, this would mean that a card with rank 14 (A) would go BEFORE a card with rank 2.

How would I go about establishing that the order of cards goes 12,13,14,2,3 for example?

This is the Card class

public class Card {
    private String suit;
    private int rank;

    public Card(String suit, int rank) {
        super();
        this.suit = suit;
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "[" + rank  + "," + suit + "]";
    }

    @Override
    public boolean equals(Object c2) {
        if (!(c2 instanceof Card)) {
            throw new RuntimeException("Illegal argument to Card.equals()");
        }
        Card card2 = (Card) c2;
        return ((this.getSuit().equals(card2.getSuit())) &&
                (this.getRank() == card2.getRank()));
    }

    public String getSuit() {
        return suit;
    }

    public int getRank() {
        return rank;
    }

    public boolean sameSuitAs(Card card2) {
        return (this.getSuit().equals(card2.getSuit()));
    }

    public boolean sameRankAs(Card card2) {
        return (this.getRank() == card2.getRank());
    }

    public boolean isAnA() {
        if (getRank() != 14) {
            return false;
        }
        return true;
    }

    public boolean isPair(Card c) {
        int rank = getRank();
        if (rank == c.getRank()) {
            return true;
        }
        return false;
    }

    public boolean isTrio(Card c1, Card c2) {
        if (c1.isPair(c2) == true ) {
            if (isPair(c1) == true) {
                return true;
            }
        }
        return false;
    }

    public boolean isFourTuple(Card c1, Card c2, Card c3) {
        if (c1.isPair(c2) == true ) {
            if (c2.isPair(c3) == true) {
                if (isPair(c1) == true) {
                    return true;
                }
            }
        }
        return false;
    }

    public static long countCardsBySuit(Card[] deck, Card target) {
        long result = 0;
        String suit = target.getSuit();
        for (int i = 0; i < deck.length; i++) {
            if (suit == deck[i].getSuit()) {
                result ++;
            }
        }
        return result;
    }

     public static boolean cardExists(Card[] deck, Card target) {
         String targetsuit = target.getSuit();
         int targetrank = target.getRank();
         for (int i = 0; i < deck.length; i++) {
             if (targetsuit == deck[i].getSuit() && targetrank == deck[i].getRank()) {
                 return true;
             }
         }
         return false;
     }

     public static boolean consecutivePairExists(Card[] deck) {
         int pairs = 0;
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             for (int j = 0 + i + 1; i < deck.length - 3; j ++) {
                 if (targetrank == deck[j].getRank()) {
                     pairs++;
                     if (pairs > 1) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean pairExists(Card[] deck) {
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             if (i == 0) {
                 for (int k = 1 ; k <deck.length; k++) {
                     if (targetrank == deck[k].getRank()) {
                         return true;
                     }
                 }
             }
             else {
                 for (int j = i + 1 ; j <deck.length; j++) {
                     if (targetrank == deck[j].getRank()) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean isConsecutiveStraightFlush(Card[] deck) {
         if (deck.length > 1) {
             long result = 0;
             String suit = deck[0].getSuit();
                for (int i = 1; i < deck.length; i++) {
                    if (suit == deck[i].getSuit()) {
                        result ++;
                    }
                }
                if (result == deck.length - 1) {
                    int count = 0;
                    int rank = deck[0].getRank();
                    for (int j = 1; j < deck.length; j++) {
                        if (rank - deck[j].getRank() == -1) {
                            count++;
                            rank = deck[j].getRank();
                            if (count == deck.length - 1) {
                                return true;
                            }
                        }
                    }
                }
         }
         return false;
     }
}

and this is the JUnit Test Case CardTest

import static org.junit.Assert.*;
import org.junit.Test;

public class CardTest {

    Card diamond1 = new Card("Diamond", 1);
    Card diamond2 = new Card("Diamond", 2);
    Card spade1 = new Card("Spade", 1);
    Card spade2 = new Card("Spade", 2);
    Card spadeA = new Card("Spade", 14);

        Card card2C = new Card("Club", 2);
        Card card2S = new Card("Spade", 2);
        Card card2D = new Card("Diamond", 2);
        Card card2H = new Card("Heart", 2);

        Card card3C = new Card("Club", 3);
        Card card4C = new Card("Club", 4);
        Card card5C = new Card("Club", 5);
        Card card6C = new Card("Club", 6);
        Card card7C = new Card("Club", 7);
        Card card8C = new Card("Club", 8);
        Card card9C = new Card("Club", 9);
        Card card10C = new Card("Club", 10);
        Card cardJC = new Card("Club", 11);
        Card cardQC = new Card("Club", 12);
        Card cardKC = new Card("Club", 13);
        Card cardAC = new Card("Club", 14);

        Card[] deck1 = { card2C, card2S, card2D, card3C };

        Card[] deck2 = { card2C, card3C, card2D};

        Card[] deck3 = { card2C, card3C, spadeA};

        Card[] straightFlush1 = { card2C, card3C, card4C, card5C, card6C};
        Card[] straightFlush2 = { cardQC, cardKC, cardAC, card2C, card3C};

        Card[] emptyDeck = {};

    @Test
    public void testToString() {
        assertTrue("Card.toString: generates incorrect String", diamond1.toString().equals("[1,Diamond]"));
        assertTrue("Card.toString: generates incorrect String", spade2.toString().equals("[2,Spade]"));
    }

    @Test
    public void testEquals() {
        assertTrue("Card.equals: Yields false incorrectly", diamond1.equals(diamond1));
        assertFalse("Card.equals: Yields true incorrectly", diamond1.equals(diamond2));
    }

    @Test
    public void testSameSuitRank() {
        assertTrue("Card.sameRankAs: Yields false incorrectly", diamond1.sameRankAs(spade1));
        assertTrue("Card.sameSuitAs: Yields false incorrectly", diamond1.sameSuitAs(diamond2));
        assertFalse("Card.sameRankAs: Yields true incorrectly", spade1.sameRankAs(spade2));
        assertFalse("Card.sameSuitAs: Yields true incorrectly", spade2.sameSuitAs(diamond1));
    }

    @Test
    public void testIsConsecutiveStraightFlush() {
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(emptyDeck));
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(deck1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush2));
    }
}

Any help would be appreciated

Body:
I'm not going to write any code examples towards the assignment for you, as the point is for you to write the code yourself, but I do want to give you some advice and pointers to help you along your way.

Work smarter, not harder

For a problem like this, it's generally much easier to tell if the condition is false than to tell if it is true.  Here is your method:

public static boolean isConsecutiveStraightFlush(Card[] deck) {
    if (deck.length > 1) {
        long result = 0;
        String suit = deck[0].getSuit();
           for (int i = 1; i < deck.length; i++) {
               if (suit == deck[i].getSuit()) {
                   result ++;
               }
           }
           if (result == deck.length - 1) {
               int count = 0;
               int rank = deck[0].getRank();
               for (int j = 1; j < deck.length; j++) {
                   if (rank - deck[j].getRank() == -1) {
                       count++;
                       rank = deck[j].getRank();
                       if (count == deck.length - 1) {
                           return true;
                       }
                   }
               }
           }
    }
    return false;
}

Your spending quite a lot of effort to keep track of everything so you can return true once every single check passes.  If you flipped it round so that you assume it is a straight flush and return false as soon as one check fails, this method become a lot simpler.

String equality

It is a very rare case you want to use the == operator to test string equality in Java.  Use string1.equals(string2) instead.  For more information on this, see this answer

Experiment with operators

You're approach to use the difference in rank to test if the cards are in sequential order is fine and worked great... Until you found the requirement that the sequence is allowed to wrap back around to the start.  The modulo operator (%) can be used to constrain numbers to a given range.  For example, the following snippet will print keep cycling through the values, even though i will get much larger than the length of the array:

String[] values = { "one", "two", "three" };
for (int i = 0; i <= 10; i++) {
    System.out.println(values[i % 3]);
}

There is a solution (not the only solution) to the wrapping rank requirement that can make use of this (hint: rank is sequential if "current rank" + 1 == "next rank").

Be careful not to turn assumptions into requirements

Does the assignment specify that the sequence Q, K, A, 2, 3 is a valid straight flush, or are you using your own understanding of poker hands?

According to Wikipedia (reliable, I know), "Q♣ K♣ A♣ 2♣ 3♣ is an ace-high flush, not a straight flush", so you might be making the assignment harder than it needs to be.

Hopefully I have given you something helpful in here.  Good luck with the assignment.


问:
Check if android device rotation possible
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

```<code>if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}
</code>```

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

答: Maybe try to simply lock the application screen in one position so you will skip the checkout step if you can rotate :)</p>

Body:
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo


问:
Garbage collector tries to collect shared memory object
I've got two Python scripts that both should do essentially the same thing: grab a large object in memory, then fork a bunch of children. The first script uses bare os.fork:

import time
import signal
import os
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        pid = os.fork()
        if pid == 0:
            child(i)
        else:
            print pid
            workers.append(pid)

    while True:
        wpid, status = os.waitpid(-1, os.WNOHANG)
        if wpid:
            print wpid, status
        time.sleep(1)
```

<p>The second script uses <code>multiprocessing</code> module. I'm running both on Linux (Ubuntu 14.04), so it should use <code>os.fork</code> under the hood too, as documentation states:</p>

<pre class="lang-python prettyprint-override"><code>import multiprocessing
import time
import signal
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        p = multiprocessing.Process(target=child, args=(i,))
        p.start()
        print p.pid
        workers.append(p)

    while True:
        for worker in workers:
            if not worker.is_alive():
                worker.join()
        time.sleep(1)
</code>```

The difference between those two scripts is the following: when I kill a child (sending a SIGTERM), bare-fork script tries to garbagecollect the shared dictionary, despite the fact that it is still referenced by parent process and isn't actually copied into child's memory (because of copy-on-write)

```<code>kill <pid>

Traceback (most recent call last):
  File "test_mp_fork.py", line 33, in <module>
    child(i)
  File "test_mp_fork.py", line 19, in child
    time.sleep(1)
  File "test_mp_fork.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
__main__.GracefulExit: 3 out
gc: collecting generation 2...
gc: objects in each generation: 521 3156 0
gc: done, 0.0024s elapsed.
</code>```

(perf record -e page-faults -g -p <pid> output:)

```<code>+  99,64%  python  python2.7           [.] PyInt_ClearFreeList
+   0,15%  python  libc-2.19.so        [.] vfprintf
+   0,09%  python  python2.7           [.] 0x0000000000144e90
+   0,06%  python  libc-2.19.so        [.] strlen
+   0,05%  python  python2.7           [.] PyArg_ParseTupleAndKeywords
+   0,00%  python  python2.7           [.] PyEval_EvalFrameEx
+   0,00%  python  python2.7           [.] Py_AddPendingCall
+   0,00%  python  libpthread-2.19.so  [.] sem_trywait
+   0,00%  python  libpthread-2.19.so  [.] __errno_location
</code>```

While multiprocessing-based script does no such thing:

```<code>kill <pid>

Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "test_mp.py", line 19, in child
    time.sleep(1)
  File "test_mp.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
GracefulExit: 2 out
</code>```

(perf record -e page-faults -g -p <pid> output:)

```<code>+  62,96%  python  python2.7           [.] 0x0000000000047a5b
+  32,28%  python  python2.7           [.] PyString_Format
+   2,65%  python  python2.7           [.] Py_BuildValue
+   1,06%  python  python2.7           [.] PyEval_GetFrame
+   0,53%  python  python2.7           [.] Py_AddPendingCall
+   0,53%  python  libpthread-2.19.so  [.] sem_trywait
</code>```

I can also force the same behavior on multiprocessing-based script by explicitly calling gc.collect() before raising GracefulExit. Curiously enough, the reverse is not true: calling gc.disable(); gc.set_threshold(0) in bare-fork script doesn't help to get rid of PyInt_ClearFreeList calls.

To the actual questions:

Why is this happening? I sort of understand why python would like to free all the allocated memory on process exit, ignoring the fact that the child process doesn't physically own it, but how come multiprocessing module doesn't do the same?

I'd like to achieve second-script-like behavior (i.e.: not trying to free the memory which has been allocated by a parent process) with bare-fork solution (mainly because I use a third-party process manager library which doesn't use multiprocessing); how could I possibly do that?

答:
Couple things

In python, multiple python processes means multiple interpreters with their own GIL, GC et al

The d dictionary is not passed in as an argument to the process, it is a globally shared variable.

The reason it gets collected is because each process thinks its the only one holding a reference to it which, strictly speaking, is true as it's a single globally shared object reference to the dictionary.

When Python GC checks it, it checks the ref counter for that object. Since there is only the one shared reference, removing that would mean ref count == 0, so it gets collected.

To resolve the issue, d should be passed into each forked process, making each process hold its own reference to it.

Body:
I've got two Python scripts that both should do essentially the same thing: grab a large object in memory, then fork a bunch of children. The first script uses bare os.fork:

import time
import signal
import os
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        pid = os.fork()
        if pid == 0:
            child(i)
        else:
            print pid
            workers.append(pid)

    while True:
        wpid, status = os.waitpid(-1, os.WNOHANG)
        if wpid:
            print wpid, status
        time.sleep(1)

The second script uses multiprocessing module. I'm running both on Linux (Ubuntu 14.04), so it should use os.fork under the hood too, as documentation states:

import multiprocessing
import time
import signal
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        p = multiprocessing.Process(target=child, args=(i,))
        p.start()
        print p.pid
        workers.append(p)

    while True:
        for worker in workers:
            if not worker.is_alive():
                worker.join()
        time.sleep(1)

The difference between those two scripts is the following: when I kill a child (sending a SIGTERM), bare-fork script tries to garbagecollect the shared dictionary, despite the fact that it is still referenced by parent process and isn't actually copied into child's memory (because of copy-on-write)

kill <pid>

Traceback (most recent call last):
  File "test_mp_fork.py", line 33, in <module>
    child(i)
  File "test_mp_fork.py", line 19, in child
    time.sleep(1)
  File "test_mp_fork.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
__main__.GracefulExit: 3 out
gc: collecting generation 2...
gc: objects in each generation: 521 3156 0
gc: done, 0.0024s elapsed.

(perf record -e page-faults -g -p <pid> output:)

+  99,64%  python  python2.7           [.] PyInt_ClearFreeList
+   0,15%  python  libc-2.19.so        [.] vfprintf
+   0,09%  python  python2.7           [.] 0x0000000000144e90
+   0,06%  python  libc-2.19.so        [.] strlen
+   0,05%  python  python2.7           [.] PyArg_ParseTupleAndKeywords
+   0,00%  python  python2.7           [.] PyEval_EvalFrameEx
+   0,00%  python  python2.7           [.] Py_AddPendingCall
+   0,00%  python  libpthread-2.19.so  [.] sem_trywait
+   0,00%  python  libpthread-2.19.so  [.] __errno_location

While multiprocessing-based script does no such thing:

kill <pid>

Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "test_mp.py", line 19, in child
    time.sleep(1)
  File "test_mp.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
GracefulExit: 2 out

(perf record -e page-faults -g -p <pid> output:)

+  62,96%  python  python2.7           [.] 0x0000000000047a5b
+  32,28%  python  python2.7           [.] PyString_Format
+   2,65%  python  python2.7           [.] Py_BuildValue
+   1,06%  python  python2.7           [.] PyEval_GetFrame
+   0,53%  python  python2.7           [.] Py_AddPendingCall
+   0,53%  python  libpthread-2.19.so  [.] sem_trywait

I can also force the same behavior on multiprocessing-based script by explicitly calling gc.collect() before raising GracefulExit. Curiously enough, the reverse is not true: calling gc.disable(); gc.set_threshold(0) in bare-fork script doesn't help to get rid of PyInt_ClearFreeList calls.

To the actual questions:

Why is this happening? I sort of understand why python would like to free all the allocated memory on process exit, ignoring the fact that the child process doesn't physically own it, but how come multiprocessing module doesn't do the same?

I'd like to achieve second-script-like behavior (i.e.: not trying to free the memory which has been allocated by a parent process) with bare-fork solution (mainly because I use a third-party process manager library which doesn't use multiprocessing); how could I possibly do that?


问:
Konvajs How to change image src dynamically
I created a Konva image like this

```<code>var imageObj = new Image();
imageObj.onload = function() {
  var image = new Konva.Image({
    x: 200,
    y: 50,
    image: imageObj,
    width: 100,
    height: 100
  });
};
imageObj.src = '/path/to/image.jpg'
</code>```

Now I need to know how to update the image src/url of created Konva.Image Object.

You can find the docs here: https://konvajs.github.io/api/Konva.Image.html

答:
You can just replace image property of Konva.Image. Or update src of native image:

```<code>var card = new Konva.Image({
    x: 200,
    y: 50,
    width: 100,
    height: 100
});

var imageObj = new Image();
imageObj.onload = function() {
  card.image(imageObj);
};
imageObj.src = '/path/to/image.jpg';

// later

var imageObj2 = new Image();
imageObj2.onload = function() {
  card.image(imageObj2);
};
imageObj2.src = '/path/to/image.jpg';
</code>```

Or

```<code>var imageObj = new Image();
var card = new Konva.Image({
    x: 200,
    y: 50,
    width: 100,
    height: 100,
    image: imageObj
});

imageObj.onload = function() {
  card.getLayer().draw();
};
imageObj.src = '/path/to/image.jpg';

// later
imageObj2.src = '/path/to/image.jpg'; // it should trigger onload
</code>```

Body:
I created a Konva image like this

var imageObj = new Image();
imageObj.onload = function() {
  var image = new Konva.Image({
    x: 200,
    y: 50,
    image: imageObj,
    width: 100,
    height: 100
  });
};
imageObj.src = '/path/to/image.jpg'

Now I need to know how to update the image src/url of created Konva.Image Object.

You can find the docs here: https://konvajs.github.io/api/Konva.Image.html

Body:
You can just replace image property of Konva.Image. Or update src of native image:

var card = new Konva.Image({
    x: 200,
    y: 50,
    width: 100,
    height: 100
});

var imageObj = new Image();
imageObj.onload = function() {
  card.image(imageObj);
};
imageObj.src = '/path/to/image.jpg';

// later

var imageObj2 = new Image();
imageObj2.onload = function() {
  card.image(imageObj2);
};
imageObj2.src = '/path/to/image.jpg';

Or

var imageObj = new Image();
var card = new Konva.Image({
    x: 200,
    y: 50,
    width: 100,
    height: 100,
    image: imageObj
});

imageObj.onload = function() {
  card.getLayer().draw();
};
imageObj.src = '/path/to/image.jpg';

// later
imageObj2.src = '/path/to/image.jpg'; // it should trigger onload


问:
Mapping resources to classes in C#/WPF
I have a bunch of Shape-classes (classic) like Rectangle and Circle in my first module.

In my second module, I have a GUI, made with WPF. I want to show a ListBox of all Shape-classes. The ListBox shall contain the localizable name of the shape, which is saved as a resource string, and an icon, saved as a resource image.

I want my whole code to be as modular as possible, e.g. if I add a new Shape-class, I want to change as few classes as possible.

My first approach would be to make a helper class in my GUI-module, which for each shape holds the Shape's Type, its name as string, and its icon as a Bitmap (or similar). I would then initialize the list at one place, e.g.

```<code>var shapeList = new List<ShapeHelperClass>
{
  new ShapeHelperClass(typeof(Rectangle), Resources.StringRectangle, Resources.IconRectangle),
  new ShapeHelperClass(typeof(Circle), Resources.StringCircle, Resources.IconCircle),
};
</code>```

and bind this list to the ListBox. Now, if I rename my classes or my resources, nothing will break, and localization should work properly. But, of course, if adding a new Shape-class in the first module, I also need to update this list.

Another approach would be to use reflection to find all my Shape classes, and build the list out of that. However, I would still need some Dictionaries or something similar to map the classes to the Resources. I could find the resources if they follow a pattern, like "Icon" + "Classname". However, if no icon is found, this is only noticed at runtime.

So, my questions are:

Is my first approach a good one, our could it be improved?

How can I make sure that a programmer who adds a new Shape also adds the new Resources and extends the mapping-list? Maybe by Unit-testing?

答:
1.Is my first approach a good one, our could it be improved?

You could create a method in your first module that returns all shapes and call this one in your client application, e.g.:

```<code>var shapes = GetShapes();
List<ShapeHelperClass> helpers = new List<ShapeHelperClass>();
foreach(var shape in shapes)
    helpers.Add(...);
</code>```

Then you should never have to modify the client application as a shape is added or removed in the first module.

2.How can I make sure that a programmer who adds a new Shape also adds the new Resources and extends the mapping-list? Maybe by Unit-testing?

Maybe you could write a unit test that uses reflection to find all shape types and asserts that they are included in the list of shapes that is returned from the first module. And likewise for the resources. I can't think of any better automatic way of ensuring this really.

Title: Mapping resources to classes in C#/WPF

Body:
I have a bunch of Shape-classes (classic) like Rectangle and Circle in my first module.

In my second module, I have a GUI, made with WPF. I want to show a ListBox of all Shape-classes. The ListBox shall contain the localizable name of the shape, which is saved as a resource string, and an icon, saved as a resource image.

I want my whole code to be as modular as possible, e.g. if I add a new Shape-class, I want to change as few classes as possible.

My first approach would be to make a helper class in my GUI-module, which for each shape holds the Shape's Type, its name as string, and its icon as a Bitmap (or similar). I would then initialize the list at one place, e.g.

var shapeList = new List<ShapeHelperClass>
{
  new ShapeHelperClass(typeof(Rectangle), Resources.StringRectangle, Resources.IconRectangle),
  new ShapeHelperClass(typeof(Circle), Resources.StringCircle, Resources.IconCircle),
};

and bind this list to the ListBox. Now, if I rename my classes or my resources, nothing will break, and localization should work properly. But, of course, if adding a new Shape-class in the first module, I also need to update this list.

Another approach would be to use reflection to find all my Shape classes, and build the list out of that. However, I would still need some Dictionaries or something similar to map the classes to the Resources. I could find the resources if they follow a pattern, like "Icon" + "Classname". However, if no icon is found, this is only noticed at runtime.

So, my questions are:

Is my first approach a good one, our could it be improved?

How can I make sure that a programmer who adds a new Shape also adds the new Resources and extends the mapping-list? Maybe by Unit-testing?

Body:
1.Is my first approach a good one, our could it be improved?

You could create a method in your first module that returns all shapes and call this one in your client application, e.g.:

var shapes = GetShapes();
List<ShapeHelperClass> helpers = new List<ShapeHelperClass>();
foreach(var shape in shapes)
    helpers.Add(...);

Then you should never have to modify the client application as a shape is added or removed in the first module.

2.How can I make sure that a programmer who adds a new Shape also adds the new Resources and extends the mapping-list? Maybe by Unit-testing?

Maybe you could write a unit test that uses reflection to find all shape types and asserts that they are included in the list of shapes that is returned from the first module. And likewise for the resources. I can't think of any better automatic way of ensuring this really.


问:
C: what is wrong with this char pointer assignment?
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

```<code>#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}
</code>```

Thanks in advance!

答:
Your problem is that within the loop, you write *option_string++.  This means that once the loop is done, you're going to be pointing past the end of the string:

```<code>option_string at start
   |
   V
+----+----+----+----+----+
|    |    |    |    |    |
|    |    |    |    |    |
+----+----+----+----+----+
                             ^
                             |
                     option_string at end
</code>```

Note that this reveals a second problem with your code: strings in C are null-terminated, but this string will eventually contain "aaaaa" and then… who knows?  Garbage, most likely, but you can't tell.  You need a six-length string.  Fixing the first problem means using simple indexing instead: option_string[j] = 'a'.  If you really want the *option_string++ method, you'll have to save and restore option_string (char * real_option_string = option_string; ... option_string = real_option_string;), but I wouldn't recommend it.  Fixing both of these bugs, and a couple of style things, gives you:

```<code>#include <stdlib.h>
#include <stdio.h>

int main (void)
{
    char * option_string = calloc(6, sizeof(char));

    int j;
    for ( j = 0; j < 5; j++)
    {
        option_string[j] = 'a';
    }

    printf("print options_string: %s\n", option_string);
    free(option_string);
    return 0;
}
</code>```

The other thing I changed was your malloc usage.  I feel like calloc is a better stylistic choice here; calloc(count, size) allocates count objects of size size, and zeros them.  It's like malloc(count*size) plus a memset, but feels cleaner to me.  You also shouldn't have a cast on malloc/calloc/etc., generally speaking (it can obscure useful warnings), and you need to allocate six slots, like I said (so you can have the null-terminator, which is the zero-valued character, so we don't need to set it explicitly).  Combine that with the option_string[j] indexing mode, include the missing stdlib.h for calloc (you should have had it for malloc, too), and we're good to go!

Body:
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}

Thanks in advance!

Body:
Your problem is that within the loop, you write *option_string++.  This means that once the loop is done, you're going to be pointing past the end of the string:

option_string at start
   |
   V
+----+----+----+----+----+
|    |    |    |    |    |
|    |    |    |    |    |
+----+----+----+----+----+
                             ^
                             |
                     option_string at end

Note that this reveals a second problem with your code: strings in C are null-terminated, but this string will eventually contain "aaaaa" and then… who knows?  Garbage, most likely, but you can't tell.  You need a six-length string.  Fixing the first problem means using simple indexing instead: option_string[j] = 'a'.  If you really want the *option_string++ method, you'll have to save and restore option_string (char * real_option_string = option_string; ... option_string = real_option_string;), but I wouldn't recommend it.  Fixing both of these bugs, and a couple of style things, gives you:

#include <stdlib.h>
#include <stdio.h>

int main (void)
{
    char * option_string = calloc(6, sizeof(char));

    int j;
    for ( j = 0; j < 5; j++)
    {
        option_string[j] = 'a';
    }

    printf("print options_string: %s\n", option_string);
    free(option_string);
    return 0;
}

The other thing I changed was your malloc usage.  I feel like calloc is a better stylistic choice here; calloc(count, size) allocates count objects of size size, and zeros them.  It's like malloc(count*size) plus a memset, but feels cleaner to me.  You also shouldn't have a cast on malloc/calloc/etc., generally speaking (it can obscure useful warnings), and you need to allocate six slots, like I said (so you can have the null-terminator, which is the zero-valued character, so we don't need to set it explicitly).  Combine that with the option_string[j] indexing mode, include the missing stdlib.h for calloc (you should have had it for malloc, too), and we're good to go!


问:
Spring Security @Secured annotation and User authorities
This is about Spring v.4 (MVC + Security). I have implemented UserDetailsServiceImpl, where inside the loadUserByUsername method a user is granted with its authorities. Let's say it's simply:

```<code>public UserDetails loadUserByUsername(String username) {
    ...
    Collection<GrantedAuthority> authorities = new ArrayList<>();

    authorities.add(new SimpleGrantedAuthority("ADMIN"));

    return new org.springframework.security.core.userdetails.User(username, password, enabled, true, true, true, authorities);
    ...
}
</code>```

And there is a security controller inside which there is an annotated method with the @Secured annotation:

```<code>@Secured("ADMIN")
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String users(Model model ...) { ... }
</code>```

As you can see inside the loadUserByUsername method I explicitly granted the ADMIN role to the user.
But when I'm trying access the /users I get an Access is denied exception:

2016-04-19 10:25:16,899 DEBUG (http-nio-8080-exec-9)
[org.springframework.security.web.access.ExceptionTranslationFilter] -
Access is denied (user is not anonymous); delegating to
AccessDeniedHandler
org.springframework.security.access.AccessDeniedException: Access is
denied    at
org.springframework.security.access.vote.AbstractAccessDecisionManager.checkAllowIfAllAbstainDecisions(AbstractAccessDecisionManager.java:70)
at
org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:88)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:232)
at
org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
...

(without the @Secured annotation everything works fine).

What have I missed here?

答:
I also faced this issue. Spring Security 4 automatically prefixes any role with ROLE_. Refer to the Spring Security 3.x to 4.x migration guide for more details.

Disabling ROLE_ prefixing

As suggested in the migration guide, the following BeanPostProcessor can be used to disable the automatic ROLE_ prefixing:

public class DefaultRolesPrefixPostProcessor implements BeanPostProcessor,
                                                        PriorityOrdered {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {

        // Remove this if you are not using JSR-250
        if (bean instanceof Jsr250MethodSecurityMetadataSource) {
            ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof DefaultMethodSecurityExpressionHandler) {
            ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof DefaultWebSecurityExpressionHandler) {
            ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof SecurityContextHolderAwareRequestFilter) {
            ((SecurityContextHolderAwareRequestFilter)bean).setRolePrefix("");
        }

        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public int getOrder() {
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }
}
```

<p>Then define it as a bean:</p>

<pre class="lang-java prettyprint-override"><code>@Bean
public static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
    return new DefaultRolesPrefixPostProcessor();
}
</code>```

Checking authorities

Alternatively you can check the authorities using the @PreAuthorize annotation:

@PreAuthorize("hasAuthority('ADMIN')")
```

<p>Ensure that <code>prePostEnabled</code> is enabled:</p>

<pre class="lang-java prettyprint-override"><code>@EnableGlobalMethodSecurity(prePostEnabled = true)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is about Spring v.4 (MVC + Security). I have implemented UserDetailsServiceImpl, where inside the loadUserByUsername method a user is granted with its authorities. Let's say it's simply:

public UserDetails loadUserByUsername(String username) {
    ...
    Collection<GrantedAuthority> authorities = new ArrayList<>();

    authorities.add(new SimpleGrantedAuthority("ADMIN"));

    return new org.springframework.security.core.userdetails.User(username, password, enabled, true, true, true, authorities);
    ...
}

And there is a security controller inside which there is an annotated method with the @Secured annotation:

@Secured("ADMIN")
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String users(Model model ...) { ... }

As you can see inside the loadUserByUsername method I explicitly granted the ADMIN role to the user.
But when I'm trying access the /users I get an Access is denied exception:

2016-04-19 10:25:16,899 DEBUG (http-nio-8080-exec-9)
[org.springframework.security.web.access.ExceptionTranslationFilter] -
Access is denied (user is not anonymous); delegating to
AccessDeniedHandler
org.springframework.security.access.AccessDeniedException: Access is
denied    at
org.springframework.security.access.vote.AbstractAccessDecisionManager.checkAllowIfAllAbstainDecisions(AbstractAccessDecisionManager.java:70)
at
org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:88)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:232)
at
org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
...

(without the @Secured annotation everything works fine).

What have I missed here?

Body:
I also faced this issue. Spring Security 4 automatically prefixes any role with ROLE_. Refer to the Spring Security 3.x to 4.x migration guide for more details.

Disabling ROLE_ prefixing

As suggested in the migration guide, the following BeanPostProcessor can be used to disable the automatic ROLE_ prefixing:

public class DefaultRolesPrefixPostProcessor implements BeanPostProcessor,
                                                        PriorityOrdered {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {

        // Remove this if you are not using JSR-250
        if (bean instanceof Jsr250MethodSecurityMetadataSource) {
            ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof DefaultMethodSecurityExpressionHandler) {
            ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof DefaultWebSecurityExpressionHandler) {
            ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
        }

        if (bean instanceof SecurityContextHolderAwareRequestFilter) {
            ((SecurityContextHolderAwareRequestFilter)bean).setRolePrefix("");
        }

        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public int getOrder() {
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }
}

Then define it as a bean:

@Bean
public static DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
    return new DefaultRolesPrefixPostProcessor();
}

Checking authorities

Alternatively you can check the authorities using the @PreAuthorize annotation:

@PreAuthorize("hasAuthority('ADMIN')")

Ensure that prePostEnabled is enabled:

@EnableGlobalMethodSecurity(prePostEnabled = true)


问:
subprocess not running the command generated though the command works on terminal
```<code>cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]
</code>```

fileformat and filteruser can be blank too

config file below

```<code>[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=
</code>```

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

```<code>['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]
</code>```

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

答:
Command and filter above

```<code>command = ["sudo", "cat", "{filepath}".format(filepath=filepath)]
userfilter = ["egrep", "-v", "\"{filteruser}\"".format(filteruser=filteruser)***]
</code>```

Subprocess

```<code>cmdout = subprocess.Popen(command, stdout=subprocess.PIPE)
filtration = subprocess.Popen(runfilter, stdin=cmdout.stdout,stdout=subprocess.PIPE)

output, err = filtration.communicate()
</code>```

Yes,I used a two steps solutions could not find a single best refer here,Python subprocess command with pipe

Body:
cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]

fileformat and filteruser can be blank too

config file below

[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

Body:
Command and filter above

command = ["sudo", "cat", "{filepath}".format(filepath=filepath)]
userfilter = ["egrep", "-v", "\"{filteruser}\"".format(filteruser=filteruser)***]

Subprocess

cmdout = subprocess.Popen(command, stdout=subprocess.PIPE)
filtration = subprocess.Popen(runfilter, stdin=cmdout.stdout,stdout=subprocess.PIPE)

output, err = filtration.communicate()

Yes,I used a two steps solutions could not find a single best refer here,Python subprocess command with pipe


问:
Conditionally trigger a full page postback from a link button inside an update panel
How do I conditionally trigger a full page postback from a link button inside of an update panel?

I have a custom control that contains its own updatepanel with a link button nested inside of  it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.

Here is the control hierarchy:

```<code>Page
  Custom Control
    UpdatePanel
      LinkButton
</code>```

Event handler Pseudo code:

```<code>LinkButton Click Handler Begin
    If is a partial post back AND a full postback is needed
        Page.DoFullPostback
    End If
End Handler
</code>```

Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.

Thanks for your help!

答: The easiest approach is to create a hidden button somewhere on your page, outside of any UpdatePanels. When you need to do a full postback, use JavaScript to either click the button or issue __doPostback() to it. You can achieve a partial postpack programmatically in JavaScript by calling __doPostback() on an UpdatePanel itself, or to a button inside one.</p>

Body:
How do I conditionally trigger a full page postback from a link button inside of an update panel?

I have a custom control that contains its own updatepanel with a link button nested inside of  it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.

Here is the control hierarchy:

Page
  Custom Control
    UpdatePanel
      LinkButton

Event handler Pseudo code:

LinkButton Click Handler Begin
    If is a partial post back AND a full postback is needed
        Page.DoFullPostback
    End If
End Handler

Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.

Thanks for your help!


问:
time difference betweern varchar field and timestamp field
I have two dates fields as below (I know they are incorrectly design but DBA will not changed it)

```<code>   order_tag varchar(2)    dt_changed timestamp(6)
   06:35:13                27-MAR-17 06.10.31.036561
</code>```

And I know to find the time difference between the timestamp_field and the varchar(2) field.

I tried the below sql and get an ora error:

ORA-01850: hour must be between 0 and 23

```<code>select orq.order_tag,
       rt.dt_changed,
       (to_date(rt.dt_changed,'hh24:mi:ss') -
         (to_date (orq.order_tag, 'hh24:mi:ss'))) time_differ
from   order_request orq,route rt
where  orq.rt_id = rt.rt_id
</code>```

ORA-01850: hour must be between 0 and 23

答:
You seem to want the result in INTERVAL data type, not NUMBER. If you convert both values to DATE, the difference is a NUMBER (in days) which then you need to convert to your desired format. By the way, to convert your timestamp to date, you shouldn't use TO_CHAR; it is much simpler than that, just use CAST( your_timestamp AS DATE ).

But you don't need that. Instead, just convert your VARCHAR2 to TIMESTAMP, using TO_TIMESTAMP( ..., format_model). The difference of two timestamps is an INTERVAL, exactly what you want.

Setup (note - your first column is surely not varchar(2)!)

```<code>create table test_data (order_tag varchar2(20), dt_changed timestamp(6));

Table TEST_DATA created.

insert into test_data
  values ('06:35:13', to_timestamp('27-MAR-17 06.10.31.036561', 'dd-MON-rr hh24.mi.ss.ff'));

1 row inserted.
</code>```

Query (note the number of days - your ORDER_TAG column doesn't have a date, so by default it's the first day of the current month. If that's no good for your business, then you should also store the date, not just the time of day.)

```<code>select to_timestamp(order_tag, 'hh24:mi:ss') - dt_changed as time_diff from test_data;

TIME_DIFF
-------------------
-25 23:35:18.036561
</code>```

If you must "attach" the date from DT_CHANGED to the string in ORDER_TAG, you can do silly things like this (not recommended):

```<code>select to_timestamp(to_char(dt_changed, 'dd-MON-rr') || order_tag, 'dd-MON-yyhh24:mi:ss')
        - dt_changed as time_diff from test_data;

TIME_DIFF
-------------------
+00 00:24:41.963439
</code>```

Body:
I have two dates fields as below (I know they are incorrectly design but DBA will not changed it)

   order_tag varchar(2)    dt_changed timestamp(6)
   06:35:13                27-MAR-17 06.10.31.036561

And I know to find the time difference between the timestamp_field and the varchar(2) field.

I tried the below sql and get an ora error:

ORA-01850: hour must be between 0 and 23

select orq.order_tag,
       rt.dt_changed,
       (to_date(rt.dt_changed,'hh24:mi:ss') -
         (to_date (orq.order_tag, 'hh24:mi:ss'))) time_differ
from   order_request orq,route rt
where  orq.rt_id = rt.rt_id

ORA-01850: hour must be between 0 and 23

Body:
You seem to want the result in INTERVAL data type, not NUMBER. If you convert both values to DATE, the difference is a NUMBER (in days) which then you need to convert to your desired format. By the way, to convert your timestamp to date, you shouldn't use TO_CHAR; it is much simpler than that, just use CAST( your_timestamp AS DATE ).

But you don't need that. Instead, just convert your VARCHAR2 to TIMESTAMP, using TO_TIMESTAMP( ..., format_model). The difference of two timestamps is an INTERVAL, exactly what you want.

Setup (note - your first column is surely not varchar(2)!)

create table test_data (order_tag varchar2(20), dt_changed timestamp(6));

Table TEST_DATA created.

insert into test_data
  values ('06:35:13', to_timestamp('27-MAR-17 06.10.31.036561', 'dd-MON-rr hh24.mi.ss.ff'));

1 row inserted.

Query (note the number of days - your ORDER_TAG column doesn't have a date, so by default it's the first day of the current month. If that's no good for your business, then you should also store the date, not just the time of day.)

select to_timestamp(order_tag, 'hh24:mi:ss') - dt_changed as time_diff from test_data;

TIME_DIFF
-------------------
-25 23:35:18.036561

If you must "attach" the date from DT_CHANGED to the string in ORDER_TAG, you can do silly things like this (not recommended):

select to_timestamp(to_char(dt_changed, 'dd-MON-rr') || order_tag, 'dd-MON-yyhh24:mi:ss')
        - dt_changed as time_diff from test_data;

TIME_DIFF
-------------------
+00 00:24:41.963439


问:
Angular 2: cannot get two ways binding to work in custom component

I'm trying to make a simple angular 2 component displaying a switch button.
It's almost working, except the parent value is not updated when using ngModel.

Here's my custom component:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-switch',
template:`

  <input id="switch" type="checkbox" [(ngModel)]="checked">

 `,
styleUrls: ['./switch.component.css']
})
export class SwitchComponent {

    checkValue:boolean;
    @Output() checkChange = new EventEmitter();

    @Input()
    get checked() {
      return this.checkValue;
    }

    set checked(val) {
       this.checkValue = val;
       this.checkChange.emit(this.checkValue);
       console.log("from switch: value = " + this.checkValue);
    }
}
```

<p>Here's the parent component with 2 instances of my custom child component.
- the first instance works fine but uses separated property [] and event () binding
- the second one is using two ways bindings [()] but is not working. Any idea what am I missing?</p>

<pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template:`
  <app-switch [checked]="checkValue" (checkChange)="onCheckChanged($event)"></app-switch>
  <div>checkBox :<span>{{checkValue}}</span></div>
  <hr/>
  <app-switch [(checked)]="switchValue" ></app-switch>
  <div>checkBox :<span>{{switchValue}}</span></div>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  checkValue:boolean = false;
  switchValue:boolean = false;

  onCheckChanged($event){
    console.log("from AppComponent : " + $event);
    this.checkValue = $event;

  }
}
</code>```

Any advice on this?

答:
Your second instance would require an output checkedChange event emitter since you're binding to the checked property. The naming is slightly off (checkChange vs checkedChange) so it won't allow for the two way binding that you have set up.

Demo Here

Body:
I'm trying to make a simple angular 2 component displaying a switch button.
It's almost working, except the parent value is not updated when using ngModel.

Here's my custom component:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-switch',
template:`

  <input id="switch" type="checkbox" [(ngModel)]="checked">

 `,
styleUrls: ['./switch.component.css']
})
export class SwitchComponent {

    checkValue:boolean;
    @Output() checkChange = new EventEmitter();

    @Input()
    get checked() {
      return this.checkValue;
    }

    set checked(val) {
       this.checkValue = val;
       this.checkChange.emit(this.checkValue);
       console.log("from switch: value = " + this.checkValue);
    }
}

Here's the parent component with 2 instances of my custom child component.
- the first instance works fine but uses separated property [] and event () binding
- the second one is using two ways bindings [()] but is not working. Any idea what am I missing?

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template:`
  <app-switch [checked]="checkValue" (checkChange)="onCheckChanged($event)"></app-switch>

checkBox :{{checkValue}}

  <app-switch [(checked)]="switchValue" ></app-switch>

checkBox :{{switchValue}}
`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  checkValue:boolean = false;
  switchValue:boolean = false;

  onCheckChanged($event){
    console.log("from AppComponent : " + $event);
    this.checkValue = $event;

  }
}

Any advice on this?


问:
android calendar permission issue
I am trying to access the android device calendar, which fails with this exception

I added this exact build hint to the codenameone_settings.properties file:

```<code>codename1.arg.android.xpermissions=<uses-permission android:name="android.permission.READ_CALENDAR"/> <uses-permission android:name="android.permission.WRITE_CALENDAR"/>
</code>```

Is there something I am missing?

答:
This is caused by the new Android security permission in API level 23.

You can set your app to use API level 21 by adding the build hint below and DeviceCalendar should work.

```<code>android.targetSDKVersion=21
</code>```

Remember to always Upvote, Mark as answer, or leave a comment when another user answers your question. That's the only reward they get for helping you to solve a problem.

Title: android calendar permission issue

Body:
I am trying to access the android device calendar, which fails with this exception

I added this exact build hint to the codenameone_settings.properties file:

codename1.arg.android.xpermissions=<uses-permission android:name="android.permission.READ_CALENDAR"/> <uses-permission android:name="android.permission.WRITE_CALENDAR"/>

Is there something I am missing?

Body:
This is caused by the new Android security permission in API level 23.

You can set your app to use API level 21 by adding the build hint below and DeviceCalendar should work.

android.targetSDKVersion=21

Remember to always Upvote, Mark as answer, or leave a comment when another user answers your question. That's the only reward they get for helping you to solve a problem.


问:
best optimal solution for streaming rails server logs to browser
I am looking for a best optimal way to stream my Rails server logs over to the browser. Have tried using browser_log gem which is not working in my case.Please suggest me any such type of gem available or any optimal way to stream the logs.

I am performing a tedious  background job on my server which require  an hour or so to complete so need logs in that case to  keep a track of the job

答:
Try this gem  logstasher

This gem is heavily inspired from lograge, but it's focused on one thing and one thing only. That's making your logs awesome like this https://github.com/shadabahmed/logstasher#awesome-logging-for-rails-