问:
pip install flask on windows bash not working
I'm trying to pip install flask with bash on Ubuntu on windows 10, but it's not working. I have pip installed, and am running Python 3.5. A copy of the command line and exception error is below. Any help will be greatly appreciated!

```<code>scot@SCOTTS_PC:~$ cd Project
bash: cd: Project: No such file or directory
scot@SCOTTS_PC:~$ cd Projects
scot@SCOTTS_PC:~/Projects$ cd py
scot@SCOTTS_PC:~/Projects/py$ cd myflaskapp
scot@SCOTTS_PC:~/Projects/py/myflaskapp$ pip install flask
Downloading/unpacking flask
  Downloading Flask-0.12.2-py2.py3-none-any.whl (83kB): 83kB downloaded
Downloading/unpacking itsdangerous>=0.21 (from flask)
  Downloading itsdangerous-0.24.tar.gz (46kB): 46kB downloaded
  Running setup.py (path:/tmp/pip_build_scot/itsdangerous/setup.py) egg_info for package itsdangerous

    warning: no previously-included files matching '*' found under directory 'docs/_build'
Downloading/unpacking Werkzeug>=0.7 (from flask)
  Downloading Werkzeug-0.12.2-py2.py3-none-any.whl (312kB): 312kB downloaded
Downloading/unpacking Jinja2>=2.4 (from flask)
  Downloading Jinja2-2.9.6-py2.py3-none-any.whl (340kB): 340kB downloaded
Downloading/unpacking click>=2.0 (from flask)
  Downloading click-6.7-py2.py3-none-any.whl (71kB): 71kB downloaded
Downloading/unpacking MarkupSafe>=0.23 (from Jinja2>=2.4->flask)
  Downloading MarkupSafe-1.0.tar.gz
  Running setup.py (path:/tmp/pip_build_scot/MarkupSafe/setup.py) egg_info for package MarkupSafe

Installing collected packages: flask, itsdangerous, Werkzeug, Jinja2, click, MarkupSafe
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/Flask-0.12.2.dist-info'

Storing debug log for failure in /home/scot/.pip/pip.log
</code>```

update to clarify setup

答: can you prefix with sudo? so sudo pip install flask? or if you on windows can you open the bash prompt with admin rights?

Body:
I'm trying to pip install flask with bash on Ubuntu on windows 10, but it's not working. I have pip installed, and am running Python 3.5. A copy of the command line and exception error is below. Any help will be greatly appreciated!

scot@SCOTTS_PC:~$ cd Project
bash: cd: Project: No such file or directory
scot@SCOTTS_PC:~$ cd Projects
scot@SCOTTS_PC:~/Projects$ cd py
scot@SCOTTS_PC:~/Projects/py$ cd myflaskapp
scot@SCOTTS_PC:~/Projects/py/myflaskapp$ pip install flask
Downloading/unpacking flask
  Downloading Flask-0.12.2-py2.py3-none-any.whl (83kB): 83kB downloaded
Downloading/unpacking itsdangerous>=0.21 (from flask)
  Downloading itsdangerous-0.24.tar.gz (46kB): 46kB downloaded
  Running setup.py (path:/tmp/pip_build_scot/itsdangerous/setup.py) egg_info for package itsdangerous

    warning: no previously-included files matching '*' found under directory 'docs/_build'
Downloading/unpacking Werkzeug>=0.7 (from flask)
  Downloading Werkzeug-0.12.2-py2.py3-none-any.whl (312kB): 312kB downloaded
Downloading/unpacking Jinja2>=2.4 (from flask)
  Downloading Jinja2-2.9.6-py2.py3-none-any.whl (340kB): 340kB downloaded
Downloading/unpacking click>=2.0 (from flask)
  Downloading click-6.7-py2.py3-none-any.whl (71kB): 71kB downloaded
Downloading/unpacking MarkupSafe>=0.23 (from Jinja2>=2.4->flask)
  Downloading MarkupSafe-1.0.tar.gz
  Running setup.py (path:/tmp/pip_build_scot/MarkupSafe/setup.py) egg_info for package MarkupSafe

Installing collected packages: flask, itsdangerous, Werkzeug, Jinja2, click, MarkupSafe
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/Flask-0.12.2.dist-info'

Storing debug log for failure in /home/scot/.pip/pip.log

update to clarify setup


来源: stackexchange

问:
How can I change the way GRAILS GSP fieldValue formats Integers?
I have a field in my domain object which I define as an Integer...

```<code>Integer minPrice
</code>```

I then access it in a GSP page as follows:

```<code>${fieldValue(bean: myBean, field: 'minPrice')}
</code>```

and what I get in my HTML is...

```<code>100,000
</code>```

which is not an Integer, it's a String.  Worse still it's a formatted String in a particular locale.

This is a problem because I have a SELECT control on an HTML FORM which has a (non-ordinal) range of values for minPrice which I want to store in my domain object as integers, and I don't want to store an index to some array of values that I have to repeatedly map back and forth between, I want the value itself.

My select control looks like this...

```<code><g:select name="minPrice"
value="${fieldValue(bean: personInstance, field: 'minPrice')}"
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
    ['name':'100,000', 'id':100000],
    ['name':'200,000', 'id':200000],
    ['name':'300,000', 'id':300000]
    ]}"
optionKey="id" optionValue="name"
/>
</code>```

When I get the value from the SELECT field to post back to the server it correctly has an Integer value, which I persist.  However the return trip never pre-selects the right row in the drop-down because the value is this comma separated String.

This works fine elsewhere in my code for small numbers where the comma formatting doesn't come into play, and the round-trip in and out of the SELECT is successful.  But values >999 don't work.

The docs say "This tag will inspect a bean which has been the subject of data binding and obtain the value of the field either from the originally submitted value contained within the bean's errors object populating during data binding or from the value of a bean's property. Once the value is obtained it will be automatically HTML encoded."

It's that last bit that I want to avoid as it appears to format Integers.  So, what little bit of Grails/GSP magic do I need to know so I can get my Integer to be rendered as an integer into my SELECT and pre-select the right row?

EDIT:
I have tried some further things based on the answers below, with pretty disappointing results so far...

If I put the <gformatNumber/> tag in my <g:select/> I get the page code as text in the browser.

```<code><g:select name="minPrice"
value='<g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />'
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
['name':'100,000', 'id':100000],
['name':'200,000', 'id':200000],
['name':'300,000', 'id':300000],
]}"
optionKey="id" optionValue="name"
/>
</code>```

Using the number format tag from GSP on my Integer value of 100000 like this...

```<code>var x = <g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />;
</code>```

gives 100.  Remember that the fieldValue gives back 100,000, so this is not a surprise.

If I use the jsp taglib like this...

```<code><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
var y = <fmt:formatNumber value="${fieldValue(bean: personInstance, field: 'minPrice')}" pattern=".00"/>;
</code>```

I get an error from the page compiler Cannot format given Object as a Number.

I guess I have a wider concern than I can't seem to get an Integer value as a genuine integer into my code if it is greater than 999 because of the default (and unconfigurable) behaviour of the fieldValue directive.  However my specific problem of not being able to pre-select an Integer value in a SELECT control is not going away.  At the moment I'm at a bit of a loss.

Anyone have any further ideas?

答:
Better use custom PropertyEditor in order not to bother with formatNumber tag every time you output a value.
Like, declare a bean in resources.groovy:

```<code>myOwnCustomEditorRegistrar(CustomEditorRegistrar)
</code>```

And create your class:

