问:
Test-AzureRmResourceGroupDeployment works with TemplateParameterFile but not TemplateParameterObject
I am trying to override some properties in a template parameter file in a powershell script then pass the object to the Test-AzureRmResourceGroupDeployment cmdlet to test it. The following works;

```<code>Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile 'template.json' -TemplateParameterFile 'parameters.json'
</code>```

However, it does not work when I load the parameters and pass the object;

```<code>$params = Get-Content 'parameters.json' | Out-String | ConvertFrom-Json | ConvertPSObjectToHashtable
Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile 'template.json' -TemplateParameterObject $params.parameters
</code>```

The ConvertPSObjectToHashtable function is one I got from here.

When I run the second command, I get the following error;

```<code>Code    : InvalidTemplate
Message : Deployment template validation failed: 'The provided value for the template parameter 'location' at line '7' and column '22' is not valid.'.
Details :
</code>```

Why doesn't it accept the parameters object, and how do I fix it?

答:
I test in my lab, I get the same error log with you. The root reason is Azure json template is like below:

```<code>   "adminUsername": {
      "value": "ghuser"
    },
</code>```

If json template is like below, the function will work.

```<code>"adminUsername":"ghuser"
</code>```

You also could test in your lab, if you transfer following parameters to -
 TemplateParameterObject, it works fine.

```<code>PS D:\compare> $parms

Name                           Value
----                           -----
adminPassword                  ********
dnsLabelPrefix                 shuitest123
adminUsername                  shui
</code>```

However, your $params.parameters is like below:

```<code>PS D:\compare> $params.parameters

Name                           Value
----                           -----
adminPassword                  {value}
dnsLabelPrefix                 {value}
adminUsername                  {value}
</code>```

What you need to do is convert  Azure parameter json file to adminUsername:shui or modify json file like "adminUsername":"ghuser".

Body:
I am trying to override some properties in a template parameter file in a powershell script then pass the object to the Test-AzureRmResourceGroupDeployment cmdlet to test it. The following works;

Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile 'template.json' -TemplateParameterFile 'parameters.json'

However, it does not work when I load the parameters and pass the object;

$params = Get-Content 'parameters.json' | Out-String | ConvertFrom-Json | ConvertPSObjectToHashtable
Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile 'template.json' -TemplateParameterObject $params.parameters

The ConvertPSObjectToHashtable function is one I got from here.

When I run the second command, I get the following error;

Code    : InvalidTemplate
Message : Deployment template validation failed: 'The provided value for the template parameter 'location' at line '7' and column '22' is not valid.'.
Details :

Why doesn't it accept the parameters object, and how do I fix it?

Body:
I test in my lab, I get the same error log with you. The root reason is Azure json template is like below:

   "adminUsername": {
      "value": "ghuser"
    },

If json template is like below, the function will work.

"adminUsername":"ghuser"

You also could test in your lab, if you transfer following parameters to -
 TemplateParameterObject, it works fine.

PS D:\compare> $parms

Name                           Value
----                           -----
adminPassword                  ********
dnsLabelPrefix                 shuitest123
adminUsername                  shui

However, your $params.parameters is like below:

PS D:\compare> $params.parameters

Name                           Value
----                           -----
adminPassword                  {value}
dnsLabelPrefix                 {value}
adminUsername                  {value}

What you need to do is convert  Azure parameter json file to adminUsername:shui or modify json file like "adminUsername":"ghuser".


来源: stackexchange

问:
jqgrid typeahead with key value
I am using the twitter bootstrap typeahead and Guriddo jqgrid Version 5.2.1 form editing.  I'd prefer to do this with key value pair rather then just value. All the code below works as far as it goes, the only thing missing is when the edit form opens for an existing record it shows the key (a number) instead of the value (the name of a company).  The grid columns are all created on the fly. I think if inside editoptions, if I could specify a value: of the name of the company, it might be a good hack-around, but that doesn't work.</p>

```<code>label: svf.fieldLabel,
name: svf.tf[0].nativename,
width: 150,
editable: true,
edittype: "text",
formatter: 'select',
formatoptions:
{
    value: getEditOptionsValue(svf.relatedItemId)
},

editoptions: {
dataInit: function (element) {
    var data = JSON.parse(getSelects(svf.relatedItemId));
    $(element).attr("autocomplete", "off").typeahead({
        appendTo: "body",
        dataType: "json",
        displayText: function (item) { return item.name; },
        source: function (query, process) {
            return process(data);
        }
    });
    } //end datainit
}//end edit options
</code>```

答:
In order to solve your problem you will need to use a custom unformat function.
The predefined unformat function return the key and not the value.
More you can see in our documentation here

You can use the following code:

    label: svf.fieldLabel,
    name: svf.tf[0].nativename,
    width: 150,
    editable: true,
    edittype: "text",
    formatter: 'select',
    unformat : function(value, options, cellObject) {
        return value;
    },

ContentLicense: CC BY-SA 3.0

Title: jqgrid typeahead with key value

Body:
I am using the twitter bootstrap typeahead and Guriddo jqgrid Version 5.2.1 form editing.  I'd prefer to do this with key value pair rather then just value. All the code below works as far as it goes, the only thing missing is when the edit form opens for an existing record it shows the key (a number) instead of the value (the name of a company).  The grid columns are all created on the fly. I think if inside editoptions, if I could specify a value: of the name of the company, it might be a good hack-around, but that doesn't work.

label: svf.fieldLabel,
name: svf.tf[0].nativename,
width: 150,
editable: true,
edittype: "text",
formatter: 'select',
formatoptions:
{
    value: getEditOptionsValue(svf.relatedItemId)
},

editoptions: {
dataInit: function (element) {
    var data = JSON.parse(getSelects(svf.relatedItemId));
    $(element).attr("autocomplete", "off").typeahead({
        appendTo: "body",
        dataType: "json",
        displayText: function (item) { return item.name; },
        source: function (query, process) {
            return process(data);
        }
    });
    } //end datainit
}//end edit options


问:
How read in parallel all data from OrientDB
I want read all data from Orientdb database and I dont want get an iterator, I want read in some way all data in parallel by chunks from distinct pc across the network. There is any way to read database´s clusters in parallel or any other way to do this?</p>

答:
You can use PARALLEL in a SELECT query.

See: https://orientdb.com/docs/last/SQL-Query.html

PARALLEL Executes the query against x concurrent threads, where x refers to the number of processors or cores found on the host operating system of the query. You may find PARALLEL execution useful on long running queries or queries that involve multiple cluster. For simple queries, using PARALLEL may cause a slow down due to the overhead inherent in using multiple threads.


问:
PowerShell length function
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}
```

<p>Loop is not working, it was working till yesterday.</p>

```Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'
```

答:
neways guys all answers are correct , but was not working so i just checked if $select is null or not like
if($select)

{

}
else
{
}

it solved my  purpose thanks a lot

Title: PowerShell length function

Body:
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}

Loop is not working, it was working till yesterday.

Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'


问:
What is the most common waste of computing power in Javascript?
We've all seen people who do this:

```<code>jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}
</code>```

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

答: Calling $.animate to animate elements should make the things slow down.</p>

Body:
We've all seen people who do this:

jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

ContentLicense: CC BY-SA 2.5


问:
Vue.js, toggle class on click doesn't work as expected
I'm learning Due and I'm trying something that should be easy but doesn't work and I'm sure there is something I don't understand.
I have to add a case to a modal...

I simplify the code: I have an array of products from my parent passed the a props and to chunk them in columns I use a computed variabile.
In the computed variable I also add to my object array an attribute active for every object, and I need to use that attribute to add the class.

I cannot change the value: when I click the button the product.active value is changed if I look the console but in my template no, it is false. Why

```<code> <template>
  <div class="columns" v-for="products in processedProducts">
   <div class="column" v-for="product in products">
    ```{{product.active}}```
    Pricy History
    <price-history :asin="product.asin" :active="product.active"></price-history>
   </div>
  </div>
 </template>

<script>

import PriceHistory from '../components/PriceHistory'

export default {
  props: ['results','search','maxprice','discount'],
  name: 'product',
  components: {
    PriceHistory
  },
  methods: {
    activeteModal: function(product){
      console.log(product.active);
      product.active = !product.active;
      console.log(product.active);
    }
  },
  computed: {
    processedProducts() {
      let products = this.results.map((obj) => {
          obj.active = false;
          return obj;
      })

      // Put Array into Chunks
      let i, j, chunkedArray = [], chunk = 5;
      for (i=0, j=0; i < products.length; i += chunk, j++) {
        chunkedArray[j] = products.slice(i,i+chunk);
      }
      return chunkedArray;
    }
  }
}
</script>
</code>```

答:
Computed objects update lazy, set the array as a data property then it will update reactive.
Furthermore computed-objects are by default getter-only.

You better trigger a method that fills the product array when the component is mounted like this:

```<code>    export default {
      props: ['results','search','maxprice','discount'],
      name: 'product',
      components: {
        PriceHistory
      },
        data: function () {
        return {
         products :[]
       }
      },
      mounted: function(){
    this.processedProducts();
    },
      methods: {
        activeteModal: function(product){
          console.log(product.active);
          product.active = !product.active;
          console.log(product.active);
        },
        processedProducts() {
          let products = this.results.map((obj) => {
              obj.active = false;
              return obj;
          })

          // Put Array into Chunks
          let i, j,  chunk = 5;
          for (i=0, j=0; i < products.length; i += chunk, j++) {
            this.products[j] = products.slice(i,i+chunk);
          }
       }
    }
}
</code>```

Body:
I'm learning Due and I'm trying something that should be easy but doesn't work and I'm sure there is something I don't understand.
I have to add a case to a modal...

I simplify the code: I have an array of products from my parent passed the a props and to chunk them in columns I use a computed variabile.
In the computed variable I also add to my object array an attribute active for every object, and I need to use that attribute to add the class.

I cannot change the value: when I click the button the product.active value is changed if I look the console but in my template no, it is false. Why

 <template>

{{product.active}}

    Pricy History
    <price-history :asin="product.asin" :active="product.active"></price-history>

 </template>

Body:
Computed objects update lazy, set the array as a data property then it will update reactive.
Furthermore computed-objects are by default getter-only.

You better trigger a method that fills the product array when the component is mounted like this:

    export default {
      props: ['results','search','maxprice','discount'],
      name: 'product',
      components: {
        PriceHistory
      },
        data: function () {
        return {
         products :[]
       }
      },
      mounted: function(){
    this.processedProducts();
    },
      methods: {
        activeteModal: function(product){
          console.log(product.active);
          product.active = !product.active;
          console.log(product.active);
        },
        processedProducts() {
          let products = this.results.map((obj) => {
              obj.active = false;
              return obj;
          })

          // Put Array into Chunks
          let i, j,  chunk = 5;
          for (i=0, j=0; i < products.length; i += chunk, j++) {
            this.products[j] = products.slice(i,i+chunk);
          }
       }
    }
}


问:
Intellij Idea: Python import showing error even when code using module is running
I am working on a python project using editor Intellij Idea, Ultimate 2017 Edition.

In my working file sample.py code looks like

```<code>import os