```<code>class CustomEditorRegistrar implements PropertyEditorRegistrar {
    void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(BigDecimal.class, new MyBigDecimalEditor(BigDecimal.class))
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a field in my domain object which I define as an Integer...

Integer minPrice

I then access it in a GSP page as follows:

${fieldValue(bean: myBean, field: 'minPrice')}

and what I get in my HTML is...

100,000

which is not an Integer, it's a String.  Worse still it's a formatted String in a particular locale.

This is a problem because I have a SELECT control on an HTML FORM which has a (non-ordinal) range of values for minPrice which I want to store in my domain object as integers, and I don't want to store an index to some array of values that I have to repeatedly map back and forth between, I want the value itself.

My select control looks like this...

<g:select name="minPrice"
value="${fieldValue(bean: personInstance, field: 'minPrice')}"
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
    ['name':'100,000', 'id':100000],
    ['name':'200,000', 'id':200000],
    ['name':'300,000', 'id':300000]
    ]}"
optionKey="id" optionValue="name"
/>

When I get the value from the SELECT field to post back to the server it correctly has an Integer value, which I persist.  However the return trip never pre-selects the right row in the drop-down because the value is this comma separated String.

This works fine elsewhere in my code for small numbers where the comma formatting doesn't come into play, and the round-trip in and out of the SELECT is successful.  But values >999 don't work.

The docs say "This tag will inspect a bean which has been the subject of data binding and obtain the value of the field either from the originally submitted value contained within the bean's errors object populating during data binding or from the value of a bean's property. Once the value is obtained it will be automatically HTML encoded."

It's that last bit that I want to avoid as it appears to format Integers.  So, what little bit of Grails/GSP magic do I need to know so I can get my Integer to be rendered as an integer into my SELECT and pre-select the right row?

EDIT:
I have tried some further things based on the answers below, with pretty disappointing results so far...

If I put the <gformatNumber/> tag in my <g:select/> I get the page code as text in the browser.

<g:select name="minPrice"
value='<g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />'
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
['name':'100,000', 'id':100000],
['name':'200,000', 'id':200000],
['name':'300,000', 'id':300000],
]}"
optionKey="id" optionValue="name"
/>

Using the number format tag from GSP on my Integer value of 100000 like this...

var x = <g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />;

gives 100.  Remember that the fieldValue gives back 100,000, so this is not a surprise.

If I use the jsp taglib like this...

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
var y = <fmt:formatNumber value="${fieldValue(bean: personInstance, field: 'minPrice')}" pattern=".00"/>;

I get an error from the page compiler Cannot format given Object as a Number.

I guess I have a wider concern than I can't seem to get an Integer value as a genuine integer into my code if it is greater than 999 because of the default (and unconfigurable) behaviour of the fieldValue directive.  However my specific problem of not being able to pre-select an Integer value in a SELECT control is not going away.  At the moment I'm at a bit of a loss.

Anyone have any further ideas?

Body:
Better use custom PropertyEditor in order not to bother with formatNumber tag every time you output a value.
Like, declare a bean in resources.groovy:

myOwnCustomEditorRegistrar(CustomEditorRegistrar)

And create your class:

class CustomEditorRegistrar implements PropertyEditorRegistrar {
    void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(BigDecimal.class, new MyBigDecimalEditor(BigDecimal.class))
    }
}

ContentLicense: CC BY-SA 3.0


问:
Hidden variable Password parameter - powershell 4.0
I am creating a release definition with a powershell script to replace a file with env variables from the release definition it works but It doesn't seem to catch the password variable which is hidden in the release definition. is there a way to tell powershell to look for hidden variables?

UPDATE: Here is the script it finds all the variables in $paramsFilePath that are not hidden my password in In environmental variables in Release definition is hidden and the script doesn't find it.

```<code>param(
    [string]$paramsFilePath,

)

Write-Verbose -Verbose "Entering script Replace-SetParameters.ps1"
Write-Verbose -Verbose ("Path to SetParametersFile: {0}" -f $paramsFilePath)

# get the environment variables
$vars = Get-ChildItem -path env:*

# read in the setParameters file
$contents = Get-Content -Path $paramsFilePath

# perform a regex replacement
$newContents = "";

$contents  | % {
    $line = $_
    if ($_ -match "__(\w+)__") {
        $setting = Get-ChildItem -path env:* | ? { $_.Name -eq $Matches[1] }
        if ($setting) {
            Write-Verbose -Verbose ("Replacing key {0} with value from environment" -f $setting.Name)
            $line = $_ -replace "__(\w+)__", $setting.Value
        }
    }
    $newContents += $line + [Environment]::NewLine
}

Write-Verbose -Verbose "Overwriting SetParameters file with new values"
Set-Content $paramsFilePath -Value $newContents

Write-Verbose -Verbose "Exiting script Replace-SetParameters.ps1"
</code>```

答:
Unlike the normal variable, the password you are trying to get is secret variable.

Secret Variables

We recommend that you make the variable Secret  if it contains a
  password, keys, or some other kind of data that you need to avoid
  exposing.

The variable replacement we do is on the inputs on the tasks, we don't parse the scripts. To use secret variables you will have to take those as inputs into your script we explicitly do not populate those into the environment.  You could take a look at this discuss: Use hidden / secret variables in commands

Body:
I am creating a release definition with a powershell script to replace a file with env variables from the release definition it works but It doesn't seem to catch the password variable which is hidden in the release definition. is there a way to tell powershell to look for hidden variables?

UPDATE: Here is the script it finds all the variables in $paramsFilePath that are not hidden my password in In environmental variables in Release definition is hidden and the script doesn't find it.

param(
    [string]$paramsFilePath,

)

Write-Verbose -Verbose "Entering script Replace-SetParameters.ps1"
Write-Verbose -Verbose ("Path to SetParametersFile: {0}" -f $paramsFilePath)

# get the environment variables
$vars = Get-ChildItem -path env:*

# read in the setParameters file
$contents = Get-Content -Path $paramsFilePath

# perform a regex replacement
$newContents = "";

$contents  | % {
    $line = $_
    if ($_ -match "__(\w+)__") {
        $setting = Get-ChildItem -path env:* | ? { $_.Name -eq $Matches[1] }
        if ($setting) {
            Write-Verbose -Verbose ("Replacing key {0} with value from environment" -f $setting.Name)
            $line = $_ -replace "__(\w+)__", $setting.Value
        }
    }
    $newContents += $line + [Environment]::NewLine
}

Write-Verbose -Verbose "Overwriting SetParameters file with new values"
Set-Content $paramsFilePath -Value $newContents

Write-Verbose -Verbose "Exiting script Replace-SetParameters.ps1"


问:
Different Intents passing through multiple activity
I have five activities say A,B,C,D and E. Each activity has two buttons Yes & No, contains 1 & 0 value respectively.

I need to do the following thing.

If user press yes button of activity A, user + (only) yes button's value (int 1) passes to activity B and if user presses no button then user + (only) no button's value (int 0) will move to activity B. how can I do this to send only the specific value whose button was pressed at activity A. how can I determine which button was pressed by the user and then passed the already save values 1/0 to next activity.

Now Here comes the tricky part.

At activity B if user presses yes/no button then, the received int value of activity's A   +    int value of activity's B move to activity C. Similarly At activity C if user presses yes, then along this yes int value i.e 1 of activity C + values of activity A & activity B also passes to activity D. The very same process goes on until user came to last one i.e activity E.

How can I achieve this behaviour via intent or sharedpreferrence or any other way?

Please share some sample code as I am new to android. As I am failed to get through this and I found no example from internet which can lead me to solve this issue, after doing lot of searching.

答:
Here is logic,
Implement view onclicklistener and set listener to buttons.

```<code> public void onClick(View v) {

            Intent intent=new Intent(A.this, B.class);
            switch (v.getId()){
                case R.id.Yes:
                    intent.putExtra("value",1);
                break;
                case R.id.NO:
                    intent.putExtra("value",0);
                    break;
           }
            startActivity(intent);
</code>```

create intent object show in about code.

Body:
Here is logic,
Implement view onclicklistener and set listener to buttons.

 public void onClick(View v) {

            Intent intent=new Intent(A.this, B.class);
            switch (v.getId()){
                case R.id.Yes:
                    intent.putExtra("value",1);
                break;
                case R.id.NO:
                    intent.putExtra("value",0);
                    break;
           }
            startActivity(intent);

create intent object show in about code.


问:
Why PyAutoGui LocateOnScreen() only Returns None
Here's the code that I'm trying to run:</p>

```<code>import pyautogui
r=pyautogui.locateOnScreen('C:\Users\David\Desktop\index.png',grayscale=False)
print r
</code>```

答:
I had that problem but then i crop the photo into specific part then it was locating and yes it takes time.

or this can also work.

```<code>b = pyautogui.center('calc7key.png')
</code>```

Body:
Here's the code that I'm trying to run:

import pyautogui
r=pyautogui.locateOnScreen('C:\Users\David\Desktop\index.png',grayscale=False)
print r

Body:
I had that problem but then i crop the photo into specific part then it was locating and yes it takes time.

or this can also work.

b = pyautogui.center('calc7key.png')


问:
How do I add all the filenames under a certain folder to an arraylist using Java
I have this much so far

```<code> import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }
</code>```

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

答:
It is very easy. You can use recursion as follows:</p>

```<code> private static void read(final File folder)  {

    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            read(fileEntry);
        } else {
       //Do something
            }
    }
}
</code>```

Body:
I have this much so far

 import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

Body:
It is very easy. You can use recursion as follows:

 private static void read(final File folder)  {

    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            read(fileEntry);
        } else {
       //Do something
            }
    }
}


问:
Iterate over subclasses of a given class in a given module
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>

答:
Given the module foo.py</p>

```<code>class foo(object): pass
class bar(foo): pass
class baz(foo): pass

class grar(Exception): pass

def find_subclasses(module, clazz):
    for name in dir(module):
        o = getattr(module, name)

        try:
             if issubclass(o, clazz):
             yield name, o
        except TypeError: pass

>>> import foo
>>> list(foo.find_subclasses(foo, foo.foo))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]
>>> list(foo.find_subclasses(foo, object))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]
>>> list(foo.find_subclasses(foo, Exception))
[('grar', <class 'foo.grar'>)]
</code>```

OwnerDisplayName: Mark Roddy

Body:
Given the module foo.py

class foo(object): pass
class bar(foo): pass
class baz(foo): pass

class grar(Exception): pass

def find_subclasses(module, clazz):
    for name in dir(module):
        o = getattr(module, name)

        try:
             if issubclass(o, clazz):
             yield name, o
        except TypeError: pass

>>> import foo
>>> list(foo.find_subclasses(foo, foo.foo))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]
>>> list(foo.find_subclasses(foo, object))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]
>>> list(foo.find_subclasses(foo, Exception))
[('grar', <class 'foo.grar'>)]

OwnerDisplayName: zacherates


问:
Your project references the latest version of Entity Framework... - Error
I trying to create an entity data model with Oracle. I am getting this error.

I have these installed for my solution.

I have also installed ODT for VS 2015.

These are my references showing.

Web.config

```<code><configSections>
    <section name="entityFramework"
             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,     EntityFramework, Version=6.0.0.0, Culture=neutral,     PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<connectionStrings>
    <add name="OracleDbContext"
         providerName="Oracle.ManagedDataAccess.Client"
         connectionString="User Id=system;Password=myPassword;Data Source=ABC_DB" />
</connectionStrings>
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
   <modules>
       <remove name="FormsAuthentication" />
   </modules>
</system.webServer>
<runtime>
 ........
</runtime>
<entityFramework>
    <defaultConnectionFactory
         type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework">
    </defaultConnectionFactory>
    <providers>
        <!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        <provider invariantName="Oracle.ManagedDataAccess.Client"
                  type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />-->
        <provider invariantName="Oracle.ManagedDataAccess.Client"
                  type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </providers>
</entityFramework>
<system.codedom>
    <compilers>
        <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
</system.codedom>
<system.data>
   <DbProviderFactories>
       <remove invariant="Oracle.ManagedDataAccess.Client" />
       <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
</system.data>
<oracle.manageddataaccess.client>
  <version number="*">
  <dataSources>
    <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
  </dataSources>
 </version>
</oracle.manageddataaccess.client>
</code>```

What am I missing?

答: I managed to resolve this issue by updating the Entity Framework to 6.1.3, Oracle Managed Data Access to 12.1.24160719 and Oracle Managed Data Access Entity Framework to 12.1.2400. Please use the nuget manager to update. After this, It WORKS!!!</p>

Body:
I trying to create an entity data model with Oracle. I am getting this error.

I have these installed for my solution.

I have also installed ODT for VS 2015.

These are my references showing.

Web.config

<configSections>

</configSections>
<connectionStrings>
    <add name="OracleDbContext"
         providerName="Oracle.ManagedDataAccess.Client"
         connectionString="User Id=system;Password=myPassword;Data Source=ABC_DB" />
</connectionStrings>
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
   <modules>
       <remove name="FormsAuthentication" />
   </modules>
</system.webServer>
<runtime>
 ........
</runtime>
<entityFramework>
    <defaultConnectionFactory
         type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory, Oracle.ManagedDataAccess.EntityFramework">
    </defaultConnectionFactory>
    <providers>

        <provider invariantName="Oracle.ManagedDataAccess.Client"
                  type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </providers>
</entityFramework>
<system.codedom>
    <compilers>
        <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
</system.codedom>
<system.data>
   <DbProviderFactories>
       <remove invariant="Oracle.ManagedDataAccess.Client" />
       <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
</system.data>
<oracle.manageddataaccess.client>
  <version number="*">
  <dataSources>
    <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
  </dataSources>
 </version>
</oracle.manageddataaccess.client>

What am I missing?


问:
SDK Location not found in android studio
I have just imported my eclipse project in android studio. it keeps my saying that

```<code>Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.
</code>```

I have seen some tutorials of editing local.properties files but it didnt work. here is my project.properties file:

```<code>sdk.dir=E:\\Mod Eclipse\\adt-bundle-windows-x86_64-20130219\\sdk
</code>```

Actual directory of my folder is :

E:\Mod Eclipse\adt-bundle-windows-x86_64-20130219\sdk

答:
You can add a local.properties with to set the sdk.dir like sdk.dir=/Users/roofe/Library/Android/sdk.

But please note below, which is very important,

add the local.properties to the uppermost path of the project. Here the uppermost have some difference with root path of a project.

For example in the below project, I just use the ijkplayer-example, but this module also used other module with different cpu architecture.

If I only add local.properties to ijkplayer-example will not work. Here will get sdk  location issue for other module.

While I can add the local.properties to the ijkplayer directory, then when I try to open the ijkplayer-example project, there will auto create a local.properties for ijkplayer-example, and everything works well.

Body:
I have just imported my eclipse project in android studio. it keeps my saying that

Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

I have seen some tutorials of editing local.properties files but it didnt work. here is my project.properties file:

sdk.dir=E:\\Mod Eclipse\\adt-bundle-windows-x86_64-20130219\\sdk

Actual directory of my folder is :

E:\Mod Eclipse\adt-bundle-windows-x86_64-20130219\sdk


问:
How to send POST Angular 2
I am studying Angular 2/4 to be able to use that framework soon, but I am very confused with the POST part, I am using the Github API to post an "issue" in my repository but I still can not do it ... so I would be very Grateful if you can clarify that point to send a "issue" type test to understand how it works in Angular 2/4 since I understand that it has to be sent in format "JSON" to work but I do not understand how ... Using github api: https://developer.github.com/v3/issues/#create-an-issue

My code:

github.service.ts

```<code>import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GithubService {

  private username: string;
  private reponame: string;
  private client_id = '+++++++++++++++++++++++';
  private client_secret = '++++++++++++++++++++++++++++';

  constructor(private http: Http) {
    console.log('Github Service Ready...');
    this.username = 'anubis';
  }

  getGithubUser() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  getGithubRepository() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '/repos'
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  // to search another user and show his/her repositories
  SearchAgain(usernamenew: string) {
    this.username = usernamenew;
  }

  // I HAVE PROBLEMS IN THIS PART
  addIssue(forms) {
    this.reponame = 'LinioAngularProfileListMarcoAntonioVMontoyaCardenas';
    const headers = new Headers({'Content-Type': 'application/json'});

    return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
        + this.reponame + ' /issues?' + forms
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret,
      {headers: headers}).map(res => res.json());
  }

}
</code>```

issue.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { GithubService } from '../../Services/github.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html'
})
export class IssueComponent implements OnInit {

  user: any;
  repo: any[];
  username: string;

  constructor(private service: GithubService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.user = false;

    this.route.params
      .subscribe(
        (params: Params) => {
          // this.id = +params['id'];
          // this.editMode = params['id'] != null;
          // this.initForm();
        }
      );
  }

  OnSearchUser() {
    // get user information
    this.service.getGithubUser().subscribe(userGit => {
      console.log(userGit);
      this.user = userGit;
    });

    // get user repositories
    this.service.getGithubRepository().subscribe(userRepo => {
      console.log(userRepo);
      this.repo = userRepo;
    });

    this.service.SearchAgain(this.username);
  }

  addIssue( title: string,
            body: string,
            assignee: string,
            milestone: number,
            labels: string) {

    var newIssueAdd = {
      // title: title,
      // body: body,
      // assignee: assignee,
      // milestone: milestone,
      // labels: labels
      title: 'test1',
      body: 'ksjdlkafjslkdf',
      assignee: 'sdljflksjadflñdks',
      milestone: 1,
      labels: 'testlbl'
    };

    console.log(newIssueAdd);

    this.service.addIssue(newIssueAdd).subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
   }
}
</code>```

issue.component.html I'm only using a simple button to send the "issue" without any forms, I tried to make the post worked but I can't...