def sample_fuc():
    print(os.stat("C:\\Users\admin"))
</code>```

Python SDK is already configured, code is running fine [When running through intellij run configuration] and printing the desired result, but somehow Intellij is not able to find the module os and showing error No module named os

So, I want to understand 2 things here :

1.) How does Intellij idea searches for modules available in python libraries. Do I need to configure somewhere in intellij to look for available modules. Is there something default set to it, if yes, why common module like os is not available in default path?

2.) If I need to configure, what all directory paths python usually have on windows where it stores installed modules?

答:
possible intellij is not able to identify your python interpreter path.

refer: How do I get IntelliJ to recognize common Python modules?

Body:
I am working on a python project using editor Intellij Idea, Ultimate 2017 Edition.

In my working file sample.py code looks like

import os

def sample_fuc():
    print(os.stat("C:\\Users\admin"))

Python SDK is already configured, code is running fine [When running through intellij run configuration] and printing the desired result, but somehow Intellij is not able to find the module os and showing error No module named os

So, I want to understand 2 things here :

1.) How does Intellij idea searches for modules available in python libraries. Do I need to configure somewhere in intellij to look for available modules. Is there something default set to it, if yes, why common module like os is not available in default path?

2.) If I need to configure, what all directory paths python usually have on windows where it stores installed modules?


问:
How to round values only for display in pandas while retaining original ones in the dataframe?
I wish to only round values in the DataFrame for display purposes, when I use head() or tail() but I want the DataFrame to retain the original values.

I tried using the round method but it changes the values in the original DataFrame. I don't wish to create a separate copy each time for this purpose.

Is there any other way than creating a separate copy?

I'm having trouble glancing at values because some columns have e^10 notations. I'd just like to have a look at two to three decimal places maximum and not keep glancing at exponent values.

答:
You can temporarily change the display option:

```<code>with pd.option_context('display.precision', 3):
    print(df.head())

       0      1      2      3      4
0 -0.462 -0.698 -2.030  0.766 -1.670
1  0.925  0.603 -1.062  1.026 -0.096
2  0.589  0.819 -1.040 -0.162  2.467
3 -1.169  0.637 -0.435  0.584  1.232
4 -0.704 -0.623  1.226  0.507  0.507
</code>```

Or change it permanently:

```<code>pd.set_option('display.precision', 3)
</code>```

A simple print(df.head().round(3))  would also work in this case. They will not change the DataFrame in place.

ContentLicense: CC BY-SA 4.0

Body:
You can temporarily change the display option:

with pd.option_context('display.precision', 3):
    print(df.head())

       0      1      2      3      4
0 -0.462 -0.698 -2.030  0.766 -1.670
1  0.925  0.603 -1.062  1.026 -0.096
2  0.589  0.819 -1.040 -0.162  2.467
3 -1.169  0.637 -0.435  0.584  1.232
4 -0.704 -0.623  1.226  0.507  0.507

Or change it permanently:

pd.set_option('display.precision', 3)

A simple print(df.head().round(3))  would also work in this case. They will not change the DataFrame in place.


问:
J string manipulation using only builtins
You are given a string like ))()(())(, and you wish to remove all instances of () from the string, which in this case means these two instances:

```<code>))()(())(
  ^^ ^^
</code>```

leaving only ))()(.

I know you can use the library function stringreplace, or you could load up a regex library, but I want to know is if there is a concise way of accomplishing this the the J builtin operators exclusively?

I should clarify that my own solution was:

```<code>#~(-.@+._1&|.)@('()'&E.)
</code>```

which I consider verbose -- so any similar solutions would not qualify as "concise" in my book.  I'm really asking if there is a way to use a builtin (or maybe a simple combination of 2) to solve this directly.  I expect this answer is no.

答:
Not sure how concise it is, but I think that this will work:

```<code>   deparen=. (-.@:(+/)@:(_1&|. ,: ])@:E. # ])
   '()' deparen '))()(())('
))()(
</code>```

Essentially the work is done by -. @: (+/) @: (_1&|. ,: ] )@:E. to create a bit string that removes the '()' instances using # (Copy) on the right argument.

E. identifies the positions of '()' using a bit string. Shift and laminate to get positions of '(' and ')', add them together to have 1 1 in the string where ever there is a '()' and then negate so these positions become 0 0 and are removed using Copy

Body:
You are given a string like ))()(())(, and you wish to remove all instances of () from the string, which in this case means these two instances:

))()(())(
  ^^ ^^

leaving only ))()(.

I know you can use the library function stringreplace, or you could load up a regex library, but I want to know is if there is a concise way of accomplishing this the the J builtin operators exclusively?

I should clarify that my own solution was:

#~(-.@+._1&|.)@('()'&E.)

which I consider verbose -- so any similar solutions would not qualify as "concise" in my book.  I'm really asking if there is a way to use a builtin (or maybe a simple combination of 2) to solve this directly.  I expect this answer is no.

Body:
Not sure how concise it is, but I think that this will work:

   deparen=. (-.@:(+/)@:(_1&|. ,: ])@:E. # ])
   '()' deparen '))()(())('
))()(

Essentially the work is done by -. @: (+/) @: (_1&|. ,: ] )@:E. to create a bit string that removes the '()' instances using # (Copy) on the right argument.

E. identifies the positions of '()' using a bit string. Shift and laminate to get positions of '(' and ')', add them together to have 1 1 in the string where ever there is a '()' and then negate so these positions become 0 0 and are removed using Copy


问:
Oracle Data Type for text file?
I need to create a table in Oracle that will store a series of large text files.  After looking at the Oracle datatype's it is unclear what type I should use to store the files.

The limits on the text specific types like VARCHAR2 seem very small (32K).  The other types don't seem to be the right match for a text file (e.g. BFILE).

Does anyone have an opinion on the right type to use?

答:
The difference between CLOB and BLOB/BFILE is that CLOBs are treated as Text. That is, if you pull a CLOB from the database it will do any conversion necessary from the database character set to the client character set (eg removing an accent from an ê). Similarly, when a CLOB is created by a client, there can be a conversion from the client character set to the database character set. If both client and database character sets are the same, then no conversion is needed or performed.

NCLOB is like CLOB except that rather than the database character set, the conversion uses the NLS NCHAR characterset.

A BLOB/BFILE will not be subject to the conversion rules.

So GENERALLY I would use a CLOB for text, but if there is some checksum/audit trail logic where I don't want even the slightest possibility of a character set conversion, I might opt for a BLOB/BFILE. I wouldn't consider a LONG or LONG RAW.

Title: Oracle Data Type for text file?


问:
sum of array fields using jquery closest
I need some help solving this problem,

i have dynamically created div,

```<code><div class='items'>
     Item 1 <input type='text' class='subprice'  name='item[]'> [X]
     Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>
</div>

<div class='items'>
    Item 1 <input type='text' class='subprice'  name='item[]'> [X]
    Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    Item 3 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>
</div>
</code>```

how am i able to get the total array value of item[] by using .closest and display it to the subtotal text field.. note that class items is dynamically created, therefore it can be created multiple times.

i tried

```<code>var i = $(.items).closest();
var arr =  i.find('[name="item[]"]');
</code>```

so arr should contain the sum of item[] within the nearest class items

Thank you in advance.

答:
Your subtotal field should be array and try like,

```<code>$('.items').each(function(){
   var items = $(this).find('[name="item[]"]'),
       total=0;
   items.each(function(){
       total+=Number(this.value);
   });
   $(this).find('[name="subtotal[]"]').val(total);
});
</code>```

Snippet,

$(function() {
  function subTotal(items) {
    items.each(function() {
      var items = $(this).find('[name="item[]"]'),
        total = 0;
      items.each(function() {
        total += Number(this.value);
      });
      $(this).find('[name="subtotal[]"]').val(total);
    });
  }
  subTotal($('.items'));
  $('.delete').on('click', function() {
    items = $(this).closest('.items');
    $(this).closest('.item').remove();
    subTotal(items);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.delete {
  color: blue;
  cursor: pointer;
  margin: 0 5px
}</code>```

Item 1 <input type='text' class='subprice' name='item[]' value="8">Delete

Item 2 <input type='text' value="5" class='subprice' name='item[]'>Delete

  <input type='text' class='subprice' name='subtotal[]'>

Item 1 <input type='text' class='subprice' name='item[]' value="8">Delete

 Item 2 <input type='text' class='subprice' name='item[]' value="55">Delete

Item 3 <input type='text' class='subprice' name='item[]' value="14">Delete

  <input type='text' class='subprice' name='subtotal[]'>

```

Body:
I need some help solving this problem,

i have dynamically created div,

     Item 1 <input type='text' class='subprice'  name='item[]'> [X]
     Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>

    Item 1 <input type='text' class='subprice'  name='item[]'> [X]
    Item 2 <input type='text' class='subprice'  name='item[]'> [X]
    Item 3 <input type='text' class='subprice'  name='item[]'> [X]
    <input type='text' class='subprice'  name='subtotal'>

how am i able to get the total array value of item[] by using .closest and display it to the subtotal text field.. note that class items is dynamically created, therefore it can be created multiple times.

i tried

var i = $(.items).closest();
var arr =  i.find('[name="item[]"]');

so arr should contain the sum of item[] within the nearest class items

Thank you in advance.

Body:
Your subtotal field should be array and try like,

$('.items').each(function(){
   var items = $(this).find('[name="item[]"]'),
       total=0;
   items.each(function(){
       total+=Number(this.value);
   });
   $(this).find('[name="subtotal[]"]').val(total);
});

Snippet,

$(function() {
  function subTotal(items) {
    items.each(function() {
      var items = $(this).find('[name="item[]"]'),
        total = 0;
      items.each(function() {
        total += Number(this.value);
      });
      $(this).find('[name="subtotal[]"]').val(total);
    });
  }
  subTotal($('.items'));
  $('.delete').on('click', function() {
    items = $(this).closest('.items');
    $(this).closest('.item').remove();
    subTotal(items);
  });
});

.delete {
  color: blue;
  cursor: pointer;
  margin: 0 5px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='items'>
  <div class="item">Item 1 <input type='text' class='subprice' name='item[]' value="8"><span class="delete">Delete</span></div>
  <div class="item">Item 2 <input type='text' value="5" class='subprice' name='item[]'><span class="delete">Delete</span></div>
  <input type='text' class='subprice' name='subtotal[]'>
</div>
<div class='items'>
  <div class="item">Item 1 <input type='text' class='subprice' name='item[]' value="8"><span class="delete">Delete</span></div>
  <div class="item"> Item 2 <input type='text' class='subprice' name='item[]' value="55"><span class="delete">Delete</span></div>
  <div class="item">Item 3 <input type='text' class='subprice' name='item[]' value="14"><span class="delete">Delete</span></div>
  <input type='text' class='subprice' name='subtotal[]'>
</div>


问:
C# Execute the catch block when the type is string
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

```<code>dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}
</code>```

答:
I'm guessing that you check in ExecuteSquarePayment for the correct type of the argument, right? If so, why not simply use the catch block with out the type restriction. If the argument type is correct there won't be an error.

I don't see any different return for other types that the argument may be.

Body:
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}


问:
Qt3D ExtrudedTextMesh is not a type
I tested this code in Qt 5.9.1 for mac, and qtcreator reports error: ExtrudedTextMesh is not a type.</p>

```<code>import QtQuick 2.0
import Qt3D.Core 2.0
import Qt3D.Extras 2.0

// 3D 文本示例
Entity{
    components: [
        // bug: ExtrudedTextMesh is not a type, Qt 5.9.1 mac
        ExtrudedTextMesh {
            text: "Hello 3D"
            depth: 0.2
        },
        PhongAlphaMaterial{
            id: colorMaterial
            ambient: Qt.rgba( 1, 0, 0, 1.0 )
            diffuse: Qt.rgba( 1, 0, 0, 1.0 )
            specular: Qt.rgba(1, 0, 0, 1.0 )
            shininess: 1.0
            alpha: 0.5
        }
    ]
}
</code>```

答:
This bug has been reported, review it QTBUG-61451. In the comments says:

Use import Qt3D.Extras 2.9 as it's new in Qt 5.9.

I have tried it and it works.

Title: Qt3D ExtrudedTextMesh is not a type

Body:
I tested this code in Qt 5.9.1 for mac, and qtcreator reports error: ExtrudedTextMesh is not a type.

import QtQuick 2.0
import Qt3D.Core 2.0
import Qt3D.Extras 2.0

// 3D 文本示例
Entity{
    components: [
        // bug: ExtrudedTextMesh is not a type, Qt 5.9.1 mac
        ExtrudedTextMesh {
            text: "Hello 3D"
            depth: 0.2
        },
        PhongAlphaMaterial{
            id: colorMaterial
            ambient: Qt.rgba( 1, 0, 0, 1.0 )
            diffuse: Qt.rgba( 1, 0, 0, 1.0 )
            specular: Qt.rgba(1, 0, 0, 1.0 )
            shininess: 1.0
            alpha: 0.5
        }
    ]
}


问:
jQuery calendar Picker css style

  var calendarPicker2 = $("#dsel2").calendarPicker({
    monthNames:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    useWheel:true,

    years:0,
    months:0,
    days:5,
    showDayArrows:false,
    callback:function(cal) {

    }});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.calBox {
  background-color: white;
  padding: 2px;
  -moz-border-radius: 4px;
  text-align: center;
  color: black;
}

.calElement {
  margin: 1px;
  display: inline-block;
  overflow:hidden;
}

.calYear {
    font-size: 20px;
    /* border-bottom: 1px dashed #c3c3c3; */
    padding-bottom: 5px;
    margin-bottom: 5px;
}

.calYear .calElement {
  border: 1px solid #999999;
}

.calMonth {
  border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;
}

.calMonth .calElement {
  font-size: 14px;
  border: 1px solid #999999;
}

.calDay {
}

.calDay .calElement {
  font-size: 12px;
  border: 1px solid #999999;
}

span.calElement.next:hover, span.calElement.prev:hover {

  cursor: pointer;
}

.calDay .calElement .dayNumber {
  font-size: 20px;
}

.calElement.selected {
  background-color: #53585f;

 border-radius: 23px
}

span.calElement:hover {
  background-color: #404040;

border-radius: 23px;
  cursor: pointer;
}

.calElement.today {

border-radius: 23px
}</code>```

```
</div>
</div>
</p>

<p>i have a jQuery calendar , im try to do change css in i needed , im attached the two image <code>image 01</code> is i need like this  , <code>image 02</code> is current view, i need  to how can i change like an <code>image 01</code>
Image-01</p>

<p>Image-02</p>

<p><strong>this is my code part</strong>
<strong>HTML</strong></p>

```

```

<p><strong>calendar script</strong></p>

```
```

<p><strong>css</strong></p>

```.calBox {
  background-color: white;
  padding: 2px;
  -moz-border-radius: 4px;
  text-align: center;
  color: black;
}

.calElement {
  margin: 1px;
  display: inline-block;
  overflow:hidden;
}

.calYear {
    font-size: 20px;
    /* border-bottom: 1px dashed #c3c3c3; */
    padding-bottom: 5px;
    margin-bottom: 5px;
}

.calYear .calElement {
  border: 1px solid #999999;
}

.calMonth {
  border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;
}

.calMonth .calElement {
  font-size: 14px;
  border: 1px solid #999999;
}

.calDay {
}

.calDay .calElement {
  font-size: 12px;
  border: 1px solid #999999;
}

span.calElement.next:hover, span.calElement.prev:hover {

  cursor: pointer;
}

.calDay .calElement .dayNumber {
  font-size: 20px;
}

.calElement.selected {
  background-color: #53585f;

 border-radius: 23px
}

span.calElement:hover {
  background-color: #404040;

border-radius: 23px;
  cursor: pointer;
}