```<code><div class="row">
  <div class="col-md-12">
    <form class="well-lg">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search Username..."
               [(ngModel)]="username" name="username" (keyup)="OnSearchUser()">
      </div>
    </form>
  </div>
</div>

<div *ngIf="user">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">{{user.name}}</h3>
    </div>
    <div class="panel-body">
      <div class="row">
        <div class="col-md-4">
          <img src="{{user.avatar_url}}" alt="" class="img-thumbnail">
          <a href="{{user.html_url}}" target="_blank" class="btn btn-default btn-block">View Profile</a>
        </div>
        <div class="col-md-8">
          <div class="stats">
            <span class="label label-default">{{user.public_repos}} Public Repositories</span>
            <span class="label label-primary">{{user.public_gists}} Public Github Gists</span>
            <span class="label label-success">{{user.followers}} Followers</span>
            <span class="label label-info">{{user.following}} Following</span>
          </div>
          <br>
          <ul class="list-group">
            <li class="list-group item"><strong>Username: </strong>{{user.login}}</li>
            <li class="list-group item"><strong>Location: </strong>{{user.location}}</li>
            <li class="list-group item"><strong>Email: </strong>{{user.email}}</li>
            <li class="list-group item"><strong>Blog: </strong>{{user.blog}}</li>
            <li class="list-group item"><strong>Member Since: </strong>{{user.created_at}}</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">User Repositories</h3>
      </div>
      <div class="panel-body">
        <div *ngFor="let re of repo">
          <div class="row">
            <div class="col-md-9">
              <h4><a target="_blank" href="{{re.html_url}}">{{re.name}}</a></h4>
              <button class="btn btn-primary" (click)="addIssue()">Create Issue</button>
              <p>{{re.description}}</p>
            </div>
            <div class="col-md-3">
              <span class="label label-default">{{re.watchers}} Watchers</span>
              <span class="label label-default">{{re.forks}} Forks</span>
            </div>
          </div>
          <hr>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

答:
In your addIssue method, what type is forms supposed to be? It looks like it's being put into the URL, when it should probably be passed in as the body argument referenced in the documentation here:

post(url: string, body: any, options?: RequestOptionsArgs) : Observable

Title: How to send POST Angular 2

Body:
I am studying Angular 2/4 to be able to use that framework soon, but I am very confused with the POST part, I am using the Github API to post an "issue" in my repository but I still can not do it ... so I would be very Grateful if you can clarify that point to send a "issue" type test to understand how it works in Angular 2/4 since I understand that it has to be sent in format "JSON" to work but I do not understand how ... Using github api: https://developer.github.com/v3/issues/#create-an-issue

My code:

github.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GithubService {

  private username: string;
  private reponame: string;
  private client_id = '+++++++++++++++++++++++';
  private client_secret = '++++++++++++++++++++++++++++';

  constructor(private http: Http) {
    console.log('Github Service Ready...');
    this.username = 'anubis';
  }

  getGithubUser() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  getGithubRepository() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '/repos'
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  // to search another user and show his/her repositories
  SearchAgain(usernamenew: string) {
    this.username = usernamenew;
  }

  // I HAVE PROBLEMS IN THIS PART
  addIssue(forms) {
    this.reponame = 'LinioAngularProfileListMarcoAntonioVMontoyaCardenas';
    const headers = new Headers({'Content-Type': 'application/json'});

    return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
        + this.reponame + ' /issues?' + forms
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret,
      {headers: headers}).map(res => res.json());
  }

}

issue.component.ts

import { Component, OnInit } from '@angular/core';
import { GithubService } from '../../Services/github.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html'
})
export class IssueComponent implements OnInit {

  user: any;
  repo: any[];
  username: string;

  constructor(private service: GithubService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.user = false;

    this.route.params
      .subscribe(
        (params: Params) => {
          // this.id = +params['id'];
          // this.editMode = params['id'] != null;
          // this.initForm();
        }
      );
  }

  OnSearchUser() {
    // get user information
    this.service.getGithubUser().subscribe(userGit => {
      console.log(userGit);
      this.user = userGit;
    });

    // get user repositories
    this.service.getGithubRepository().subscribe(userRepo => {
      console.log(userRepo);
      this.repo = userRepo;
    });

    this.service.SearchAgain(this.username);
  }

  addIssue( title: string,
            body: string,
            assignee: string,
            milestone: number,
            labels: string) {

    var newIssueAdd = {
      // title: title,
      // body: body,
      // assignee: assignee,
      // milestone: milestone,
      // labels: labels
      title: 'test1',
      body: 'ksjdlkafjslkdf',
      assignee: 'sdljflksjadflñdks',
      milestone: 1,
      labels: 'testlbl'
    };

    console.log(newIssueAdd);

    this.service.addIssue(newIssueAdd).subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
   }
}

issue.component.html I'm only using a simple button to send the "issue" without any forms, I tried to make the post worked but I can't...

    <form class="well-lg">

        <input type="text" class="form-control" placeholder="Search Username..."
               [(ngModel)]="username" name="username" (keyup)="OnSearchUser()">

    </form>

{{user.name}}

          View Profile

            {{user.public_repos}} Public Repositories
            {{user.public_gists}} Public Github Gists
            {{user.followers}} Followers
            {{user.following}} Following

Username: {{user.login}}

Location: {{user.location}}

Email: {{user.email}}

Blog: {{user.blog}}

Member Since: {{user.created_at}}

User Repositories

{{re.name}}

              <button class="btn btn-primary" (click)="addIssue()">Create Issue</button>

{{re.description}}

              {{re.watchers}} Watchers
              {{re.forks}} Forks


问:
Redirect from '/' in React-Router
I trying setup redirect from "/account" to "/account/signIn"

```<code>  <Layout>
    <Switch>
      <Redirect from="/account" to="/account/signIn" />
      <Route path="/account/signIn" component={() => <div>signIn</div>} />
      <Route path="/account/signUp" component={() => <div>signUp</div>} />
    </Switch>
  </Layout>
</code>```

When i go to http://localhost:3000/account/signUp i redirecting to http://localhost:3000/account/signIn.
This problem is fixed in this way:

```<code>  <Layout>
    <Route exact path="/account" render={() => <Redirect to="/account/signIn" />} />
    <Route path="/account/signIn" component={() => <div>signIn</div>} />
    <Route path="/account/signUp" component={() => <div>signUp</div>} />
  </Layout>
</code>```

But i think that is not best way, because i have a question this is bug or normal behaviour?

答:
The from on <Redirect> matches loosely by default. As you have it, it will match anything that starts with /account, which includes your /account/signIn and /account/signUp paths.

Inside of Switch, it's actually reading the props of its children directly and doesn't distinguish the type of component. So, you can use exact and strict like you can on a Route.

Therefore, this should work for you:

```<code><Layout>
  <Switch>
    <Redirect exact from="/account" to="/account/signIn" />
    <Route path="/account/signIn" component={() => <div>signIn</div>} />
    <Route path="/account/signUp" component={() => <div>signUp</div>} />
  </Switch>
</Layout>
</code>```

Title: Redirect from '/' in React-Router

Body:
I trying setup redirect from "/account" to "/account/signIn"

  <Layout>
    <Switch>
      <Redirect from="/account" to="/account/signIn" />
      <Route path="/account/signIn" component={() =>
signIn
} />
      <Route path="/account/signUp" component={() =>
signUp
} />
    </Switch>
  </Layout>

When i go to http://localhost:3000/account/signUp i redirecting to http://localhost:3000/account/signIn.
This problem is fixed in this way:

  <Layout>
    <Route exact path="/account" render={() => <Redirect to="/account/signIn" />} />
    <Route path="/account/signIn" component={() =>
signIn
} />
    <Route path="/account/signUp" component={() =>
signUp
} />
  </Layout>

But i think that is not best way, because i have a question this is bug or normal behaviour?

Body:
The from on <Redirect> matches loosely by default. As you have it, it will match anything that starts with /account, which includes your /account/signIn and /account/signUp paths.

Inside of Switch, it's actually reading the props of its children directly and doesn't distinguish the type of component. So, you can use exact and strict like you can on a Route.

Therefore, this should work for you:

<Layout>
  <Switch>
    <Redirect exact from="/account" to="/account/signIn" />
    <Route path="/account/signIn" component={() => <div>signIn</div>} />
    <Route path="/account/signUp" component={() => <div>signUp</div>} />
  </Switch>
</Layout>


问:
WPF Refresh StaticResource
I have a ComboBox that has it's ItemsSource bound as

```<code>ItemsSource="{Binding Source={StaticResource documentTemplates}}"
</code>```

Where documentTemplates is

```<code><ObjectDataProvider x:Key="documentTemplates"
                    ObjectType="{x:Type Core:DataHelper}"
                    MethodName="GetDocumentTemplates"/>
</code>```

The problem I have is that the document templates defined in the database could be changed by other areas of the application (or indeed by another user) and so I want to have the ItemsSource requery each time. At the moment, once the resource has been populated it will never requery. I assume that this is because it is a StaticResource, but if I swap this for a DynamicResource  I get

A 'DynamicResourceExtension' cannot be set on the 'Source' property of type 'Binding'. A 'DynamicResrouceExtension' can only be set on a DependencyProperty or a DependencyObject

How should I go about fixing this?

答:
Keep your XAML as is and whenever a requery is needed call Refresh on the ObjectDataProvider.</p>

```<code>(FindResource("documentTemplates") as ObjectDataProvider).Refresh();
</code>```

Title: WPF Refresh StaticResource

Body:
I have a ComboBox that has it's ItemsSource bound as

ItemsSource="{Binding Source={StaticResource documentTemplates}}"

Where documentTemplates is

<ObjectDataProvider x:Key="documentTemplates"
                    ObjectType="{x:Type Core:DataHelper}"
                    MethodName="GetDocumentTemplates"/>

The problem I have is that the document templates defined in the database could be changed by other areas of the application (or indeed by another user) and so I want to have the ItemsSource requery each time. At the moment, once the resource has been populated it will never requery. I assume that this is because it is a StaticResource, but if I swap this for a DynamicResource  I get

A 'DynamicResourceExtension' cannot be set on the 'Source' property of type 'Binding'. A 'DynamicResrouceExtension' can only be set on a DependencyProperty or a DependencyObject

How should I go about fixing this?

Body:
Keep your XAML as is and whenever a requery is needed call Refresh on the ObjectDataProvider.

(FindResource("documentTemplates") as ObjectDataProvider).Refresh();


问:
How does Jetty deployment on Azure App Service work?
I have a Java web app that I run on an Azure App Service instance. To deploy it, I use a Bitbucket repo with a .war file inside it. When I commit a new .war file to this repo, it is supposed to be deployed automagically by the service. However, more often than not, I have to either restart, re-deploy, or even upload the .war file via FTP for the deployment to be completed successfully.

I have a single Jetty instance residing in this service, hence my .war file is named ROOT.war. AFAIK, when uploaded to the service (whether via Bitbucket or FTP), this .war file should be unarchived into the same directory, which is /site/wwwroot/webapps. In my case, this doesn't happen. The web app works with the ROOT.war file sitting alone inside /site/wwwroot/webapps. And every once in a while, I get a ROOT folder under /site/wwwroot/webapps, with two default files index.jsp and background.png. I don't have the slightest idea what causes the ROOT folder to appear with these default files. The only clue I have is that it happened a couple of times after I changed an environment variable.

Also after the ROOT folder appears with the empty server files, the only way I can re-deploy the app is to manually delete this ROOT folder via FTP or the console provided in the portal, and only then my re-deploy request succeeds with my web app.

So, if it isn't clear enough, my question is what is going on here? I can't make anything out of the behaviors I'm facing. I feel like I'm using this Azure service blindly, and can't get to fix anything when something goes wrong. Are there any resources that may explain what happens in the background when a web app is deployed?

答:
So, Azure API Apps are a PAAS, not IAAS service. You can access the PaaS platform by coming to yoursite.scm.azurewebsites.net, where you can browse the file system in CMD or Powershell, and you can see the running processes. This may feel like you are on a single VM, but you are not. The data you see here is replicated down into your API App instances. You can control how many instances you have through scaling your API App.

I have commonly seen your issue with deploying, then ROOT being empty(working internally to see this fixed...).
The best method that works every time for me, is to stop your API App, manually UNZIP your ROOT.war. Move the files into /ROOT/, then to start your API App.

You can simply place ROOT.war, and let the system unpack it when you turn it back on, but this can sometimes lead to that empty ROOT directory, then requiring another restart.

All of this has me moving to Spring-Boot instead. No unpacking required. Simply configure your web.config and drop the jar file.

https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-java-custom-upload#springboot


问:
angularJs routeProvider issue
I have the below mentioned Angular code that uses the config and the routeProvider. View1 and View 2 are also enclosed.

```<code><!DOCTYPE html>
<html>
<head>
    <title>My test application</title>