.calElement.today {

border-radius: 23px
}
```

<p><strong>js</strong></p>

```jQuery.fn.calendarPicker = function(options) {
  // --------------------------  start default option values --------------------------
  if (!options.date) {
    options.date = new Date();
  }

  if (typeof(options.years) == "undefined")
    options.years=1;

  if (typeof(options.months) == "undefined")
    options.months=3;

  if (typeof(options.days) == "undefined")
    options.days=4;

  if (typeof(options.showDayArrows) == "undefined")
    options.showDayArrows=true;

  if (typeof(options.useWheel) == "undefined")
    options.useWheel=true;

  if (typeof(options.callbackDelay) == "undefined")
    options.callbackDelay=500;

  if (typeof(options.monthNames) == "undefined")
    options.monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

  if (typeof(options.dayNames) == "undefined")
    options.dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

  // --------------------------  end default option values --------------------------

  var calendar = {currentDate: options.date};
  calendar.options = options;

  //build the calendar on the first element in the set of matched elements.
  var theDiv = this.eq(0);//$(this);
  theDiv.addClass("calBox");

  //empty the div
  theDiv.empty();

  var divYears = $("
").addClass("calYear");
  var divMonths = $("
").addClass("calMonth");
  var divDays = $("
").addClass("calDay");

  theDiv.append(divYears).append(divMonths).append(divDays);

  calendar.changeDate = function(date) {
    calendar.currentDate = date;

    var fillYears = function(date) {
      var year = date.getFullYear();
      var t = new Date();
      divYears.empty();
      var nc = options.years*2+1;
      var w = parseInt((theDiv.width()-4-(nc)*4)/nc)+"px";
      for (var i = year - options.years; i <= year + options.years; i++) {
        var d = new Date(date);
        d.setFullYear(i);
        var span = $("").addClass("calElement").attr("millis", d.getTime()).html(i).css("width",w);
        if (d.getYear() == t.getYear())
          span.addClass("today");
        if (d.getYear() == calendar.currentDate.getYear())
          span.addClass("selected");
        divYears.append(span);
      }
    }

    var fillMonths = function(date) {
      var month = date.getMonth();
      var t = new Date();
      divMonths.empty();
      var oldday = date.getDay();
      var nc = options.months*2+1;
      var w = parseInt((theDiv.width()-4-(nc)*4)/nc)+"px";
      for (var i = -options.months; i <= options.months; i++) {
        var d = new Date(date);
        var oldday = d.getDate();
        d.setMonth(month + i);

        if (d.getDate() != oldday) {
          d.setMonth(d.getMonth() - 1);
          d.setDate(28);
        }
        var span = $("").addClass("calElement").attr("millis", d.getTime()).html(options.monthNames[d.getMonth()]).css("width",w);
        if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth())
          span.addClass("today");
        if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth())
          span.addClass("selected");
        divMonths.append(span);

      }
    }

    var fillDays = function(date) {
      var day = date.getDate();
      var t = new Date();
      divDays.empty();
      var nc = options.days*2+1;
      var w = parseInt((theDiv.width()-4-(options.showDayArrows?12:0)-(nc)*4)/(nc-(options.showDayArrows?2:0)))+"px";
      for (var i = -options.days; i <= options.days; i++) {
        var d = new Date(date);
        d.setDate(day + i)
        var span = $("").addClass("calElement").attr("millis", d.getTime())
        if (i == -options.days && options.showDayArrows) {
          span.addClass("prev");
        } else if (i == options.days && options.showDayArrows) {
          span.addClass("next");
        } else {
          span.html("" + d.getDate() + "
" + options.dayNames[d.getDay()]).css("width",w);
          if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth() && d.getDate() == t.getDate())
            span.addClass("today");
          if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth() && d.getDate() == calendar.currentDate.getDate())
            span.addClass("selected");
        }
        divDays.append(span);

      }
    }

    var deferredCallBack = function() {
      if (typeof(options.callback) == "function") {
        if (calendar.timer)
          clearTimeout(calendar.timer);

        calendar.timer = setTimeout(function() {
          options.callback(calendar);
        }, options.callbackDelay);
      }
    }

    fillYears(date);
    fillMonths(date);
    fillDays(date);

    deferredCallBack();

  }

  theDiv.click(function(ev) {
    var el = $(ev.target).closest(".calElement");
    if (el.hasClass("calElement")) {
      calendar.changeDate(new Date(parseInt(el.attr("millis"))));
    }
  });

  //if mousewheel
  if ($.event.special.mousewheel && options.useWheel) {
    divYears.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setFullYear(d.getFullYear() + delta);
      calendar.changeDate(d);
      return false;
    });
    divMonths.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setMonth(d.getMonth() + delta);
      calendar.changeDate(d);
      return false;
    });
    divDays.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setDate(d.getDate() + delta);
      calendar.changeDate(d);
      return false;
    });
  }

  calendar.changeDate(options.date);

  return calendar;
};
```

答:
Try this,

Here I am using bootstrap date paginator for horizontal calendar.

jsFiddle for the same.

https://jsfiddle.net/40hye90d/3/

Use below js for your requirement.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepaginator/1.1.0/bootstrap-datepaginator.js"></script>
</code>```

To enable date selection in calender, use below code.

```<code>    <script type="text/javascript">
        $(function() {
            $('#paginator').datepaginator({selectedDate:'2017-07-07',startDate:'2017-01-01',endDate:'2017-12-30'});
        });
    </script>
</code>```

Title: jQuery calendar Picker css style

Body:
  var calendarPicker2 = $("#dsel2").calendarPicker({
    monthNames:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    useWheel:true,

    years:0,
    months:0,
    days:5,
    showDayArrows:false,
    callback:function(cal) {

    }});

.calBox {
  background-color: white;
  padding: 2px;
  -moz-border-radius: 4px;
  text-align: center;
  color: black;
}

.calElement {
  margin: 1px;
  display: inline-block;
  overflow:hidden;
}

.calYear {
    font-size: 20px;
    /* border-bottom: 1px dashed #c3c3c3; */
    padding-bottom: 5px;
    margin-bottom: 5px;
}

.calYear .calElement {
  border: 1px solid #999999;
}

.calMonth {
  border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;
}

.calMonth .calElement {
  font-size: 14px;
  border: 1px solid #999999;
}

.calDay {
}

.calDay .calElement {
  font-size: 12px;
  border: 1px solid #999999;
}

span.calElement.next:hover, span.calElement.prev:hover {

  cursor: pointer;
}

.calDay .calElement .dayNumber {
  font-size: 20px;
}

.calElement.selected {
  background-color: #53585f;

 border-radius: 23px
}

span.calElement:hover {
  background-color: #404040;

border-radius: 23px;
  cursor: pointer;
}

.calElement.today {

border-radius: 23px
}

i have a jQuery calendar , im try to do change css in i needed , im attached the two image image 01 is i need like this  , image 02 is current view, i need  to how can i change like an image 01
Image-01

Image-02

this is my code part
HTML

calendar script

css

.calBox {
  background-color: white;
  padding: 2px;
  -moz-border-radius: 4px;
  text-align: center;
  color: black;
}

.calElement {
  margin: 1px;
  display: inline-block;
  overflow:hidden;
}

.calYear {
    font-size: 20px;
    /* border-bottom: 1px dashed #c3c3c3; */
    padding-bottom: 5px;
    margin-bottom: 5px;
}

.calYear .calElement {
  border: 1px solid #999999;
}

.calMonth {
  border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;
}

.calMonth .calElement {
  font-size: 14px;
  border: 1px solid #999999;
}

.calDay {
}

.calDay .calElement {
  font-size: 12px;
  border: 1px solid #999999;
}

span.calElement.next:hover, span.calElement.prev:hover {

  cursor: pointer;
}

.calDay .calElement .dayNumber {
  font-size: 20px;
}

.calElement.selected {
  background-color: #53585f;

 border-radius: 23px
}

span.calElement:hover {
  background-color: #404040;

border-radius: 23px;
  cursor: pointer;
}

.calElement.today {

border-radius: 23px
}

js

jQuery.fn.calendarPicker = function(options) {
  // --------------------------  start default option values --------------------------
  if (!options.date) {
    options.date = new Date();
  }

  if (typeof(options.years) == "undefined")
    options.years=1;

  if (typeof(options.months) == "undefined")
    options.months=3;

  if (typeof(options.days) == "undefined")
    options.days=4;

  if (typeof(options.showDayArrows) == "undefined")
    options.showDayArrows=true;

  if (typeof(options.useWheel) == "undefined")
    options.useWheel=true;

  if (typeof(options.callbackDelay) == "undefined")
    options.callbackDelay=500;

  if (typeof(options.monthNames) == "undefined")
    options.monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

  if (typeof(options.dayNames) == "undefined")
    options.dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

  // --------------------------  end default option values --------------------------

  var calendar = {currentDate: options.date};
  calendar.options = options;

  //build the calendar on the first element in the set of matched elements.
  var theDiv = this.eq(0);//$(this);
  theDiv.addClass("calBox");

  //empty the div
  theDiv.empty();

  var divYears = $("
").addClass("calYear");
  var divMonths = $("
").addClass("calMonth");
  var divDays = $("
").addClass("calDay");

  theDiv.append(divYears).append(divMonths).append(divDays);

  calendar.changeDate = function(date) {
    calendar.currentDate = date;

    var fillYears = function(date) {
      var year = date.getFullYear();
      var t = new Date();
      divYears.empty();
      var nc = options.years*2+1;
      var w = parseInt((theDiv.width()-4-(nc)*4)/nc)+"px";
      for (var i = year - options.years; i <= year + options.years; i++) {
        var d = new Date(date);
        d.setFullYear(i);
        var span = $("").addClass("calElement").attr("millis", d.getTime()).html(i).css("width",w);
        if (d.getYear() == t.getYear())
          span.addClass("today");
        if (d.getYear() == calendar.currentDate.getYear())
          span.addClass("selected");
        divYears.append(span);
      }
    }

    var fillMonths = function(date) {
      var month = date.getMonth();
      var t = new Date();
      divMonths.empty();
      var oldday = date.getDay();
      var nc = options.months*2+1;
      var w = parseInt((theDiv.width()-4-(nc)*4)/nc)+"px";
      for (var i = -options.months; i <= options.months; i++) {
        var d = new Date(date);
        var oldday = d.getDate();
        d.setMonth(month + i);

        if (d.getDate() != oldday) {
          d.setMonth(d.getMonth() - 1);
          d.setDate(28);
        }
        var span = $("").addClass("calElement").attr("millis", d.getTime()).html(options.monthNames[d.getMonth()]).css("width",w);
        if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth())
          span.addClass("today");
        if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth())
          span.addClass("selected");
        divMonths.append(span);

      }
    }

    var fillDays = function(date) {
      var day = date.getDate();
      var t = new Date();
      divDays.empty();
      var nc = options.days*2+1;
      var w = parseInt((theDiv.width()-4-(options.showDayArrows?12:0)-(nc)*4)/(nc-(options.showDayArrows?2:0)))+"px";
      for (var i = -options.days; i <= options.days; i++) {
        var d = new Date(date);
        d.setDate(day + i)
        var span = $("").addClass("calElement").attr("millis", d.getTime())
        if (i == -options.days && options.showDayArrows) {
          span.addClass("prev");
        } else if (i == options.days && options.showDayArrows) {
          span.addClass("next");
        } else {
          span.html("" + d.getDate() + "
" + options.dayNames[d.getDay()]).css("width",w);
          if (d.getYear() == t.getYear() && d.getMonth() == t.getMonth() && d.getDate() == t.getDate())
            span.addClass("today");
          if (d.getYear() == calendar.currentDate.getYear() && d.getMonth() == calendar.currentDate.getMonth() && d.getDate() == calendar.currentDate.getDate())
            span.addClass("selected");
        }
        divDays.append(span);

      }
    }

    var deferredCallBack = function() {
      if (typeof(options.callback) == "function") {
        if (calendar.timer)
          clearTimeout(calendar.timer);

        calendar.timer = setTimeout(function() {
          options.callback(calendar);
        }, options.callbackDelay);
      }
    }

    fillYears(date);
    fillMonths(date);
    fillDays(date);

    deferredCallBack();

  }

  theDiv.click(function(ev) {
    var el = $(ev.target).closest(".calElement");
    if (el.hasClass("calElement")) {
      calendar.changeDate(new Date(parseInt(el.attr("millis"))));
    }
  });

  //if mousewheel
  if ($.event.special.mousewheel && options.useWheel) {
    divYears.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setFullYear(d.getFullYear() + delta);
      calendar.changeDate(d);
      return false;
    });
    divMonths.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setMonth(d.getMonth() + delta);
      calendar.changeDate(d);
      return false;
    });
    divDays.mousewheel(function(event, delta) {
      var d = new Date(calendar.currentDate.getTime());
      d.setDate(d.getDate() + delta);
      calendar.changeDate(d);
      return false;
    });
  }

  calendar.changeDate(options.date);

  return calendar;
};

Body:
Try this,

Here I am using bootstrap date paginator for horizontal calendar.

jsFiddle for the same.

https://jsfiddle.net/40hye90d/3/

Use below js for your requirement.

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepaginator/1.1.0/bootstrap-datepaginator.js"></script>

To enable date selection in calender, use below code.

    <script type="text/javascript">
        $(function() {
            $('#paginator').datepaginator({selectedDate:'2017-07-07',startDate:'2017-01-01',endDate:'2017-12-30'});
        });
    </script>


问:
m2eclipse: Eclipse is running in a JRE, but a JDK is required
I have a problem with m2eclipse (0.10.0) together with eclipse galileo (Build id: 20090920-1017).

I always get the error message:"Eclipse is running in a JRE, but a JDK is required". I have tried several things, but nothing works. The error message is still there. Here are the things I have tried:

In Window>Preferences>Java>Installed JREs I checked JDK1.6.0_20. DOES NOT WORK

In Window>Preferences>Java>Installed JREs I removed all JREs. Only the checked JDK1.6.0_20 is still there. DOES NOT WORK

In Window>Preferences>Java>Installed JREs>Execution Environments I choosed JavaSE-1.6 and checked JDK1.6.0_20[perfect match]. DOES NOT WORK.

In Preferences of the eclipse desktop start icon I added the -vm parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin). DOES NOT WORK.

I added the clean parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin -clean). DOES NOT WORK.

I added the -vm parameter to the eclipse.ini file with a carriage return after -vm and C:/Programme/Java/jdk1.6.0_20/bin/javaw.exe in a new line. DOES NOT WORK.

After doing all these things I removed the m2eclipse plugin and installed it once again.  DOES NOT WORK.

New ideas I have tried:

In Preferences of the eclipse desktop start icon I put the executable at the end (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe). DOES NOT WORK.

I changed in eclipse.ini the slashes to backslashes. DOES NOT WORK.

Here is my eclipse.ini file:

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
</code>```

Is anyone out there who have other ideas? Any help is appreciated.

Thank You very much.
GernoK

答:
MARIO-ORTEGON  answered is the right answer to this problem. The only thing you need to do is to move this line "-vm C:\java\jdk\bin\javaw.exe" under the section -product org.eclipse.epp.package.jee.product in eclipse.ini. like this:
-product
org.eclipse.epp.package.jee.product
-vm
C:\java\jdk\bin\javaw.exe
save and restart the eclipse. Error will be gone.  </p>

Body:
I have a problem with m2eclipse (0.10.0) together with eclipse galileo (Build id: 20090920-1017).

I always get the error message:"Eclipse is running in a JRE, but a JDK is required". I have tried several things, but nothing works. The error message is still there. Here are the things I have tried:

In Window>Preferences>Java>Installed JREs I checked JDK1.6.0_20. DOES NOT WORK

In Window>Preferences>Java>Installed JREs I removed all JREs. Only the checked JDK1.6.0_20 is still there. DOES NOT WORK

In Window>Preferences>Java>Installed JREs>Execution Environments I choosed JavaSE-1.6 and checked JDK1.6.0_20[perfect match]. DOES NOT WORK.

In Preferences of the eclipse desktop start icon I added the -vm parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin). DOES NOT WORK.

I added the clean parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin -clean). DOES NOT WORK.

I added the -vm parameter to the eclipse.ini file with a carriage return after -vm and C:/Programme/Java/jdk1.6.0_20/bin/javaw.exe in a new line. DOES NOT WORK.

After doing all these things I removed the m2eclipse plugin and installed it once again.  DOES NOT WORK.

New ideas I have tried:

In Preferences of the eclipse desktop start icon I put the executable at the end (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe). DOES NOT WORK.

I changed in eclipse.ini the slashes to backslashes. DOES NOT WORK.

Here is my eclipse.ini file:

-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

Is anyone out there who have other ideas? Any help is appreciated.

Thank You very much.
GernoK


问:
How to fix Fail to connect to camera service on android?
my app occur Fail to connect to camera service error.

because, I intentionally disconnect my camera.

this problem. if users intentionally disconnect camera. occur Fail to connect to camera service and app is die.

I want if camera disconnect, app not die.

my source

```<code>private static Camera mCamera = null;

if (mCamera == null) {
    mCamera = Camera.open(0);
    if (mCamera != null) {
        mCamera.lock();
    }
} ...
</code>```

How to avoid camera opening when camera is not connected?

thanks.

答:
First of all, android.hardware.Camera was deprecated in API level 21. You should use android.hardware.camera2 instead if you targeting API level 21 or above.

Camera.open(0) throw exception if opening the camera fails but noth returning null. See the documentation for more details. So, you need to catch exception instead of checking null.

```<code>if (mCamera == null) {
    try {
        mCamera = Camera.open(0);
        mCamera.lock();
        ...
    } catch(RuntimeException e) {
        // opening the camera fails
    }
} ...
</code>```

Body:
my app occur Fail to connect to camera service error.

because, I intentionally disconnect my camera.

this problem. if users intentionally disconnect camera. occur Fail to connect to camera service and app is die.

I want if camera disconnect, app not die.

my source

private static Camera mCamera = null;

if (mCamera == null) {
    mCamera = Camera.open(0);
    if (mCamera != null) {
        mCamera.lock();
    }
} ...

How to avoid camera opening when camera is not connected?

thanks.

Body:
First of all, android.hardware.Camera was deprecated in API level 21. You should use android.hardware.camera2 instead if you targeting API level 21 or above.

Camera.open(0) throw exception if opening the camera fails but noth returning null. See the documentation for more details. So, you need to catch exception instead of checking null.

if (mCamera == null) {
    try {
        mCamera = Camera.open(0);
        mCamera.lock();
        ...
    } catch(RuntimeException e) {
        // opening the camera fails
    }
} ...


问:
How to implement method swizzling swift 3.0?
How can I implement method swizzling in Swift 3.0 ?

I've read nshipster article about it, but in this code's chunk

```<code>struct Static {
    static var token: dispatch_once_t = 0
}
</code>```

the compiler gives me an error

dispatch_once_t is unavailable in Swift: Use lazily initialized
  globals instead

答:
Swizzling in Playground

Swift 5

```<code>import Foundation
class TestSwizzling : NSObject {
    @objc dynamic func methodOne()->Int{
        return 1
    }
}

extension TestSwizzling {
    @objc func methodTwo()->Int{
        // It will not be a recursive call anymore after the swizzling
        return 2
    }
    //In Objective-C you'd perform the swizzling in load(),
    //but this method is not permitted in Swift
    func swizzle(){
        let i: () -> () = {
            let originalSelector = #selector(TestSwizzling.methodOne)
            let swizzledSelector = #selector(TestSwizzling.methodTwo)
            let originalMethod = class_getInstanceMethod(TestSwizzling.self, originalSelector);
            let swizzledMethod = class_getInstanceMethod(TestSwizzling.self, swizzledSelector)
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
            print("swizzled!")
        }
        i()
    }
}

var c = TestSwizzling()
print([c.methodOne(), c.methodTwo()])  // [1, 2]
c.swizzle()                            // swizzled!
print([c.methodOne(), c.methodTwo()])  // [2, 1]
</code>```

Body:
How can I implement method swizzling in Swift 3.0 ?

I've read nshipster article about it, but in this code's chunk

struct Static {
    static var token: dispatch_once_t = 0
}

the compiler gives me an error

dispatch_once_t is unavailable in Swift: Use lazily initialized
  globals instead

Body:
Swizzling in Playground

Swift 5

import Foundation
class TestSwizzling : NSObject {
    @objc dynamic func methodOne()->Int{
        return 1
    }
}

extension TestSwizzling {
    @objc func methodTwo()->Int{
        // It will not be a recursive call anymore after the swizzling
        return 2
    }
    //In Objective-C you'd perform the swizzling in load(),
    //but this method is not permitted in Swift
    func swizzle(){
        let i: () -> () = {
            let originalSelector = #selector(TestSwizzling.methodOne)
            let swizzledSelector = #selector(TestSwizzling.methodTwo)
            let originalMethod = class_getInstanceMethod(TestSwizzling.self, originalSelector);
            let swizzledMethod = class_getInstanceMethod(TestSwizzling.self, swizzledSelector)
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
            print("swizzled!")
        }
        i()
    }
}

var c = TestSwizzling()
print([c.methodOne(), c.methodTwo()])  // [1, 2]
c.swizzle()                            // swizzled!
print([c.methodOne(), c.methodTwo()])  // [2, 1]


问:
How can I write bash script that returns line from file which starts from the begining untill specific symbol?
I have simple file:

```<code>line1(sometext)
line222(other_text)
line333(other text)
</code>```

I pass to script in arguments part of word before symbol "("
How can I chech using grep command if this line exists ?
for example I pass in arguments word line222  - it returns line222(other_text)

but it I pass "line2" - it says that line was not found
Right now I have this code, that gives wrong result if I type one symbol

```<code>if ! grep home "myfile.txt" | grep -- "$1"; then
   echo "Line doesn't exist"