</head>
<body ng-app="myApp">
    <div>
        <div ng-view></div>
    </div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
min.js"></script>
    <script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
    <script>
        var myApp = angular.module('myApp', ['ngRoute']);

        myApp.config(function($routeProvider){
            $routeProvider
                .when('/',
                {
                    controller: 'SimpleController',
                    templateUrl: 'Partials/view1.html'
                })
                .when('/view2',{
                    controller: 'SimpleController'
                    templateUrl:'Partials/view2.html'
                })
                .otherwise({
                    redirectTo: '/'
                });
        });

        myApp.controller('SimpleController',SimpFunc);
        function SimpFunc($scope){
            $scope.customers = [
                {name:'Dave Smith', city:'New York'},
                {name:'Will Smith', city:'Phily'},
                {name:'Will Die', city:'Cincy'},
                {name:'Die till', city:'New Jersey'},
                {name:'Till What', city:'Cincy'}
            ];
            $scope.addCustomer = function(){
                $scope.customers.push(
                    {
                        name: $scope.newCust.name,
                        city: $scope.newCust.city
                    });
            };
        }
    </script>
</body>
</html>
</code>```

View1.html

```<code><div class="container">
<h2>View 1</h2>
Name:
<br />
<input type="text" ng-model="filter.name" />
<br />
<ul>
    <li ng-repeat="cust in customers | filter:filter.name">{{ cust.name
}} - {{ cust.city }}</li>
</ul>
<br />
Customer Name:
<br />
<input type="text" ng-model="newCust.name" />
Customer City:
<br />
<input type="text" ng-model="newCust.city" />
<br />
<button ng-click="addCustomer()">Add customer</button>
<br />
<a href="#/view2">View 2</a>
</div>
</code>```

View 2

```<code><div class="container">
<h2>View 2</h2>
City:
<br />
<input type="text" ng-model="filter.city" />
<br />
<ul>
    <li ng-repeat="cust in customers | filter:filter.city">{{ cust.name
}} - {{ cust.city }}</li>
</ul>
</div>
</code>```

I am not able to render view1 and/or view2 in the page. How can I do that?

答:
Your script library URLs are giving 404 error.

I used below

https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.js

And comma missing after SimpleController

``` <code>
.when('/view2',{
                    controller: 'SimpleController',

 </code> ```

Title: angularJs routeProvider issue

Body:
I have the below mentioned Angular code that uses the config and the routeProvider. View1 and View 2 are also enclosed.

<!DOCTYPE html>

    <title>My test application</title>

View1.html

View 1

Name:

<input type="text" ng-model="filter.name" />

{{ cust.name
}} - {{ cust.city }}

Customer Name:

<input type="text" ng-model="newCust.name" />
Customer City:

<input type="text" ng-model="newCust.city" />

<button ng-click="addCustomer()">Add customer</button>

View 2

View 2

View 2

City:

<input type="text" ng-model="filter.city" />

{{ cust.name
}} - {{ cust.city }}

I am not able to render view1 and/or view2 in the page. How can I do that?

Body:
Your script library URLs are giving 404 error.

I used below

https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.js

And comma missing after SimpleController

.when('/view2',{
                    controller: 'SimpleController',


问:
Azure Custom Controller / API .Net backend
I have had a MobileService running on Azure, and have decided to create a new service and migrate the code myself. The new service is of the new type called: Azure Mobile App Service.

Currently I have Authentication working, and can do migrations/update-database. I am following the TodoItem example. I now want to create my own Custom API, which easily worked on MobileService, but I cannot get it working on Azure Mobile App :/

I have followed these two links web-Api-routing and app-service-mobile-backend. And I now have the following:

I have created a new controller:

```<code>[MobileAppController]
public class TestController : ApiController
{
    // GET api/Test
    [Route("api/Test/completeAll")]
    [HttpPost]
    public async Task<ihttpactionresult> completeAll(string info)
    {
        return Ok(info + info + info);
    }
}
</code>```

In the mobileApp.cs I have added the below code according to backend:

```<code>HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
</code>```

Additionally I have installed the below package according to web-api-routing:

```<code>Microsoft.AspNet.WebApi.WebHost
</code>```

and the call from the client:

```<code>string t = await App.MobileService.InvokeApiAsync<string,string>("Test/completeAll", "hej");
</code>```

Debug shows, that it is the correct URL:

{Method: POST, RequestUri: 'https://xxxxxxx.azurewebsites.net/api/Test/completeAll',
  Version: 1.1, Content: System.Net.Http.StringContent, Headers:{  X-ZUMO-FEATURES:
  AT  X-ZUMO-INSTALLATION-ID: e9b359df-d15e-4119-a4ad-afe3031d8cd5  X-ZUMO-AUTH:
  xxxxxxxxxxx  Accept: application/json  User-Agent:
  ZUMO/2.0  User-Agent: (lang=Managed; os=Windows Store; os_version=--; arch=Neutral; version=2.0.31125.0)
    X-ZUMO-VERSION: ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=Neutral; version=2.0.31125.0)
    ZUMO-API-VERSION: 2.0.0  Content-Type: application/json; charset=utf-8  Content-Length: 3}}

But keep getting: 404 (Not Found)
Debug Message   "The request could not be completed.  (Not Found)"

What am I missing :/ ?

Update

I have tried expanding the code in The mobileApp.cs, with:

```<code>HttpConfiguration config = new HttpConfiguration();
        new MobileAppConfiguration()
            .UseDefaultConfiguration().MapApiControllers()
            .ApplyTo(config);
        config.MapHttpAttributeRoutes();
        app.UseWebApi(config);
</code>```

based on app-service-backend, however still no access :/

Update

I used fiddler2 to access the endpoint through a browser and got the following results:

Update Again

I have tried to create another minimal solution, but still get the same error. Are there any great tutorials that I can follow to achieve this functionality?

The positive feeling is slowly evaporating . . .

The question is also running now on msdn, I will update here if any information is shown there.

Update

Tested Lindas comment, and I can in fact access the value converter:

```<code>// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
public class ValuesController : ApiController
{
    // GET api/values
    public string Get()
    {
        MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
        ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter();

        string host = settings.HostName ?? "localhost";
        string greeting = "Hello from " + host;

        traceWriter.Info(greeting);
        return greeting;
    }

    // POST api/values
    public string Post()
    {
        return "Hello World!";
    }

}
</code>```

This I access using the both the post and get function:

```<code>string t = await App.MobileService.InvokeApiAsync<string, string>("values", null, HttpMethod.Post, null);
</code>```

or

```<code>string t = await App.MobileService.InvokeApiAsync<string, string>("values", null, HttpMethod.Get, null);
</code>```

But the code I pasted has no route so why can I access it using values? What would the path be to the original controller if did not use the route parameter?

Extra Information

I have now created a support ticket with Microsoft and will update with additional information. . . Hopefully.

Update
Info from MSDN Forum: try MS_SkipVersionCheck
Reading about the attribute here, it does not seem applicable. But I tried it. Still Not Found for my API but the original one is still working. So it did not have an impact on this issue.

答:
I found another cause for the 404 errors when it came to use attribute routing.

The code above originally had this in mobileApp.cs:

```<code>HttpConfiguration config = new HttpConfiguration();
    new MobileAppConfiguration()
        .UseDefaultConfiguration().MapApiControllers()
        .ApplyTo(config);
    config.MapHttpAttributeRoutes();
    app.UseWebApi(config);
</code>```

The config.MapHttpAttributeRoutes() needs to be moved above the .ApplyTo:

```<code>HttpConfiguration config = new HttpConfiguration();
 config.MapHttpAttributeRoutes();
 new MobileAppConfiguration()
        .UseDefaultConfiguration().MapApiControllers()
        .ApplyTo(config);
</code>```

Body:
I have had a MobileService running on Azure, and have decided to create a new service and migrate the code myself. The new service is of the new type called: Azure Mobile App Service.

Currently I have Authentication working, and can do migrations/update-database. I am following the TodoItem example. I now want to create my own Custom API, which easily worked on MobileService, but I cannot get it working on Azure Mobile App :/

I have followed these two links web-Api-routing and app-service-mobile-backend. And I now have the following:

I have created a new controller:

[MobileAppController]
public class TestController : ApiController
{
    // GET api/Test
    [Route("api/Test/completeAll")]
    [HttpPost]
    public async Task<ihttpactionresult> completeAll(string info)
    {
        return Ok(info + info + info);
    }
}

In the mobileApp.cs I have added the below code according to backend:

HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();

Additionally I have installed the below package according to web-api-routing:

Microsoft.AspNet.WebApi.WebHost

and the call from the client:

string t = await App.MobileService.InvokeApiAsync<string,string>("Test/completeAll", "hej");

Debug shows, that it is the correct URL:

{Method: POST, RequestUri: 'https://xxxxxxx.azurewebsites.net/api/Test/completeAll',
  Version: 1.1, Content: System.Net.Http.StringContent, Headers:{  X-ZUMO-FEATURES:
  AT  X-ZUMO-INSTALLATION-ID: e9b359df-d15e-4119-a4ad-afe3031d8cd5  X-ZUMO-AUTH:
  xxxxxxxxxxx  Accept: application/json  User-Agent:
  ZUMO/2.0  User-Agent: (lang=Managed; os=Windows Store; os_version=--; arch=Neutral; version=2.0.31125.0)
    X-ZUMO-VERSION: ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=Neutral; version=2.0.31125.0)
    ZUMO-API-VERSION: 2.0.0  Content-Type: application/json; charset=utf-8  Content-Length: 3}}

But keep getting: 404 (Not Found)
Debug Message   "The request could not be completed.  (Not Found)"

What am I missing :/ ?

Update

I have tried expanding the code in The mobileApp.cs, with:

HttpConfiguration config = new HttpConfiguration();
        new MobileAppConfiguration()
            .UseDefaultConfiguration().MapApiControllers()
            .ApplyTo(config);
        config.MapHttpAttributeRoutes();
        app.UseWebApi(config);

based on app-service-backend, however still no access :/

Update

I used fiddler2 to access the endpoint through a browser and got the following results:

Update Again

I have tried to create another minimal solution, but still get the same error. Are there any great tutorials that I can follow to achieve this functionality?

The positive feeling is slowly evaporating . . .

The question is also running now on msdn, I will update here if any information is shown there.

Update

Tested Lindas comment, and I can in fact access the value converter:

// Use the MobileAppController attribute for each ApiController you want to use
// from your mobile clients
[MobileAppController]
public class ValuesController : ApiController
{
    // GET api/values
    public string Get()
    {
        MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
        ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter();

        string host = settings.HostName ?? "localhost";
        string greeting = "Hello from " + host;

        traceWriter.Info(greeting);
        return greeting;
    }

    // POST api/values
    public string Post()
    {
        return "Hello World!";
    }

}

This I access using the both the post and get function:

string t = await App.MobileService.InvokeApiAsync<string, string>("values", null, HttpMethod.Post, null);

or

string t = await App.MobileService.InvokeApiAsync<string, string>("values", null, HttpMethod.Get, null);

But the code I pasted has no route so why can I access it using values? What would the path be to the original controller if did not use the route parameter?

Extra Information

I have now created a support ticket with Microsoft and will update with additional information. . . Hopefully.

Update
Info from MSDN Forum: try MS_SkipVersionCheck
Reading about the attribute here, it does not seem applicable. But I tried it. Still Not Found for my API but the original one is still working. So it did not have an impact on this issue.

Body:
I found another cause for the 404 errors when it came to use attribute routing.

The code above originally had this in mobileApp.cs:

HttpConfiguration config = new HttpConfiguration();
    new MobileAppConfiguration()
        .UseDefaultConfiguration().MapApiControllers()
        .ApplyTo(config);
    config.MapHttpAttributeRoutes();
    app.UseWebApi(config);

The config.MapHttpAttributeRoutes() needs to be moved above the .ApplyTo:

HttpConfiguration config = new HttpConfiguration();
 config.MapHttpAttributeRoutes();
 new MobileAppConfiguration()
        .UseDefaultConfiguration().MapApiControllers()
        .ApplyTo(config);


问:
Parallel processing in golang
Given the following code:

```<code>package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    for i := 0; i < 3; i++ {
        go f(i)
    }

    // prevent main from exiting immediately
    var input string
    fmt.Scanln(&input)
}

func f(n int) {
    for i := 0; i < 10; i++ {
        dowork(n, i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func dowork(goroutine, loopindex int) {
    // simulate work
    time.Sleep(time.Second * time.Duration(5))
    fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex)
}
</code>```

Can i assume that the 'dowork' function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate 'dowork' workers for each goroutine?

答:
Regarding GOMAXPROCS, you can find this in Go 1.5's release docs:

By default, Go programs run with GOMAXPROCS set to the number of cores available; in prior releases it defaulted to 1.

Regarding preventing the main function from exiting immediately, you could leverage WaitGroup's Wait function.

I wrote this utility function to help parallelize a group of functions:

```<code>import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So in your case, we could do this

```<code>func1 := func() {
    f(0)
}

func2 = func() {
    f(1)
}

func3 = func() {
    f(2)
}

Parallelize(func1, func2, func3)
</code>```

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util

Title: Parallel processing in golang

Body:
Given the following code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    for i := 0; i < 3; i++ {
        go f(i)
    }

    // prevent main from exiting immediately
    var input string
    fmt.Scanln(&input)
}

func f(n int) {
    for i := 0; i < 10; i++ {
        dowork(n, i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func dowork(goroutine, loopindex int) {
    // simulate work
    time.Sleep(time.Second * time.Duration(5))
    fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex)
}

Can i assume that the 'dowork' function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate 'dowork' workers for each goroutine?

Body:
Regarding GOMAXPROCS, you can find this in Go 1.5's release docs:

By default, Go programs run with GOMAXPROCS set to the number of cores available; in prior releases it defaulted to 1.

Regarding preventing the main function from exiting immediately, you could leverage WaitGroup's Wait function.

I wrote this utility function to help parallelize a group of functions:

import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So in your case, we could do this

func1 := func() {
    f(0)
}

func2 = func() {
    f(1)
}

func3 = func() {
    f(2)
}

Parallelize(func1, func2, func3)

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util


问:
what is order of complexity in Big O notation?
Question

Hi I am trying to understand what order of complexity in terms of Big O notation is. I have read many articles and am yet to find anything explaining exactly 'order of complexity', even on the useful descriptions of Big O on here.

What I already understand about big O

The part which I already understand. about Big O notation is that we are measuring the time and space complexity of an algorithm in terms of the growth of input size n. I also understand that certain sorting methods have best, worst and average scenarios for Big O such as O(n) ,O(n^2) etc and the n is input size (number of elements to be sorted).

Any simple definitions or examples would be greatly appreciated thanks.

答:
I see that you are commenting on several answers wanting to know the specific term of order as it relates to Big-O.

Suppose f(n) = O(n^2), we say that the order is n^2.


问:
Clicking New Chat Icon in Whatsapp Web using Javascript
image of code using inspector

I want to click new chat button in http://web.whatsapp.com/ , and search a string.

Below is html tag that i want click:

```<code><button class="icon icon-chat" title="New chat"></button>
</code>```

and i use this javascript to click it:

```<code>document.querySelector('.icon.icon-chat').click()
</code>```

but not work.

in same web, i use this code for clicking sending icon for send message and work:

```<code> document.querySelector('.icon.icon-send.compose-btn-send').click()
</code>```

答:
The React dev tools shows that the event handler is written to trigger on mousedown. So you have to fire mousedown event

Type this in console

```<code>function simulateMouseEvents(element, eventName) {
    var mouseEvent= document.createEvent ('MouseEvents');
    mouseEvent.initEvent (eventName, true, true);
    element.dispatchEvent (mouseEvent);
}

simulateMouseEvents(document.querySelector('.icon.icon-chat'), 'mousedown')
</code>```

Body:
image of code using inspector

I want to click new chat button in http://web.whatsapp.com/ , and search a string.

Below is html tag that i want click:

<button class="icon icon-chat" title="New chat"></button>

and i use this javascript to click it:

document.querySelector('.icon.icon-chat').click()

but not work.

in same web, i use this code for clicking sending icon for send message and work:

 document.querySelector('.icon.icon-send.compose-btn-send').click()

Body:
The React dev tools shows that the event handler is written to trigger on mousedown. So you have to fire mousedown event

Type this in console

function simulateMouseEvents(element, eventName) {
    var mouseEvent= document.createEvent ('MouseEvents');
    mouseEvent.initEvent (eventName, true, true);
    element.dispatchEvent (mouseEvent);
}

simulateMouseEvents(document.querySelector('.icon.icon-chat'), 'mousedown')


问:
The command "dotnet bundle" exited with code 1 - VS 2017 Publish ASP.NET Core Web API
I'm getting the following error when trying to publish my Web API to a server:

The command "dotnet bundle" exited with code 1

This is the publish screen:

This is the error from output:

Can anyone help me?

答:
Make sure you have added the DotNetCliToolReference in your WebApi project.  I'm assuming VS2017 csproj file.

```<code>  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
    <DotNetCliToolReference Include="BundlerMinifier.Core" Version="2.2.281" />
  </ItemGroup>
</code>```

The second entry in the code above.

Body:
Make sure you have added the DotNetCliToolReference in your WebApi project.  I'm assuming VS2017 csproj file.

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
    <DotNetCliToolReference Include="BundlerMinifier.Core" Version="2.2.281" />
  </ItemGroup>

The second entry in the code above.


问:
How do I get notifications sent to each device when a child is added, using Swift and Firebase?
I have a fully functioning application that uses Firebase as a backend. I want to be able to have a user receive a notification when a child is added to my Firebase database under that users ID.

I have looked everywhere but all I can find are links to OneSignal or people telling me to "make a custom server" as if it can be done by magic. How do I go about making a server? What language? What do I do with OneSignal? Can someone guide me step by step without telling me to simple make a custom server.

答:
I believe Cloud Functions for Firebase is exactly what you're looking for. Specifically, Realtime Database Triggers:

The Realtime Database supports the onWrite() event, which triggers anytime data is created, destroyed, or changed in a specified database location.

In a typical lifecycle, a Firebase Realtime Database function does the following:

Waits for changes to a particular database location for write events.

Fires when a write event occurs and performs its tasks (see What can I do with Cloud Functions? for examples of use cases).

Receives an event data object that contains two snapshots of the data stored at the specified path: one with the original data prior to the change, and one with the new data.

And going through the What can I do with Cloud Functions?, theres Notifying users:

Notify users when something interesting happens

Developers can use Cloud Functions to keep users engaged and up to date with relevant information about an app. Consider, for example, an app that allows users to follow one another's activities in the app. In such an app, a function triggered by Realtime Database writes to store new followers could create Firebase Cloud Messaging (FCM) notifications to let the appropriate users know that they have gained new followers.

The function triggers on writes to the Realtime Database path where followers are stored.

The function composes a message to send via FCM.

FCM sends the notification message to the user's device.

To review working code, see Send FCM notifications.

Other interesting notification use cases

Send confirmation emails to users subscribing/unsubscribing to a newsletter.

Send a welcome email when a user completes signup.

Send an SMS confirmation when a user creates a new account.


问:
use lookahead to match a string that starts and ends with a quotes and strip the quotes?
I'd like to match on strings that start and end with the same quote, but only with the quotes at the start and end:

```<code>"foo bar"
'foo bar'
"the quick brown fox"
</code>```

But I don't want these matched or stripped:

```<code>foo "bar"
foo 'bar'
'foo bar"
"the lazy" dogs
</code>```

I tried with this java regexp but it doesn't quite work for all the cases:

```<code>Pattern.compile("^\"|^'(.+)\"$|'$").matcher(quotedString).replaceAll("");
</code>```

I think there is a way to do lookahead, but I don't know how to use it in this case.

Or would it be more efficient to set up an if statement that checks them separately?

```<code>Pattern startPattern = Pattern.compile("^\"|^');
Pattern endPattern = Pattern.compile(\"$|'$");

if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) {
    ...
}
</code>```

(of course, this would match 'foo bar", which I do not want)

答:
The regex you're looking for is

```<code>^(["'])(.*)\1$
</code>```

with the replacement string being "$2":

```<code>Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$");
String output = pattern.matcher(input).replaceAll("$2");
</code>```

Demo: https://ideone.com/3a5PET

Body:
I'd like to match on strings that start and end with the same quote, but only with the quotes at the start and end:

"foo bar"
'foo bar'
"the quick brown fox"

But I don't want these matched or stripped:

foo "bar"
foo 'bar'
'foo bar"
"the lazy" dogs

I tried with this java regexp but it doesn't quite work for all the cases:

Pattern.compile("^\"|^'(.+)\"$|'$").matcher(quotedString).replaceAll("");

I think there is a way to do lookahead, but I don't know how to use it in this case.

Or would it be more efficient to set up an if statement that checks them separately?

Pattern startPattern = Pattern.compile("^\"|^');
Pattern endPattern = Pattern.compile(\"$|'$");

if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) {
    ...
}

(of course, this would match 'foo bar", which I do not want)

Body:
The regex you're looking for is

^(["'])(.*)\1$

with the replacement string being "$2":

Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$");
String output = pattern.matcher(input).replaceAll("$2");

Demo: https://ideone.com/3a5PET


问:
boxing unboxing, cglib, spring and NoSuchMethodError mystery
I use Spring and GWt in my project. In few cases I've got a NoSuchMethodError thrown by CGLIB when I invoke a method of a spring bean proxy.

If I look at the error, It shows me that it tries to find a method with Integer object instead basic int fields.

For example, I've got a method which is defined like that in my spring bean

```<code>public void saveObject(int value)
{
// some stuff
}
</code>```

When I call this method an error is thrown : NoSuchMethodError which indicates it tries to find method saveObject with a field java.lang.Integer and not a basic int field (with I key)

What's the problem ? is there boxing/unboxing problems ? I precise that I call this method with a basic int and not an Integer.

答: Are you using cglib-nodep? That has worked for me in the past. Also check the version of cglib that you are using and try to use the latest one.</p>

Body:
I use Spring and GWt in my project. In few cases I've got a NoSuchMethodError thrown by CGLIB when I invoke a method of a spring bean proxy.

If I look at the error, It shows me that it tries to find a method with Integer object instead basic int fields.

For example, I've got a method which is defined like that in my spring bean

public void saveObject(int value)
{
// some stuff
}

When I call this method an error is thrown : NoSuchMethodError which indicates it tries to find method saveObject with a field java.lang.Integer and not a basic int field (with I key)

What's the problem ? is there boxing/unboxing problems ? I precise that I call this method with a basic int and not an Integer.


问:
How to use Flasgger with Flask applications using Blueprints?
I am adding Swagger UI to my Python Flask application using Flasgger. Most common examples on the Internet are for the basic Flask style using @app.route:

```<code>from flasgger.utils import swag_from

@app.route('/api/<string:username>')
@swag_from('path/to/external_file.yml')
def get(username):
    return jsonify({'username': username})
</code>```

That works.

In my application however, I am not using @app.route decorators to define the endpoints. I am using flask Blueprints. Like following:

```<code>from flask import Flask, Blueprint
from flask_restful import Api, Resource
from flasgger.utils import swag_from
...

class TestResourceClass(Resource):

      @swag_from('docs_test_get.yml', endpoint='test')
      def get() :
         print "This is the get method for GET /1.0/myapi/test endpoint"

app = Flask(__name__)
my_api_blueprint = Blueprint('my_api', __name__)
my_api = Api(my_api_blueprint)

app.register_blueprint(my_api_blueprint, url_prefix='/1.0/myapi/')

my_api.add_resource(TestResourceClass, '/test/'
                        endpoint='test',
                        methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
....
</code>```

As seen above, I used @swag_from decorator on the TestResourceClass.get() method which is bound to the GET method endpoint. I also have the endpoint=test  matching in the two places.

But I am not getting anything on the Swagger UI, it is all blank. The docs_test_get.yml file does contain the valid yaml markup to define the swagger spec.

What am I missing? How can I get Flasgger Swagger UI working with Flask Blueprint based setup?

答: Seems flasgger does not work or has no proper support for blue print style Flask definitions (yet). I used https://github.com/rantav/flask-restful-swagger which worked great!</p>

Body:
I am adding Swagger UI to my Python Flask application using Flasgger. Most common examples on the Internet are for the basic Flask style using @app.route:

from flasgger.utils import swag_from

@app.route('/api/<string:username>')
@swag_from('path/to/external_file.yml')
def get(username):
    return jsonify({'username': username})

That works.

In my application however, I am not using @app.route decorators to define the endpoints. I am using flask Blueprints. Like following:

from flask import Flask, Blueprint
from flask_restful import Api, Resource
from flasgger.utils import swag_from
...

class TestResourceClass(Resource):

      @swag_from('docs_test_get.yml', endpoint='test')
      def get() :
         print "This is the get method for GET /1.0/myapi/test endpoint"

app = Flask(__name__)
my_api_blueprint = Blueprint('my_api', __name__)
my_api = Api(my_api_blueprint)

app.register_blueprint(my_api_blueprint, url_prefix='/1.0/myapi/')

my_api.add_resource(TestResourceClass, '/test/'
                        endpoint='test',
                        methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
....

As seen above, I used @swag_from decorator on the TestResourceClass.get() method which is bound to the GET method endpoint. I also have the endpoint=test  matching in the two places.

But I am not getting anything on the Swagger UI, it is all blank. The docs_test_get.yml file does contain the valid yaml markup to define the swagger spec.

What am I missing? How can I get Flasgger Swagger UI working with Flask Blueprint based setup?


问:
Calculate performance based on rating in another table
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

```<code>CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000
</code>```

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

```<code>Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000
</code>```

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

答:
First get the Performance Rating table in a way such that each record has Range and corresponding Rating.
Then join the Sales data based on the Performance Range and calculate the final performance.

```<code>with
RangePerformance as
(
select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating
)
select  sales.Date, sales.Revenue, sales.Revenue*RangePerformance.Percentage
from sales
join RangePerformance
on sales.Revenue between RangePerformance.LowVal and RangePerformance.HighVal
</code>```

Breaking it down

```<code>select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating
</code>```

will give you the intermediate result set:

```<code>0     20000 1.1
20000 30000 1.2
30000 40000 1.3
</code>```

Then join this result set to Sales table based on Join condition of Sales Revenue falling within any range in above set.

Body:
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

Body:
First get the Performance Rating table in a way such that each record has Range and corresponding Rating.
Then join the Sales data based on the Performance Range and calculate the final performance.

with
RangePerformance as
(
select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating
)
select  sales.Date, sales.Revenue, sales.Revenue*RangePerformance.Percentage
from sales
join RangePerformance
on sales.Revenue between RangePerformance.LowVal and RangePerformance.HighVal

Breaking it down

select lag(Revenue, 1, 0) over (order by Revenue) LowVal, Revenue HighVal, Percentage
from Rating

will give you the intermediate result set:

0     20000 1.1
20000 30000 1.2
30000 40000 1.3

Then join this result set to Sales table based on Join condition of Sales Revenue falling within any range in above set.


问:
How to convert the following code to Java 8 Stream?
I was wondered if it is possible to convert the following code to Java 8 Stream?

```<code>List<Borg> newBorgMembers = new ArrayList<>();

// mankind is a List<Individual>
mankind.forEach(id -> newBorgMembers.add(new Borg(id)));
</code>```

Desired structure:

```<code>List<Borg> newBorgMembers = mankind.stream().filter().map().collect()
</code>```

This question is from a tutorial, the hints are using filter and map. The difficulty to me is that how to add elements without initiate an empty holder List<Borg>.

答:
Here is a small piece of code for your stream. </p>

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTest {

    public static void main(String[] args) {
        // Initialize mankind
        List<Individual> mankind = new ArrayList<>();
        mankind.add(new Individual("A"));
        mankind.add(new Individual("B"));
        mankind.add(new Individual("C"));

        // The stream
        List<Borg> newBorgMembers = mankind.stream().map(individual -> new Borg(individual.id)).collect(Collectors.toList());

        newBorgMembers.forEach(borg -> System.out.println(borg.id));
    }
}

class Individual {
    String id;
    public Individual(String id) {
        this.id = id;
    }

}
class Borg {
    String id;

    public Borg(String id) {
        this.id = id;
    }

}
</code>```

Body:
I was wondered if it is possible to convert the following code to Java 8 Stream?

List<Borg> newBorgMembers = new ArrayList<>();

// mankind is a List<Individual>
mankind.forEach(id -> newBorgMembers.add(new Borg(id)));

Desired structure:

List<Borg> newBorgMembers = mankind.stream().filter().map().collect()

This question is from a tutorial, the hints are using filter and map. The difficulty to me is that how to add elements without initiate an empty holder List<Borg>.

Body:
Here is a small piece of code for your stream.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTest {

    public static void main(String[] args) {
        // Initialize mankind
        List<Individual> mankind = new ArrayList<>();
        mankind.add(new Individual("A"));
        mankind.add(new Individual("B"));
        mankind.add(new Individual("C"));

        // The stream
        List<Borg> newBorgMembers = mankind.stream().map(individual -> new Borg(individual.id)).collect(Collectors.toList());

        newBorgMembers.forEach(borg -> System.out.println(borg.id));
    }
}

class Individual {
    String id;
    public Individual(String id) {
        this.id = id;
    }

}
class Borg {
    String id;

    public Borg(String id) {
        this.id = id;
    }

}


问:
Servicem8 API - Staff Jobs are scheduled to
We are building an integration between Servicem8 and Unleashed and I'm trying to find out if we can get the staff member the job is scheduled to via the Servicem8 API.

If not, is there another way for us to identify the staff member?

答:
You can determine if a job is scheduled by querying the jobActivity endpoint. Records with activity_was_scheduled == 1 are scheduled bookings (records with activity_was_scheduled == 0 are check-ins recorded for the job).

JobActivity records have a staff_uuid property which tells you the Staff member assigned to that scheduled booking.

```<code>GET https://api.servicem8.com/api_1.0/JobActivity.json?%24filter=job_uuid%20eq%20'your_job_uuid_here'
</code>```

Note that you can have multiple scheduled bookings per job, each assigned to different staff.

Body:
You can determine if a job is scheduled by querying the jobActivity endpoint. Records with activity_was_scheduled == 1 are scheduled bookings (records with activity_was_scheduled == 0 are check-ins recorded for the job).

JobActivity records have a staff_uuid property which tells you the Staff member assigned to that scheduled booking.

GET https://api.servicem8.com/api_1.0/JobActivity.json?%24filter=job_uuid%20eq%20'your_job_uuid_here'

Note that you can have multiple scheduled bookings per job, each assigned to different staff.


问:
Windows bat: loop files in directories
I'm working on Windows. I have many jpg files in subdirectories of a directory. I don't know exactly the architecture of the directory, meaning that I don't know how many levels the subdirectories have. What I need to do is to process jpg files according to their paths. Here is an example:

```<code>dir
 |---sub dir1
 |      |-----sub dir11
 |               |-----a.jpg
 |               |-----b.jpg
 |---sub dir2
        |-----c.jpg
        |-----d.jpg
</code>```

So I need to execute commands as below:

```<code>process.bat C:\dir\sub dir1\sub dir11\a.jpg C:\dir\sub dir1\sub dir11\b.jpg
process.bat C:\dir\sub dir2\c.jpg C:\dir\sub dir2\d.jpg
</code>```

I don't know how to write such a bat file especially a bat processing paths contains spaces. I don't know if spaces will make some trouble.

I've tried as below but it doesn't work:

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /f %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat %%~fA\*.jpg
)

pause
</code>```

When I execute the script, I get the result as below:

```<code>process.bat C:\dir\sub dir1\*.jpg
process.bat C:\dir\sub dir2\*.jpg
</code>```

It seems that * is regarded as a normal character.

答:
```<code>If defined Files echo process.bat !files!
</code>```

should solve the problem - but whether process.bat will co-operate is yet to be determined. Would need you to list process.bat if required.

Title: Windows bat: loop files in directories

Body:
I'm working on Windows. I have many jpg files in subdirectories of a directory. I don't know exactly the architecture of the directory, meaning that I don't know how many levels the subdirectories have. What I need to do is to process jpg files according to their paths. Here is an example:

dir
 |---sub dir1
 |      |-----sub dir11
 |               |-----a.jpg
 |               |-----b.jpg
 |---sub dir2
        |-----c.jpg
        |-----d.jpg

So I need to execute commands as below:

process.bat C:\dir\sub dir1\sub dir11\a.jpg C:\dir\sub dir1\sub dir11\b.jpg
process.bat C:\dir\sub dir2\c.jpg C:\dir\sub dir2\d.jpg

I don't know how to write such a bat file especially a bat processing paths contains spaces. I don't know if spaces will make some trouble.

I've tried as below but it doesn't work:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /f %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat %%~fA\*.jpg
)

pause

When I execute the script, I get the result as below:

process.bat C:\dir\sub dir1\*.jpg
process.bat C:\dir\sub dir2\*.jpg

It seems that * is regarded as a normal character.

Body:
If defined Files echo process.bat !files!

should solve the problem - but whether process.bat will co-operate is yet to be determined. Would need you to list process.bat if required.


问:
upload_max_filesize set to 4M in phpinfo(), can't change it!
I've got this in my php.ini

```<code>upload_max_filesize = 25M
post_max_size = 25M
</code>```

and I've got this in my .htaccess

```<code>php_value upload_max_filesize 26214400
php_value post_max_size 26214400
</code>```

as shorthand can only be used in the php.ini (http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes)

but no matter what I do, when i call phpinfo() I get

```<code>Directive               Local Value     Master Value
upload_max_filesize     4M              25M
</code>```

I've looked at all other php.ini files, my .htaccess, ini_set(). Anything I could think of and nothing will change it from 4M. Any help would be great!

EDIT: restarting apache didn't work, i've check my httpd.conf, it seems like an external file or something. any other places to check?

答: Make sure that you're editing the php.ini in the conf/"server_version" folder

Body:
I've got this in my php.ini

upload_max_filesize = 25M
post_max_size = 25M

and I've got this in my .htaccess

php_value upload_max_filesize 26214400
php_value post_max_size 26214400

as shorthand can only be used in the php.ini (http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes)

but no matter what I do, when i call phpinfo() I get

Directive               Local Value     Master Value
upload_max_filesize     4M              25M

I've looked at all other php.ini files, my .htaccess, ini_set(). Anything I could think of and nothing will change it from 4M. Any help would be great!

EDIT: restarting apache didn't work, i've check my httpd.conf, it seems like an external file or something. any other places to check?