fi
</code>```

答:
You can verify whether the certain line exists or doesn't exist in your file as follows:

```<code>if [[ $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" exists"
else
    echo "Line starts with \"${1}\" doesn't exist"
fi
</code>```

or if you just want print the output info when it doesn't exist, then this may help:

```<code>if [[ ! $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" doesn't exist"
fi
</code>```

grep "^${1}" searches for the text pattern, ^${1} means starting with the variable that you pass to your script. [[ ... ]] tests the condition (bash way) and ! sign negates the test condition.

Body:
I have simple file:

line1(sometext)
line222(other_text)
line333(other text)

I pass to script in arguments part of word before symbol "("
How can I chech using grep command if this line exists ?
for example I pass in arguments word line222  - it returns line222(other_text)

but it I pass "line2" - it says that line was not found
Right now I have this code, that gives wrong result if I type one symbol

if ! grep home "myfile.txt" | grep -- "$1"; then
   echo "Line doesn't exist"
fi

Body:
You can verify whether the certain line exists or doesn't exist in your file as follows:

if [[ $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" exists"
else
    echo "Line starts with \"${1}\" doesn't exist"
fi

or if you just want print the output info when it doesn't exist, then this may help:

if [[ ! $(grep "^${1}" "myfile.txt") ]]; then
    echo "Line starts with \"${1}\" doesn't exist"
fi

grep "^${1}" searches for the text pattern, ^${1} means starting with the variable that you pass to your script. [[ ... ]] tests the condition (bash way) and ! sign negates the test condition.


问:
Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7
In Eclipse Juno, I installed the latest m2e plugin (1.2.20120903-1050).  In preferences, I have added jdk1.7.0_11 in Java -> Installed JREs -> Add, and then specified the location (C:\Program Files\Java\jdk1.7.0_11).  When I create a new Maven project and run it, I get a warning:

Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.

I am not sure how to resolve this.

I believe it is a Maven problem because I do not have this error when I run normal Java projects.  I read here that I should change the "maven-compiler-plugin.pom" and change the source and target from 1.5 to something more appropriate.  In my case, 1.7.  I have done this, but I still get the warning.

答:
I got an error in Eclipse Mars version as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.

To resolve this issue, please do the following steps,
"Right click on Project
Choose Build path
Choose Configure Build path
Choose Libraries tab
Select JRE System Library and click on Edit button
Choose workspace default JRE and Finish

Problem will be resolved.


问:
Print available disk space and send email notification
I have a playbook to check the hard drive free space and send email if the threshold limit is reached. Following is my play

```<code>---
- hosts: Test
  tasks:
    - name: Ensuring that free space on '/' is grater than 30%
      assert:
    that:
          - not {{ item.mount == '/' and ( item.size_available < item.size_total - ( item.size_total|float * 0.3 ) ) }}
      with_items: '{{ ansible_mounts }}'
      ignore_errors: yes
      register: disk_free
    -  debug: var=disk_free

    - name: Notifying the IT admin about the disk usage
      mail:
    host="smtp.myserver.com"
        port="2525"
        username="my_username"
        password="my_password"
        from="my_email"
        to="to_email"
        subject='HDD Space Low'
        body='{{ inventory_hostname }} is running low on disk space. Currently {{ disk_free.results['item']['size_available'] }}MB available.'
</code>```

Following is the debug output I receive when i run the above play:

```<code>ok: [Test] => {
    "disk_free": {
        "changed": false,
        "failed": true,
        "msg": "One or more items failed",
        "results": [
            {
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_verbose_always": true,
                "assertion": "not True",
                "evaluated_to": false,
                "failed": true,
                "item": {
                    "device": "/dev/mapper/centos-root",
                    "fstype": "xfs",
                    "mount": "/",
                    "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                    "size_available": 18377105408,
                    "size_total": 19828572160,
                    "uuid": "d700725b-6937-4e56-8e20-2039e787f055"
                }
</code>```

Now, when I access the result veriable within the notification email body, it fails.

FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute

So can somebody please help me to print the 'size_available' value within the outgoing email?

答:
You get:

'list object' has no attribute

If you look at the result of your debug task, you'll notice disk_free.results is a list (because you used a loop when registering), so it does not contain item.

For a single value you might refer to disk_free.results[0]['item']['size_available'], but I guess you should iterate over the list.

Body:
I have a playbook to check the hard drive free space and send email if the threshold limit is reached. Following is my play

---
- hosts: Test
  tasks:
    - name: Ensuring that free space on '/' is grater than 30%
      assert:
    that:
          - not {{ item.mount == '/' and ( item.size_available < item.size_total - ( item.size_total|float * 0.3 ) ) }}
      with_items: '{{ ansible_mounts }}'
      ignore_errors: yes
      register: disk_free
    -  debug: var=disk_free

    - name: Notifying the IT admin about the disk usage
      mail:
    host="smtp.myserver.com"
        port="2525"
        username="my_username"
        password="my_password"
        from="my_email"
        to="to_email"
        subject='HDD Space Low'
        body='{{ inventory_hostname }} is running low on disk space. Currently {{ disk_free.results['item']['size_available'] }}MB available.'

Following is the debug output I receive when i run the above play:

ok: [Test] => {
    "disk_free": {
        "changed": false,
        "failed": true,
        "msg": "One or more items failed",
        "results": [
            {
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_verbose_always": true,
                "assertion": "not True",
                "evaluated_to": false,
                "failed": true,
                "item": {
                    "device": "/dev/mapper/centos-root",
                    "fstype": "xfs",
                    "mount": "/",
                    "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                    "size_available": 18377105408,
                    "size_total": 19828572160,
                    "uuid": "d700725b-6937-4e56-8e20-2039e787f055"
                }

Now, when I access the result veriable within the notification email body, it fails.

FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute

So can somebody please help me to print the 'size_available' value within the outgoing email?


问:
Two Rectangles intersection
I have two rectangles characterized by 4 values each :

Left position X, top position Y, width W and height H:

```<code>X1, Y1, H1, W1
X2, Y2, H2, W2
</code>```

Rectangles are not rotated, like so:

```<code>+--------------------> X axis
|
|    (X,Y)      (X+W, Y)
|    +--------------+
|    |              |
|    |              |
|    |              |
|    +--------------+
v    (X, Y+H)     (X+W,Y+H)

Y axis
</code>```

What is the best solution to determine whether the intersection of the two rectangles is empty or not?

答:
Should the two rectangles have the same dimensions you can do:</p>

```<code>if (abs (x1 - x2) < w && abs (y1 - y2) < h) {
    // overlaps
}
</code>```

Title: Two Rectangles intersection

Body:
I have two rectangles characterized by 4 values each :

Left position X, top position Y, width W and height H:

X1, Y1, H1, W1
X2, Y2, H2, W2

Rectangles are not rotated, like so:

+--------------------> X axis
|
|    (X,Y)      (X+W, Y)
|    +--------------+
|    |              |
|    |              |
|    |              |
|    +--------------+
v    (X, Y+H)     (X+W,Y+H)

Y axis

What is the best solution to determine whether the intersection of the two rectangles is empty or not?

Body:
Should the two rectangles have the same dimensions you can do:

if (abs (x1 - x2) < w && abs (y1 - y2) < h) {
    // overlaps
}


问:
VB6 Manifest not working on Windows 7
I have created a manifest file for a VB6 application that is running on Windows 7 (not for any visual style changes, just to make sure it accesses the common registry and not a virtualised one)

The exe name is Capadm40.exe, the manifest is named Capadm40.exe.manifest and contains the following:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="CompanyName.Capadm40"
     type="win32"/>
  <description>Administers the System</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>
</code>```

However, this doesn't seem to make any difference. ie the application is still using the virtualised registry hive. What is also strange is the after I unticked the 'Run this program as an administrator' option in the properties of the application exe, windows still shows a shield on the application icon, leading my to think this is some issue with my windows installation rather than a fault with the manifest. Any ideas?

答: I would take advantage of LaVolpe's manifest creator, works great for XP, Vista and 7: http://www.vbforums.com/showthread.php?t=606736</p>

Title: VB6 Manifest not working on Windows 7

Body:
I have created a manifest file for a VB6 application that is running on Windows 7 (not for any visual style changes, just to make sure it accesses the common registry and not a virtualised one)

The exe name is Capadm40.exe, the manifest is named Capadm40.exe.manifest and contains the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="CompanyName.Capadm40"
     type="win32"/>
  <description>Administers the System</description>

  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

However, this doesn't seem to make any difference. ie the application is still using the virtualised registry hive. What is also strange is the after I unticked the 'Run this program as an administrator' option in the properties of the application exe, windows still shows a shield on the application icon, leading my to think this is some issue with my windows installation rather than a fault with the manifest. Any ideas?


问:
How to spawn a Erlang process dynamically for one activity and kill it once activity done
There are many parallel requests coming to one erlang OTP (gen_server) process.
One process is not sufficient to handle this.
I can have fix number pool of same processes to handle this using Poolboy or worker_pool.

But I dont want to have fix set of process pool.
I want to create dynamically Process to handle that activity and get killed once it done its work.

So I will be having N numbers of active process for N parallel request.
and than it get killed once that process complete the processing.

How I can achieve this?

答:
Use Erlang supervisor module and use transient in its flags.

When your event comes, start new child for doing that and when event done, exit process with reason 'normal'.

Supervisor behavior info: Design   -    API


问:
Can't get ApiGateway Lambda:InvokeFunction permissions working in CloudFormation
I'm trying to set up a CloudFormation template that will create a lambda function and an APIGateway that can access it. However, despite setting up the Lambda:InvokeFunction permission as shown below (and trying every permutation under the sun as recommended on other SO questions), I get the message Execution failed due to configuration error: Invalid permissions on Lambda function.

The only way I can get it to work is if I go into the AWS console and manually un-set and re-set the APIGateway's destination to the lambda.

I've also tried the CLI to no effect:

```<code>aws lambda add-permission --function-name $updatedFunction.FunctionName --statement-id "AllowExecutionFromAPIGateway" --action "lambda:InvokeFunction" --principal "apigateway.amazonaws.com" --source-arn $api.StackId
</code>```

Does anyone have any insight into why these permissions wouldn't work?

```<code>...
"Get":{
     "Type":"AWS::Lambda::Function",
     "Properties":{
        "Code":{
           "S3Bucket":"webapistack-bucket-org0oolyde9v",
           "S3Key":"webapi/webapistack-636349410359047808.zip"
        },
        "Tags":[
           {
              "Value":"SAM",
              "Key":"lambda:createdBy"
           }
        ],
        "MemorySize":256,
        "Environment":{
           "Variables":{
              "AppS3Bucket":{
                 "Fn::If":[
                    "CreateS3Bucket",
                    {
                       "Ref":"Bucket"
                    },
                    {
                       "Ref":"BucketName"
                    }
                 ]
              }
           }
        },
        "Handler":"webapi::webapi.LambdaEntryPoint::FunctionHandlerAsync",
        "Role":{
           "Fn::GetAtt":[
              "GetRole",
              "Arn"
           ]
        },
        "Timeout":30,
        "Runtime":"dotnetcore1.0"
     }
},
"GetPutResourcePermissionTest":{
  "Type":"AWS::Lambda::Permission",
  "Properties":{
     "Action":"lambda:invokeFunction",
     "Principal":"apigateway.amazonaws.com",
     "FunctionName":{
        "Ref":"Get"
     },
     "SourceArn":{
        "Fn::Sub":[
           "arn:aws:execute-api:WS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/ANY/*",
           {
              "__Stage__":"*",
              "__ApiId__":{
                 "Ref":"ServerlessRestApi"
              }
           }
        ]
     }
  }
},
...
"ServerlessRestApi":{
   "Type":"AWS::ApiGateway::RestApi",
   "Properties":{
      "Body":{
         "info":{
            "version":"1.0",
            "title":{
               "Ref":"AWS::StackName"
            }
         },
         "paths":{
            "/{proxy+}":{
               "x-amazon-apigateway-any-method":{
                  "x-amazon-apigateway-integration":{
                     "httpMethod":"POST",
                     "type":"aws_proxy",
                     "uri":{
               "Fn::Sub":"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Get.Arn}/invocations"
                       }
                    },
                    "responses":{

                    }
                 }
              }
           },
           "swagger":"2.0"
        }
     }
  }
</code>```

答:
Your AWS::Lambda::Permission seems to be incorrect.

The FunctionName you are referencing is the logical ID, the spec, however, requires the physical ID or ARN.

The SourceArn pattern of the Sub is missing some characters on the Region replacement.

Since I'm not sure whether the "ANY"-operation is valid for the ARN, I would replace it with "*", just to be sure.

Here a changed version of the permission:

```<code>"GetPutResourcePermissionTest":{
  "Type":"AWS::Lambda::Permission",
  "Properties":{
     "Action":"lambda:invokeFunction",
     "Principal":"apigateway.amazonaws.com",
     "FunctionName":{
        "Fn::GetAtt": [ "Get" , "Arn" ]
     },
     "SourceArn":{
        "Fn::Sub":[
           "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/*/*",
           {
              "__Stage__":"*",
              "__ApiId__":{
                 "Ref":"ServerlessRestApi"
              }
           }
        ]
     }
  }
},
</code>```

Body:
I'm trying to set up a CloudFormation template that will create a lambda function and an APIGateway that can access it. However, despite setting up the Lambda:InvokeFunction permission as shown below (and trying every permutation under the sun as recommended on other SO questions), I get the message Execution failed due to configuration error: Invalid permissions on Lambda function.

The only way I can get it to work is if I go into the AWS console and manually un-set and re-set the APIGateway's destination to the lambda.

I've also tried the CLI to no effect:

aws lambda add-permission --function-name $updatedFunction.FunctionName --statement-id "AllowExecutionFromAPIGateway" --action "lambda:InvokeFunction" --principal "apigateway.amazonaws.com" --source-arn $api.StackId

Does anyone have any insight into why these permissions wouldn't work?

...
"Get":{
     "Type":"AWS::Lambda::Function",
     "Properties":{
        "Code":{
           "S3Bucket":"webapistack-bucket-org0oolyde9v",
           "S3Key":"webapi/webapistack-636349410359047808.zip"
        },
        "Tags":[
           {
              "Value":"SAM",
              "Key":"lambda:createdBy"
           }
        ],
        "MemorySize":256,
        "Environment":{
           "Variables":{
              "AppS3Bucket":{
                 "Fn::If":[
                    "CreateS3Bucket",
                    {
                       "Ref":"Bucket"
                    },
                    {
                       "Ref":"BucketName"
                    }
                 ]
              }
           }
        },
        "Handler":"webapi::webapi.LambdaEntryPoint::FunctionHandlerAsync",
        "Role":{
           "Fn::GetAtt":[
              "GetRole",
              "Arn"
           ]
        },
        "Timeout":30,
        "Runtime":"dotnetcore1.0"
     }
},
"GetPutResourcePermissionTest":{
  "Type":"AWS::Lambda::Permission",
  "Properties":{
     "Action":"lambda:invokeFunction",
     "Principal":"apigateway.amazonaws.com",
     "FunctionName":{
        "Ref":"Get"
     },
     "SourceArn":{
        "Fn::Sub":[
           "arn:aws:execute-api:WS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/ANY/*",
           {
              "__Stage__":"*",
              "__ApiId__":{
                 "Ref":"ServerlessRestApi"
              }
           }
        ]
     }
  }
},
...
"ServerlessRestApi":{
   "Type":"AWS::ApiGateway::RestApi",
   "Properties":{
      "Body":{
         "info":{
            "version":"1.0",
            "title":{
               "Ref":"AWS::StackName"
            }
         },
         "paths":{
            "/{proxy+}":{
               "x-amazon-apigateway-any-method":{
                  "x-amazon-apigateway-integration":{
                     "httpMethod":"POST",
                     "type":"aws_proxy",
                     "uri":{
               "Fn::Sub":"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Get.Arn}/invocations"
                       }
                    },
                    "responses":{

                    }
                 }
              }
           },
           "swagger":"2.0"
        }
     }
  }

Body:
Your AWS::Lambda::Permission seems to be incorrect.

The FunctionName you are referencing is the logical ID, the spec, however, requires the physical ID or ARN.

The SourceArn pattern of the Sub is missing some characters on the Region replacement.

Since I'm not sure whether the "ANY"-operation is valid for the ARN, I would replace it with "*", just to be sure.

Here a changed version of the permission:

"GetPutResourcePermissionTest":{
  "Type":"AWS::Lambda::Permission",
  "Properties":{
     "Action":"lambda:invokeFunction",
     "Principal":"apigateway.amazonaws.com",
     "FunctionName":{
        "Fn::GetAtt": [ "Get" , "Arn" ]
     },
     "SourceArn":{
        "Fn::Sub":[
           "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/*/*",
           {
              "__Stage__":"*",
              "__ApiId__":{
                 "Ref":"ServerlessRestApi"
              }
           }
        ]
     }
  }
},


问:
Error12 'Membership' is an ambiguous reference between 'System.Web.Security.Membership' and 'testSiteV1.Model.Membership'
I modified a data type from int to float, then, I updated model->edms file by select the 'update model from database'.

It successfully updated but turns out with an error:Error   12  'Membership' is an ambiguous reference between 'System.Web.Security.Membership' and 'testSiteV1.Model.Membership'.

May anyone helps me with this problem?

By the way, there is another warning says: Warning  5   The variable 'e' is declared but never used

答:
You have class Membership in your model and also include the namespace System.Web.Security, which contains a class called Membership.

Hence the error:

'Membership' is an ambiguous reference between 'System.Web.Security.Membership' and 'testSiteV1.Model.Membership'.

Remove the using System.Web.Security; statement if you don't need it or qualify the class usage by using the full name, i.e. testSiteV1.Model.Membership or System.Web.Security.Membership.

I can't tell you more because you don't show your code.


问:
OpsHub Unable to set Source EndPoint to TFS2015 with error TF31002
I am trying to use OpsHub Visual Studio Migration Utility (Free Version) to migrate the Work Items in TFS2015 (Version 14.102.25423.0) to VSTS.
When I set the TFS server URL as Source EndPoint, I got the TF31002 error as shown in the following screenshot:
TF31002 Error when setting the Source EndPoint to a TFS2015 Server

I am able to connect to the TFS Server via all of my browsers and Visual Studio (2015/2017).

I tried some solutions like:
 - clearing IE cache/cookies
 - clearing TFS cache
 - delete Visual Studio TokenManager folder on registy

Thanks in advance for any provided solution.

My machine is behind a proxy et here are the configuration in settings.properties:

```<code>action=update
installationLocation=C:\\Program Files\\OpsHub Visual Studio Migration Utility
httpHostName=my_proxy_ip_address
httpPort=8080
httpUsername=my_company_username
httpPassword=my_password
httpNonProxyHosts=localhost|127.0.0.1

useSameParametersForHTTPS=true

httpsHostName=
httpsPort=
httpsUsername=
httpsPassword=
httpsNonProxyHosts=localhost|127.0.0.1
</code>```

答:
It seems that you'll have to enable two of the OVSMU's processes to utilize the proxy configuration as done in the _JAVA_OPTIONS environment variable.

C:\Program Files\OpsHub Visual Studio Migration Utility\Other_Resources\Resources\TFSUtility\ovsmu.exe.config

C:\Program Files\OpsHub Visual Studio Migration Utility\Other_Resources\Resources\TFSUtility\TFSService\opshubtfsservice.exe.config

Open each of the above mentioned configuration file in a text editor (as an Admin) and un-comment the following XML node structure.

```<code><!-- <system.net>
    <defaultProxy enabled="true" useDefaultCredentials="false">
      <module type="com.opshub.tfs.test.Proxy, opshubtfsservice" />
    </defaultProxy>
  </system.net> -->
</code>```

Remove the comments and restart the tool, you should be able to connect to the end points then.

Body:
I am trying to use OpsHub Visual Studio Migration Utility (Free Version) to migrate the Work Items in TFS2015 (Version 14.102.25423.0) to VSTS.
When I set the TFS server URL as Source EndPoint, I got the TF31002 error as shown in the following screenshot:
TF31002 Error when setting the Source EndPoint to a TFS2015 Server

I am able to connect to the TFS Server via all of my browsers and Visual Studio (2015/2017).

I tried some solutions like:
 - clearing IE cache/cookies
 - clearing TFS cache
 - delete Visual Studio TokenManager folder on registy

Thanks in advance for any provided solution.

My machine is behind a proxy et here are the configuration in settings.properties:

action=update
installationLocation=C:\\Program Files\\OpsHub Visual Studio Migration Utility
httpHostName=my_proxy_ip_address
httpPort=8080
httpUsername=my_company_username
httpPassword=my_password
httpNonProxyHosts=localhost|127.0.0.1

useSameParametersForHTTPS=true

httpsHostName=
httpsPort=
httpsUsername=
httpsPassword=
httpsNonProxyHosts=localhost|127.0.0.1

Body:
It seems that you'll have to enable two of the OVSMU's processes to utilize the proxy configuration as done in the _JAVA_OPTIONS environment variable.

C:\Program Files\OpsHub Visual Studio Migration Utility\Other_Resources\Resources\TFSUtility\ovsmu.exe.config

C:\Program Files\OpsHub Visual Studio Migration Utility\Other_Resources\Resources\TFSUtility\TFSService\opshubtfsservice.exe.config

Open each of the above mentioned configuration file in a text editor (as an Admin) and un-comment the following XML node structure.

<!-- <system.net>
    <defaultProxy enabled="true" useDefaultCredentials="false">
      <module type="com.opshub.tfs.test.Proxy, opshubtfsservice" />
    </defaultProxy>
  </system.net> -->

Remove the comments and restart the tool, you should be able to connect to the end points then.


问:
Dynamically setting CSS values using ASP.NET
I'm working on a site where the images and other resources will be located on a separate domain from the main content of the site. We will use something like 'www.example.com' for the main site, and then 'images.example.com' for all extra resources for styles, etc.

When developing the site I will keep all of these resources on local dev. machines. The challenge here is keeping CSS references consistent between the production server and development environments.

What I was thinking of doing was creating a web.config key that would store the URL of the images server. Then, when switching from development to production I could just change the web.config value and everything would be done.

Is there any way to add a value to a CSS file, dynamically or otherwise, from some place in a config or C# class? Or am I going about this the wrong way?

Also, I'm limited to using .NET 2.0 if that makes a difference.

UPDATE

To expand on this a little more, I know I can use a web.config setting for server controls' URLs. Those are already generated dynamically. What I'm more interested in is what options I have for modifying (or doing "something") to static CSS files that will allow me to change URLs for things such as background image resources that would be referenced in CSS. Is there anything I can do besides find/replacing the values using my IDE? Perhaps something that can be done automatically with a deployment script?

答:
What about putting a place holder on the web page and then selecting which CSS file to utilize (PROD, TEST, etc.) at run time and add it to the place hodler?

I think that Update had the right idea...

```<code><link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />
</code>```

OwnerDisplayName: DanHerbert

LastEditorDisplayName: DanHerbert

Body:
What about putting a place holder on the web page and then selecting which CSS file to utilize (PROD, TEST, etc.) at run time and add it to the place hodler?

I think that Update had the right idea...

<link rel="stylesheet" href="<%= ConfigurationManager.AppSettings("css-server") %>style.css" />

OwnerDisplayName: Russell Solberg


问:
In IE6, and using divs, how to split entire page into two columns, left div with static width and right with elastic width?
I don't know if what am asking for is even possible in IE6, but here goes:  I am working on a page layout and want to split the body into two container divs. I want to give the left div a fixed width of 200px; while making the right div elastic along the page's width.  The right div's left border must be touching the left div's right border to make things clearer i made a diagram:

答:
Example on jsfiddle: http://jsfiddle.net/Damien_at_SF/UhdHu/

HTML:

```<code><html>
    <body>
        <div id="col_1">
            <p>column 1</p>
        </div>
        <div id="col_2">
            <p>column 2</p>
        </div>
    </body>
</html>
</code>```

CSS:

```<code>html, body {
     height:100%;
     margin:0;
     padding:0;
     background-color:#000000;
}
#col_1 {
     height:100%;
     position:absolute;
     top:0px;
     left:0px;
     width:200px;
     padding:10px;
     background-color:#DBDBDB;
}
#col_2 {
     height:100%;
     margin-top:0px;
     margin-right:0px;
     margin-left:220px;
     padding:10px;
     background-color:#FFFFFF;
     overflow:hidden;
}
</code>```

sourced from: http://css.flepstudio.org/en/css-box-model/1-column-fixed-1-column-fluid.html

hope that helps :)

Body:
Example on jsfiddle: http://jsfiddle.net/Damien_at_SF/UhdHu/

HTML:

<html>
    <body>
        <div id="col_1">
            <p>column 1</p>
        </div>
        <div id="col_2">
            <p>column 2</p>
        </div>
    </body>
</html>

CSS:

html, body {
     height:100%;
     margin:0;
     padding:0;
     background-color:#000000;
}
#col_1 {
     height:100%;
     position:absolute;
     top:0px;
     left:0px;
     width:200px;
     padding:10px;
     background-color:#DBDBDB;
}
#col_2 {
     height:100%;
     margin-top:0px;
     margin-right:0px;
     margin-left:220px;
     padding:10px;
     background-color:#FFFFFF;
     overflow:hidden;
}

sourced from: http://css.flepstudio.org/en/css-box-model/1-column-fixed-1-column-fluid.html

hope that helps :)


问:
org.glassfish.json.JsonStringImpl cannot be cast to javax.json.JsonArray
I have this piece of code:

```<code>JsonObject fg = null;
try{
      fg =  message.getJson();  //gettng the JSON object from the client
      System.out.println("JSONGOBJECT IS HERE:   "+fg);

      JsonArray arr1 =  fg.getJsonArray("to");  //I get the exception here
      int size =  arr1.length();
      arrays = new ArrayList<String>();
      for(Object o : arr1)
      {
        String user=(o == null ? null : o.toString());
           if (user != null) {
                 arrays.add(user);
           }
       }
       catch(Exception e)
       {
           System.out.println("Exeption HERE: "+e);
       }
</code>```

I get this exception while I try to access value for "to" parameter from JsonArray. I am not using org.glassfish.json library anywhere. Have not imported it either.

I have imported only javax.json  in my current code. How do I fix this ?

答:
The error occurred because you tried to convert number into string.

This will work for sure.

```<code>for (int i = 0; i < jsonArray.size(); i++)
jsonArray.getJsonObject(i).get(key).toString();
</code>```

Get object in a generic way.

Body:
I have this piece of code:

JsonObject fg = null;
try{
      fg =  message.getJson();  //gettng the JSON object from the client
      System.out.println("JSONGOBJECT IS HERE:   "+fg);

      JsonArray arr1 =  fg.getJsonArray("to");  //I get the exception here
      int size =  arr1.length();
      arrays = new ArrayList<String>();
      for(Object o : arr1)
      {
        String user=(o == null ? null : o.toString());
           if (user != null) {
                 arrays.add(user);
           }
       }
       catch(Exception e)
       {
           System.out.println("Exeption HERE: "+e);
       }

I get this exception while I try to access value for "to" parameter from JsonArray. I am not using org.glassfish.json library anywhere. Have not imported it either.

I have imported only javax.json  in my current code. How do I fix this ?

Body:
The error occurred because you tried to convert number into string.

This will work for sure.

for (int i = 0; i < jsonArray.size(); i++)
jsonArray.getJsonObject(i).get(key).toString();

Get object in a generic way.


问:
Synchronous Call in WSO2 ESB in iterator mediator
Is there any way to make synchronous call of all the codes written inside the iterator mediator in esb wso2?</p>

答:
Finally, it is working by doing two things together.
Set sequential="true" in iterator and in call mediator use  blocking = "true"</p>


问:
Using "View As" device other than active device results in layout issues
This one is best demonstrated with a video. The layout of my view changes based on which device I "View As: " in Interface Builder. It looks like changing this setting modifies the rects in Interface Builder, and then those changes stick. Is there a better way to prevent this from happening?

(It doesn't matter which device I use. If "View As" doesn't match the device, something will appear off.)

答:
I figured this one out. It was a missing constraint. I was adding my view to a page view controller, but forgot to constraint the child view in the process:

```<code>marqueeViewController.addChildViewController(pageViewController)
marqueeViewController.containerView.addSubview(pageViewController.view)
// ** This constraint was missing, and is needed to resize the child view. **
Layout.edges(parent: marqueeViewController.containerView, child: pageViewController.view)
</code>```

The rectangle of my views were changing size as I changed the "View As:" setting in Interface Builder. And since there was no constraint to reel them back in, they stayed set at the different size.

Body:
I figured this one out. It was a missing constraint. I was adding my view to a page view controller, but forgot to constraint the child view in the process:

marqueeViewController.addChildViewController(pageViewController)
marqueeViewController.containerView.addSubview(pageViewController.view)
// ** This constraint was missing, and is needed to resize the child view. **
Layout.edges(parent: marqueeViewController.containerView, child: pageViewController.view)

The rectangle of my views were changing size as I changed the "View As:" setting in Interface Builder. And since there was no constraint to reel them back in, they stayed set at the different size.