问:
Android checkbox and text box on top of the other
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<!-- quick and dirty divider -->
<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>
</code>```

I would be happy if someone can help me to fix this problem. Thanks.

答:
Try it.</p>

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="horizontal">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World"/>
    </LinearLayout>
</RelativeLayout>
</code>```

Body:
I have the following FrameLayout, this layout is used to my RecyclerView as the rows. In etch row I have text box and checkbox. The problem is the checkbox and the text box are connected to each other and the checkbox on the top of the text and it's hide the text box.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="56dp"
android:focusable="false"
>

<Button
    android:id="@+id/undo_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_undo"
    android:textAllCaps="true"
    android:textColor="@android:color/white"
    android:layout_gravity="end|center_vertical"
    style="@style/Base.Widget.AppCompat.Button.Borderless"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"
    android:layout_gravity="bottom"
    />

<TextView
    android:id="@+id/title_text_view"
    android:layout_width="323dp"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:allowUndo="true"
    android:elevation="0dp"
    android:gravity="center_vertical"
    android:textSize="16sp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/CheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</FrameLayout>

I would be happy if someone can help me to fix this problem. Thanks.

Body:
Try it.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="horizontal">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World"/>
    </LinearLayout>
</RelativeLayout>


来源: stackexchange

问:
problem with unix date util running in emacs shell
here's a oddity.

on Cygwin bash on Windows Vista, i can get date like this:

```<code>$ date
2010-11-30  4:40:48 AM PST

xah@xah-PC ~
$ date +%s
1291120855
</code>```

but in emacs “shell”, running the same date command, i get this:

```<code>c:\Users\xah\web\xahlee_org\comp>which date
which date
/usr/bin/date

c:\Users\xah\web\xahlee_org\comp>date
date
The current date is: 2010-11-30
Enter the new date: (yy-mm-dd)

c:\Users\xah\web\xahlee_org\comp>date +%s
date +%s
The system cannot accept the date entered.
Enter the new date: (yy-mm-dd)
</code>```

any idea what's going on?

答:
This is because your emacs shell is actually a Windows Command Prompt shell and the date command gets sent to it and fails.

Take a look at this question to find out how you can configure emacs to use Cygwin's bash shell instead:

How can I run Cygwin Bash Shell from within Emacs?

ContentLicense: CC BY-SA 2.5

Body:
here's a oddity.

on Cygwin bash on Windows Vista, i can get date like this:

$ date
2010-11-30  4:40:48 AM PST

xah@xah-PC ~
$ date +%s
1291120855

but in emacs “shell”, running the same date command, i get this:

c:\Users\xah\web\xahlee_org\comp>which date
which date
/usr/bin/date

c:\Users\xah\web\xahlee_org\comp>date
date
The current date is: 2010-11-30
Enter the new date: (yy-mm-dd)

c:\Users\xah\web\xahlee_org\comp>date +%s
date +%s
The system cannot accept the date entered.
Enter the new date: (yy-mm-dd)

any idea what's going on?


问:
How to Auto Inject Dependency with Laravel
I'm trying to build a structure that uses dependency injection on lumen.

I Have a Service Layer and repository layer.

I want to inject the repository layer to service layer. Let me try to show you the code

```<code>    interface IUserRepostitory {
        public function getByID($id);
    }

    class UserRepository extends BaseRepository implements IRepository{
        public function getByID($id) {
            //Please don't think how this function works, my question about dependency injection
            return $this->findOrFail($id);
        }

    }

   interface IService {
       public function getByID($id);
   }

   class UserService implements IService{

       private $Repository;
       public __construct(IUserRepositor $UserRepository) {
            $this->Repository = $UserRepository
       }

       public function getByID($id) {
             return $this->Repository->getByID($id);
       }
   }
</code>```

Here I'm registering the dependency resolver.

```<code>//Dependency resolver for Repository Layer
class RepositoryServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserRepository::class, function () {
            return new UserRepository();
        });
    }

}
</code>```

Here I'm registering Service Layer

```<code>class ServiceServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserService::class, function () {
            //Here is what I don't like
            //It would be great a solution that automaticly resolve UserRepository.
            return new UserService(new UserRepository());
        });
    }
}
</code>```

As you see, I want to auto resolve the dependency into UserService. But singleton method need to create the returning object.

Is there a better way for this?

*** note : please don't pay attention on syntax, I'm writing it on lumen but the same problem on laravel.

答:
Once you bind the UserRepository to the IUserRepository, you may then instantiate the IUserService with the IUserRepository by resolving with the make function!

Modifying your ServiceServiceProvider as such:

```<code>class ServiceServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(IUserService::class, function ($app) {
            return new UserService($app->make(IUserRepository::class));
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build a structure that uses dependency injection on lumen.

I Have a Service Layer and repository layer.

I want to inject the repository layer to service layer. Let me try to show you the code

    interface IUserRepostitory {
        public function getByID($id);
    }

    class UserRepository extends BaseRepository implements IRepository{
        public function getByID($id) {
            //Please don't think how this function works, my question about dependency injection
            return $this->findOrFail($id);
        }

    }

   interface IService {
       public function getByID($id);
   }

   class UserService implements IService{

       private $Repository;
       public __construct(IUserRepositor $UserRepository) {
            $this->Repository = $UserRepository
       }

       public function getByID($id) {
             return $this->Repository->getByID($id);
       }
   }

Here I'm registering the dependency resolver.

//Dependency resolver for Repository Layer
class RepositoryServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserRepository::class, function () {
            return new UserRepository();
        });
    }

}

Here I'm registering Service Layer

class ServiceServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserService::class, function () {
            //Here is what I don't like
            //It would be great a solution that automaticly resolve UserRepository.
            return new UserService(new UserRepository());
        });
    }
}

As you see, I want to auto resolve the dependency into UserService. But singleton method need to create the returning object.

Is there a better way for this?

*** note : please don't pay attention on syntax, I'm writing it on lumen but the same problem on laravel.

Body:
Once you bind the UserRepository to the IUserRepository, you may then instantiate the IUserService with the IUserRepository by resolving with the make function!

Modifying your ServiceServiceProvider as such:

class ServiceServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(IUserService::class, function ($app) {
            return new UserService($app->make(IUserRepository::class));
        });
    }
}


问:
running esdoc's got error
to generate document i want to use esdoc

esdoc -c esdoc.json

esdoc.json

```<code>{
   "source": "./src/",
   "destination": "./doc"
}
</code>```

./src/index.js

```<code>/**
* @type {Object}
* @property {boolean} Foo.info
*/
var Foo = {
    info: true
};

export default Foo;
</code>```

but it shows

```<code>\node_modules\esdoc\out\src\ESDoc.js:121
  results.push(...temp.results);
               ^^^

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
</code>```

what did i wrong?

答:
As one of the answers indicated, upgrade your node version - Had a similar problem and I did following (note I am on Mac OS X)

```
    brew upgrade node
    brew upgrade npm
    sudo npm cache clean -f
    sudo npm install -g n
    nvm install 7.8.0
    npm install -g esdoc
```

finally If you run

```
    esdoc
```

It should give you doc directory as expected; Hope it clarifies and helps others ...

Title: running esdoc's got error

Body:
to generate document i want to use esdoc

esdoc -c esdoc.json

esdoc.json

{
   "source": "./src/",
   "destination": "./doc"
}

./src/index.js

/**
* @type {Object}
* @property {boolean} Foo.info
*/
var Foo = {
    info: true
};

export default Foo;

but it shows

\node_modules\esdoc\out\src\ESDoc.js:121
  results.push(...temp.results);
               ^^^

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)

what did i wrong?

Body:
As one of the answers indicated, upgrade your node version - Had a similar problem and I did following (note I am on Mac OS X)

    brew upgrade node
    brew upgrade npm
    sudo npm cache clean -f
    sudo npm install -g n
    nvm install 7.8.0
    npm install -g esdoc

finally If you run

    esdoc

It should give you doc directory as expected; Hope it clarifies and helps others ...


问:
elasticsearch dsl python unpack q queries
How can I dynamically create a combined Q query in elasticsearch dsl python?
I have gone through docs and this SO post. I constructed a q_query dictionary with all required info.

```<code>ipdb> q_queries
{'queries': [{'status': 'PASS'}, {'status': 'FAIL'}, {'status': 'ABSE'}, {'status': 'WITH'}], 'operation': 'or'}
</code>```

I want to perform the following q_query

```<code>qq=Q("match", status='PASS') | Q("match", status="FAIL") | Q("match", status="ABSE") | Q("match", status="WITH")
</code>```

for a list of dict following works out

```<code>ipdb> [Q('match', **z) for z in q_queries['queries']]
[Match(status='PASS'), Match(status='FAIL'), Match(status='ABSE'), Match(status='WITH')]
</code>```

But How to combine multiple Qs with an or operator or an and operator? Also what is the corresponding elasticsearch raw query for the above? I tried following since I have to filter based on test_id.

```<code>{
  "query": {
    "bool": {
      "must":     [
        { "match": { "test_id": "7" }},
        {
          "range": {
            "created": {
              "gte": "2016-01-01",
              "lte": "2016-01-31"
            }
          }
        }
        ],
      "should": [
                  { "match": { "status": "PASS"}},
                  { "match": { "status": "FAIL"}}
      ]
    }
  }
}
</code>```

But results are not as expected I same query without should filter and the results obtained were the same. So should filters were not executed by elasticsearch in my case.
Any help is much appreciated.

TIA

答:
After exploring elasticsearch dsl python for some more time, this piece of documentation helped me to solve above issue. Below posted is the function that I wrote to resolve this issue.

```<code>def create_q_queries(self, q_queries, search_query):
    """
    create q queries and chain if multiple q queries.
    :param q_queries: Q queries with operation and query params as a dict.
    :param search_query: Search() object.
    :return: search_query updated with q queries.
    """
    if q_queries:
        logical_operator_mappings = {'or': 'should', 'and': 'must'}
        for query in q_queries:
            queries = [Q('match', **query) for query in query['queries']]
            search_query = search_query.query(Q('bool', **{
                logical_operator_mappings.get(query.get('operation')): queries
            }))
    return search_query
</code>```

I changed format of q_queries to perform chaining based on multiple operators like and, or etc.

```<code>q_queries = [
              {
                "operation": "or",
                "queries":
                  [
                    {"status": "PASS"}, {"status": "FAIL"}, {"status": "ABSE"}, {"status": "WITH"}
                  ]
                }

             ]
</code>```

Body:
How can I dynamically create a combined Q query in elasticsearch dsl python?
I have gone through docs and this SO post. I constructed a q_query dictionary with all required info.

ipdb> q_queries
{'queries': [{'status': 'PASS'}, {'status': 'FAIL'}, {'status': 'ABSE'}, {'status': 'WITH'}], 'operation': 'or'}

I want to perform the following q_query

qq=Q("match", status='PASS') | Q("match", status="FAIL") | Q("match", status="ABSE") | Q("match", status="WITH")

for a list of dict following works out

ipdb> [Q('match', **z) for z in q_queries['queries']]
[Match(status='PASS'), Match(status='FAIL'), Match(status='ABSE'), Match(status='WITH')]

But How to combine multiple Qs with an or operator or an and operator? Also what is the corresponding elasticsearch raw query for the above? I tried following since I have to filter based on test_id.

{
  "query": {
    "bool": {
      "must":     [
        { "match": { "test_id": "7" }},
        {
          "range": {
            "created": {
              "gte": "2016-01-01",
              "lte": "2016-01-31"
            }
          }
        }
        ],
      "should": [
                  { "match": { "status": "PASS"}},
                  { "match": { "status": "FAIL"}}
      ]
    }
  }
}

But results are not as expected I same query without should filter and the results obtained were the same. So should filters were not executed by elasticsearch in my case.
Any help is much appreciated.

TIA

Body:
After exploring elasticsearch dsl python for some more time, this piece of documentation helped me to solve above issue. Below posted is the function that I wrote to resolve this issue.

def create_q_queries(self, q_queries, search_query):
    """
    create q queries and chain if multiple q queries.
    :param q_queries: Q queries with operation and query params as a dict.
    :param search_query: Search() object.
    :return: search_query updated with q queries.
    """
    if q_queries:
        logical_operator_mappings = {'or': 'should', 'and': 'must'}
        for query in q_queries:
            queries = [Q('match', **query) for query in query['queries']]
            search_query = search_query.query(Q('bool', **{
                logical_operator_mappings.get(query.get('operation')): queries
            }))
    return search_query

I changed format of q_queries to perform chaining based on multiple operators like and, or etc.

q_queries = [
              {
                "operation": "or",
                "queries":
                  [
                    {"status": "PASS"}, {"status": "FAIL"}, {"status": "ABSE"}, {"status": "WITH"}
                  ]
                }

             ]


问:
pip install error: ModuleNotFoundError No module named 'setuptools'
When I run pip install virtualenvwrapper-win in a PowerShell console I get the error:

PS C:\Windows\system32> pip install virtualenvwrapper-win
  Collecting virtualenvwrapper-win
    Using cached virtualenvwrapper-win-1.2.1.zip
      Complete output from command python setup.py egg_info:
      Traceback (most recent call last):
        File "", line 1, in
      ModuleNotFoundError: No module named 'setuptools'

Command "python setup.py egg_info" failed with error code 1 in

I've tried doing pip install setuptools and also tried uninstalling and reinstalling and update but the error persists.

pip and python executables have been added to environment variables.

答:
Try installing the virtualenvwrapper-win module manually by downloading the ZIP archive from here:
https://pypi.python.org/pypi/virtualenvwrapper-win

In your PowerShell console, go to the directory the archive downloaded to (mine goes to C:\Users\user\Downloads\) and run this to extract the archive: Expand-Archive .\virtualenvwrapper-win-1.2.1.zip

Still in PowerShell and in the same directory as above, run: cd .\virtualenvwrapper-win-1.2.1\virtualenvwrapper-win-1.2.1\

Next, run: python setup.py install

If all went well, you should see something like this:

```<code>    PS C:\Users\user\Downloads\virtualenvwrapper-win-1.2.1\virtualenvwrapper-win-1.2.1> python .\setup.py install
    running install
    running bdist_egg
    running egg_info
    writing virtualenvwrapper_win.egg-info\PKG-INFO
    writing dependency_links to virtualenvwrapper_win.egg-info\dependency_links.txt
    writing requirements to virtualenvwrapper_win.egg-info\requires.txt
    writing top-level names to virtualenvwrapper_win.egg-info\top_level.txt
    reading manifest file 'virtualenvwrapper_win.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'virtualenvwrapper_win.egg-info\SOURCES.txt'
    installing library code to build\bdist.win-amd64\egg
    running install_lib
    warning: install_lib: 'build\lib' does not exist -- no Python modules to install

    creating build
    creating build\bdist.win-amd64
    creating build\bdist.win-amd64\egg
    creating build\bdist.win-amd64\egg\EGG-INFO
    installing scripts to build\bdist.win-amd64\egg\EGG-INFO\scripts
    running install_scripts
    running build_scripts
    creating build\scripts-3.6
    copying scripts\add2virtualenv.bat -> build\scripts-3.6
    copying scripts\cd-.bat -> build\scripts-3.6
    copying scripts\cdproject.bat -> build\scripts-3.6
    copying scripts\cdsitepackages.bat -> build\scripts-3.6
    copying scripts\cdvirtualenv.bat -> build\scripts-3.6
    copying scripts\folder_delete.bat -> build\scripts-3.6
    copying scripts\lssitepackages.bat -> build\scripts-3.6
    copying scripts\lsvirtualenv.bat -> build\scripts-3.6
    copying scripts\mkvirtualenv.bat -> build\scripts-3.6
    copying scripts\rmvirtualenv.bat -> build\scripts-3.6
    copying scripts\setprojectdir.bat -> build\scripts-3.6
    copying scripts\toggleglobalsitepackages.bat -> build\scripts-3.6
    copying scripts\whereis.bat -> build\scripts-3.6
    copying scripts\workon.bat -> build\scripts-3.6
    creating build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\add2virtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cd-.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdproject.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdsitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\folder_delete.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\lssitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\lsvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\mkvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\rmvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\setprojectdir.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\toggleglobalsitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\whereis.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\workon.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying virtualenvwrapper_win.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\not-zip-safe -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\requires.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO
    creating dist
    creating 'dist\virtualenvwrapper_win-1.2.1-py3.6.egg' and adding 'build\bdist.win-amd64\egg' to it
    removing 'build\bdist.win-amd64\egg' (and everything under it)
    Processing virtualenvwrapper_win-1.2.1-py3.6.egg
    creating c:\users\user\appdata\local\programs\python\python36\lib\site-packages\virtualenvwrapper_win-1.2.1-py3.6.egg
    Extracting virtualenvwrapper_win-1.2.1-py3.6.egg to c:\users\user\appdata\local\programs\python\python36\lib\site-packages
    Adding virtualenvwrapper-win 1.2.1 to easy-install.pth file
    Installing add2virtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cd-.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdproject.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdsitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing folder_delete.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing lssitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing lsvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing mkvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing rmvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing setprojectdir.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing toggleglobalsitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing whereis.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing workon.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts

    Installed c:\users\user\appdata\local\programs\python\python36\lib\site-packages\virtualenvwrapper_win-1.2.1-py3.6.egg
    Processing dependencies for virtualenvwrapper-win==1.2.1
    Searching for virtualenv==15.1.0
    Best match: virtualenv 15.1.0
    Adding virtualenv 15.1.0 to easy-install.pth file
    Installing virtualenv-script.py script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing virtualenv.exe script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts

    Using c:\users\user\appdata\local\programs\python\python36\lib\site-packages
    Finished processing dependencies for virtualenvwrapper-win==1.2.1
</code>```

Body:
Try installing the virtualenvwrapper-win module manually by downloading the ZIP archive from here:
https://pypi.python.org/pypi/virtualenvwrapper-win

In your PowerShell console, go to the directory the archive downloaded to (mine goes to C:\Users\user\Downloads\) and run this to extract the archive: Expand-Archive .\virtualenvwrapper-win-1.2.1.zip

Still in PowerShell and in the same directory as above, run: cd .\virtualenvwrapper-win-1.2.1\virtualenvwrapper-win-1.2.1\

Next, run: python setup.py install

If all went well, you should see something like this:

    PS C:\Users\user\Downloads\virtualenvwrapper-win-1.2.1\virtualenvwrapper-win-1.2.1> python .\setup.py install
    running install
    running bdist_egg
    running egg_info
    writing virtualenvwrapper_win.egg-info\PKG-INFO
    writing dependency_links to virtualenvwrapper_win.egg-info\dependency_links.txt
    writing requirements to virtualenvwrapper_win.egg-info\requires.txt
    writing top-level names to virtualenvwrapper_win.egg-info\top_level.txt
    reading manifest file 'virtualenvwrapper_win.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'virtualenvwrapper_win.egg-info\SOURCES.txt'
    installing library code to build\bdist.win-amd64\egg
    running install_lib
    warning: install_lib: 'build\lib' does not exist -- no Python modules to install

    creating build
    creating build\bdist.win-amd64
    creating build\bdist.win-amd64\egg
    creating build\bdist.win-amd64\egg\EGG-INFO
    installing scripts to build\bdist.win-amd64\egg\EGG-INFO\scripts
    running install_scripts
    running build_scripts
    creating build\scripts-3.6
    copying scripts\add2virtualenv.bat -> build\scripts-3.6
    copying scripts\cd-.bat -> build\scripts-3.6
    copying scripts\cdproject.bat -> build\scripts-3.6
    copying scripts\cdsitepackages.bat -> build\scripts-3.6
    copying scripts\cdvirtualenv.bat -> build\scripts-3.6
    copying scripts\folder_delete.bat -> build\scripts-3.6
    copying scripts\lssitepackages.bat -> build\scripts-3.6
    copying scripts\lsvirtualenv.bat -> build\scripts-3.6
    copying scripts\mkvirtualenv.bat -> build\scripts-3.6
    copying scripts\rmvirtualenv.bat -> build\scripts-3.6
    copying scripts\setprojectdir.bat -> build\scripts-3.6
    copying scripts\toggleglobalsitepackages.bat -> build\scripts-3.6
    copying scripts\whereis.bat -> build\scripts-3.6
    copying scripts\workon.bat -> build\scripts-3.6
    creating build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\add2virtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cd-.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdproject.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdsitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\cdvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\folder_delete.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\lssitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\lsvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\mkvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\rmvirtualenv.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\setprojectdir.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\toggleglobalsitepackages.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\whereis.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying build\scripts-3.6\workon.bat -> build\bdist.win-amd64\egg\EGG-INFO\scripts
    copying virtualenvwrapper_win.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\not-zip-safe -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\requires.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying virtualenvwrapper_win.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO
    creating dist
    creating 'dist\virtualenvwrapper_win-1.2.1-py3.6.egg' and adding 'build\bdist.win-amd64\egg' to it
    removing 'build\bdist.win-amd64\egg' (and everything under it)
    Processing virtualenvwrapper_win-1.2.1-py3.6.egg
    creating c:\users\user\appdata\local\programs\python\python36\lib\site-packages\virtualenvwrapper_win-1.2.1-py3.6.egg
    Extracting virtualenvwrapper_win-1.2.1-py3.6.egg to c:\users\user\appdata\local\programs\python\python36\lib\site-packages
    Adding virtualenvwrapper-win 1.2.1 to easy-install.pth file
    Installing add2virtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cd-.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdproject.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdsitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing cdvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing folder_delete.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing lssitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing lsvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing mkvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing rmvirtualenv.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing setprojectdir.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing toggleglobalsitepackages.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing whereis.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing workon.bat script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts

    Installed c:\users\user\appdata\local\programs\python\python36\lib\site-packages\virtualenvwrapper_win-1.2.1-py3.6.egg
    Processing dependencies for virtualenvwrapper-win==1.2.1
    Searching for virtualenv==15.1.0
    Best match: virtualenv 15.1.0
    Adding virtualenv 15.1.0 to easy-install.pth file
    Installing virtualenv-script.py script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts
    Installing virtualenv.exe script to C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts

    Using c:\users\user\appdata\local\programs\python\python36\lib\site-packages
    Finished processing dependencies for virtualenvwrapper-win==1.2.1


问:
Need to associate unique integer value with classes
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

```<code>type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;
</code>```

Testing this, I found out that I need to be super careful which class I declare. If I use this:

```<code>  var Fruit: TFruit;

  Fruit := TOrange.Create;
</code>```

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

答:
First, you need

```<code>type
  TFruit = class
  end;

  TApple = class(TFruit)
  end;

  TOrange = class(TFruit)
  end;
</code>```

and then you can use Fruit.ClassName and Fruit.ClassType, can't you?

```<code>function ClassToID(const Fruit: TFruit): word;
begin
  if Fruit is TApple then
    result := 1
  else if Fruit is TOrange then
    result := 2;
end;
</code>```

or

```<code>TFruitClass = class of TFruit;

type
  TFruitAndID = record
    FruitClass: TFruitClass;
    ID: word;
  end;

const FruitIDs: array[0..1] of TFruitAndID =
  ((FruitClass: TApple; ID: 1), (FruitClass: TOrange; ID: 2));

function ClassToID(Fruit: TFruit): word;
var
  i: Integer;
begin
  for i := 0 to high(FruitIDs) do
    if FruitIDs[i].FruitClass = Fruit.ClassType then
      Exit(FruitIDs[i].ID);
end;
</code>```

Body:
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;

Testing this, I found out that I need to be super careful which class I declare. If I use this:

  var Fruit: TFruit;

  Fruit := TOrange.Create;

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

Body:
First, you need

type
  TFruit = class
  end;

  TApple = class(TFruit)
  end;

  TOrange = class(TFruit)
  end;

and then you can use Fruit.ClassName and Fruit.ClassType, can't you?

function ClassToID(const Fruit: TFruit): word;
begin
  if Fruit is TApple then
    result := 1
  else if Fruit is TOrange then
    result := 2;
end;

or

TFruitClass = class of TFruit;

type
  TFruitAndID = record
    FruitClass: TFruitClass;
    ID: word;
  end;

const FruitIDs: array[0..1] of TFruitAndID =
  ((FruitClass: TApple; ID: 1), (FruitClass: TOrange; ID: 2));

function ClassToID(Fruit: TFruit): word;
var
  i: Integer;
begin
  for i := 0 to high(FruitIDs) do
    if FruitIDs[i].FruitClass = Fruit.ClassType then
      Exit(FruitIDs[i].ID);
end;


问:
HTTP status 404-Page not found. SpringMVC error
It is my first application in SpringMVC using Maven.
here is the application structure.

Controller code:

When I click on the link in the index.jsp the page should be traversed to helloworld.jsp

index.jsp has this link:

```<code>    <h3>
        <a href="hello?name=Eric">Click Here</a>
    </h3>
</code>```

helloworld.jsp

```<code>    <h2>
        ${message} ${name}
    </h2>
</code>```

The code for dispatcher servlet:

Update: web.xml file.

I understand that it's a silly question, but as a newbie to SpringMVC structure, I am not able to find the error. Please help!

Spring is starting up.
This is the homepage, when I click on the link, it should be traversed to helloworld.jsp.

And this is the pom.xml.

```<code> <project xmlns="http://maven.apache.org/POM/4.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</code>```

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

```<code>  <modelVersion>4.0.0</modelVersion>
 <groupId>demoproject</groupId>
 <artifactId>demoMVC</artifactId>

 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>demoMVC Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
    <spring.version>4.0.1.RELEASE</spring.version>
 </properties>
<dependencies>
 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
  </dependencies>
 <build>
   <finalName>demoMVC</finalName>
    <directory>${basedir}/target</directory>
       <plugins>
            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.3</version>
                 <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                      <showWarnings>true</showWarnings>
                 </configuration>
            </plugin>
       </plugins>
     </build>
   </project>
</code>```

Console:

```<code>  WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting    property 'source' to 'org.eclipse.jst.jee.server:demoMVC' did not find a matching property.
  Mar 31, 2017 1:22:08 PM org.apache.coyote.AbstractProtocol init
  INFO: Initializing ProtocolHandler ["http-bio-8080"]
  Mar 31, 2017 1:22:08 PM org.apache.coyote.AbstractProtocol init
  INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
  Mar 31, 2017 1:22:08 PM org.apache.catalina.startup.Catalina load
  INFO: Initialization processed in 1005 ms
  Mar 31, 2017 1:22:08 PM org.apache.catalina.core.StandardService startInternal
  INFO: Starting service Catalina
   Mar 31, 2017 1:22:08 PM org.apache.catalina.core.StandardEngine startInternal
   INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
   Mar 31, 2017 1:22:12 PM org.apache.catalina.core.ApplicationContext log
   INFO: No Spring WebApplicationInitializer types detected on classpath
   Mar 31, 2017 1:22:12 PM org.apache.coyote.AbstractProtocol start
   INFO: Starting ProtocolHandler ["http-bio-8080"]
   Mar 31, 2017 1:22:12 PM org.apache.coyote.AbstractProtocol start
  INFO: Starting ProtocolHandler ["ajp-bio-8009"]
   Mar 31, 2017 1:22:12 PM org.apache.catalina.startup.Catalina start
   INFO: Server startup in 3739 ms
</code>```

答:
In the logs you should see something like:

```<code>19:05:56,530 INFO  [io.undertow.servlet] (ServerService Thread Pool -- 106) Initializing Spring FrameworkServlet 'mvc-dispatcher'
19:05:56,531 INFO  [org.springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 106) FrameworkServlet 'mvc-dispatcher': initialization started
19:05:56,547 INFO  [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 106) Refreshing WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Fri Mar 31 19:05:56 UTC 2017]; root of context hierarchy
19:05:56,584 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (ServerService Thread Pool -- 106) Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
19:05:56,741 INFO  [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] (ServerService Thread Pool -- 106) JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
19:05:56,859 INFO  [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] (ServerService Thread Pool -- 106) Mapped "{[/hello],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto protected org.springframework.web.servlet.ModelAndView com.crramirez.HelloWorldController.showMessage(java.lang.String) throws java.lang.Exception
19:05:57,084 INFO  [org.springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 106) FrameworkServlet 'mvc-dispatcher': initialization completed in 553 ms
</code>```

Delete these lines in web.xml:

```<code><context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

and rename the file in WEB-INF from dispatcher-servlet.xml to mvc-dispatcher-servlet.xml

With this your program should work.

Body:
It is my first application in SpringMVC using Maven.
here is the application structure.

Controller code:

When I click on the link in the index.jsp the page should be traversed to helloworld.jsp

index.jsp has this link:

        Click Here

helloworld.jsp

        ${message} ${name}

The code for dispatcher servlet:

Update: web.xml file.

I understand that it's a silly question, but as a newbie to SpringMVC structure, I am not able to find the error. Please help!

Spring is starting up.
This is the homepage, when I click on the link, it should be traversed to helloworld.jsp.

And this is the pom.xml.

 <project xmlns="http://maven.apache.org/POM/4.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
 <groupId>demoproject</groupId>
 <artifactId>demoMVC</artifactId>

 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>demoMVC Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
    <spring.version>4.0.1.RELEASE</spring.version>
 </properties>
<dependencies>
 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
  </dependencies>
 <build>
   <finalName>demoMVC</finalName>
    <directory>${basedir}/target</directory>
       <plugins>
            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.3</version>
                 <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                      <showWarnings>true</showWarnings>
                 </configuration>
            </plugin>
       </plugins>
     </build>
   </project>

Console:

  WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting    property 'source' to 'org.eclipse.jst.jee.server:demoMVC' did not find a matching property.
  Mar 31, 2017 1:22:08 PM org.apache.coyote.AbstractProtocol init
  INFO: Initializing ProtocolHandler ["http-bio-8080"]
  Mar 31, 2017 1:22:08 PM org.apache.coyote.AbstractProtocol init
  INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
  Mar 31, 2017 1:22:08 PM org.apache.catalina.startup.Catalina load
  INFO: Initialization processed in 1005 ms
  Mar 31, 2017 1:22:08 PM org.apache.catalina.core.StandardService startInternal
  INFO: Starting service Catalina
   Mar 31, 2017 1:22:08 PM org.apache.catalina.core.StandardEngine startInternal
   INFO: Starting Servlet Engine: Apache Tomcat/7.0.34
   Mar 31, 2017 1:22:12 PM org.apache.catalina.core.ApplicationContext log
   INFO: No Spring WebApplicationInitializer types detected on classpath
   Mar 31, 2017 1:22:12 PM org.apache.coyote.AbstractProtocol start
   INFO: Starting ProtocolHandler ["http-bio-8080"]
   Mar 31, 2017 1:22:12 PM org.apache.coyote.AbstractProtocol start
  INFO: Starting ProtocolHandler ["ajp-bio-8009"]
   Mar 31, 2017 1:22:12 PM org.apache.catalina.startup.Catalina start
   INFO: Server startup in 3739 ms

Body:
In the logs you should see something like:

19:05:56,530 INFO  [io.undertow.servlet] (ServerService Thread Pool -- 106) Initializing Spring FrameworkServlet 'mvc-dispatcher'
19:05:56,531 INFO  [org.springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 106) FrameworkServlet 'mvc-dispatcher': initialization started
19:05:56,547 INFO  [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 106) Refreshing WebApplicationContext for namespace 'mvc-dispatcher-servlet': startup date [Fri Mar 31 19:05:56 UTC 2017]; root of context hierarchy
19:05:56,584 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (ServerService Thread Pool -- 106) Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
19:05:56,741 INFO  [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] (ServerService Thread Pool -- 106) JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
19:05:56,859 INFO  [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] (ServerService Thread Pool -- 106) Mapped "{[/hello],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto protected org.springframework.web.servlet.ModelAndView com.crramirez.HelloWorldController.showMessage(java.lang.String) throws java.lang.Exception
19:05:57,084 INFO  [org.springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 106) FrameworkServlet 'mvc-dispatcher': initialization completed in 553 ms

Delete these lines in web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

and rename the file in WEB-INF from dispatcher-servlet.xml to mvc-dispatcher-servlet.xml

With this your program should work.


问:
using nginx' lua to validate GitHub webhooks and delete cron-lock-file

What I have:

GNU/Linux host

nginx is up and running

there is a cron-job scheduled to run immediately after a specific file has been removed (similar to run-crons)

GitHub sends a webhook when someone pushes to a repository

What I want:

I do now want to run either lua or anything comparable to parse GitHub's request and validate it and then delete a file (if the request was valid of course).

Preferably all of this should happen without the hassle to maintain an additional PHP installation as there is currently none, or the need to use fcgiwrap or similar.

Template:

On the nginx side I have something equivalent to

```<code>location /deploy {
    # execute lua (or equivalent) here
}
</code>```

答:
To read json body of GH webhook you nead use JSON4Lua lib, and to validate HMAC signature use luacrypto.

Preconfigure

Install required modules

```<code>$ sudo luarocks install JSON4Lua
$ sudo luarocks install luacrypto
</code>```

In Nginx define location for deploy

```<code>  location /deploy {
    client_body_buffer_size 3M;
    client_max_body_size  3M;

    content_by_lua_file /path/to/handler.lua;
  }
</code>```

The max_body_size and body_buffer_size should be equal to prevent error

request body in temp file not supported

https://github.com/openresty/lua-nginx-module/issues/521

Process webhook

Get request payload data and check is correct

```<code>ngx.req.read_body()
local data = ngx.req.get_body_data()

if not data then
    ngx.log(ngx.ERR, "failed to get request body")
    return ngx.exit (ngx.HTTP_BAD_REQUEST)
end
</code>```

Verify GH signature with use luacrypto

```<code>local function verify_signature (hub_sign, data)
    local sign = 'sha1=' .. crypto.hmac.digest('sha1', data, secret)
    -- this is simple comparison, but it's better to use a constant time comparison
    return hub_sign == sign
end

-- validate GH signature
if not verify_signature(headers['X-Hub-Signature'], data) then
    ngx.log(ngx.ERR, "wrong webhook signature")
    return ngx.exit (ngx.HTTP_FORBIDDEN)
end
</code>```

Parse data as json and check is master branch, for deploy

```<code>data = json.decode(data)
-- on master branch
if data['ref'] ~= branch then
    ngx.say("Skip branch ", data['ref'])
    return ngx.exit (ngx.HTTP_OK)
end
</code>```

If all correct, call deploy function

```<code>local function deploy ()
    -- run command for deploy
    local handle = io.popen("cd /path/to/repo && sudo -u username git pull")
    local result = handle:read("*a")
    handle:close()

    ngx.say (result)
    return ngx.exit (ngx.HTTP_OK)
end
</code>```

Example

Example constant time string compare

```<code>local function const_eq (a, b)
    -- Check is string equals, constant time exec
    getmetatable('').__index = function (str, i)
        return string.sub(str, i, i)
    end

    local diff = string.len(a) == string.len(b)
    for i = 1, math.min(string.len(a), string.len(b)) do
        diff = (a[i] == b[i]) and diff
    end
    return diff
end
</code>```

A complete example of how I use it in github gist  https://gist.github.com/Samael500/5dbdf6d55838f841a08eb7847ad1c926

Body:
What I have:

GNU/Linux host

nginx is up and running

there is a cron-job scheduled to run immediately after a specific file has been removed (similar to run-crons)

GitHub sends a webhook when someone pushes to a repository

What I want:

I do now want to run either lua or anything comparable to parse GitHub's request and validate it and then delete a file (if the request was valid of course).

Preferably all of this should happen without the hassle to maintain an additional PHP installation as there is currently none, or the need to use fcgiwrap or similar.

Template:

On the nginx side I have something equivalent to

location /deploy {
    # execute lua (or equivalent) here
}

Body:
To read json body of GH webhook you nead use JSON4Lua lib, and to validate HMAC signature use luacrypto.

Preconfigure

Install required modules

$ sudo luarocks install JSON4Lua
$ sudo luarocks install luacrypto

In Nginx define location for deploy

  location /deploy {
    client_body_buffer_size 3M;
    client_max_body_size  3M;

    content_by_lua_file /path/to/handler.lua;
  }

The max_body_size and body_buffer_size should be equal to prevent error

request body in temp file not supported

https://github.com/openresty/lua-nginx-module/issues/521

Process webhook

Get request payload data and check is correct

ngx.req.read_body()
local data = ngx.req.get_body_data()

if not data then
    ngx.log(ngx.ERR, "failed to get request body")
    return ngx.exit (ngx.HTTP_BAD_REQUEST)
end

Verify GH signature with use luacrypto

local function verify_signature (hub_sign, data)
    local sign = 'sha1=' .. crypto.hmac.digest('sha1', data, secret)
    -- this is simple comparison, but it's better to use a constant time comparison
    return hub_sign == sign
end

-- validate GH signature
if not verify_signature(headers['X-Hub-Signature'], data) then
    ngx.log(ngx.ERR, "wrong webhook signature")
    return ngx.exit (ngx.HTTP_FORBIDDEN)
end

Parse data as json and check is master branch, for deploy

data = json.decode(data)
-- on master branch
if data['ref'] ~= branch then
    ngx.say("Skip branch ", data['ref'])
    return ngx.exit (ngx.HTTP_OK)
end

If all correct, call deploy function

local function deploy ()
    -- run command for deploy
    local handle = io.popen("cd /path/to/repo && sudo -u username git pull")
    local result = handle:read("*a")
    handle:close()

    ngx.say (result)
    return ngx.exit (ngx.HTTP_OK)
end

Example

Example constant time string compare

local function const_eq (a, b)
    -- Check is string equals, constant time exec
    getmetatable('').__index = function (str, i)
        return string.sub(str, i, i)
    end

    local diff = string.len(a) == string.len(b)
    for i = 1, math.min(string.len(a), string.len(b)) do
        diff = (a[i] == b[i]) and diff
    end
    return diff
end

A complete example of how I use it in github gist  https://gist.github.com/Samael500/5dbdf6d55838f841a08eb7847ad1c926


问:
Passing String as POST parameter Retrofit payload
I'm trying to pass a String to a POST retrofit method to my server.
This is my call:

```<code>Observable<MyOrder> addNoteOrder(@Header("Token1")String token1,
                                 @Header("Token2")String token1,
                                 @Path("orderId")long orderId,
                                 @Body String orderNote);
</code>```

And I'm callin this way:

```<code>mRestApi.addNoteOrder("token1", "token2", "0", "001");
</code>```

Debuggin with my server I'm having 500 error, because it tells me the error is in payload creation.

So,how can I send a String object as a payload to my server. This is the first time I do this.

答:
The @Path replaces the parameter in the POST url with the string you pass to it. It should look something like

```<code>@POST("some/{orderId}")
Call<MyOrder> addNoteOrder(@Path("orderId") long orderId,
                           @Header("Token1") String token1,
                           @Header("Token2") String token1,
                           @Body String orderNote);
</code>```

And call the service

```<code>Call<MyOrder> responseBodyCall = mRestApi.addNoteOrder(params);
responseBodyCall.clone().enqueue(new Callback<MyOrder>() {
    @Override
    public void onResponse(Call<MyOrder> call, Response<MyOrder> response) {

    }

    @Override
    public void onFailure(Call<MyOrder> call, Throwable t) {

    }
});
</code>```

Body:
I'm trying to pass a String to a POST retrofit method to my server.
This is my call:

Observable<MyOrder> addNoteOrder(@Header("Token1")String token1,
                                 @Header("Token2")String token1,
                                 @Path("orderId")long orderId,
                                 @Body String orderNote);

And I'm callin this way:

mRestApi.addNoteOrder("token1", "token2", "0", "001");

Debuggin with my server I'm having 500 error, because it tells me the error is in payload creation.

So,how can I send a String object as a payload to my server. This is the first time I do this.

Body:
The @Path replaces the parameter in the POST url with the string you pass to it. It should look something like

@POST("some/{orderId}")
Call<MyOrder> addNoteOrder(@Path("orderId") long orderId,
                           @Header("Token1") String token1,
                           @Header("Token2") String token1,
                           @Body String orderNote);

And call the service

Call<MyOrder> responseBodyCall = mRestApi.addNoteOrder(params);
responseBodyCall.clone().enqueue(new Callback<MyOrder>() {
    @Override
    public void onResponse(Call<MyOrder> call, Response<MyOrder> response) {

    }

    @Override
    public void onFailure(Call<MyOrder> call, Throwable t) {

    }
});


问:
How to convert a 2D array to a value object in ruby
I have a 2D array:

```<code>a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]
</code>```

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

```<code>class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}
</code>```

答:
It sounds like you want to call the attribute accessor method that corresponds to each array value.  You use send to call methods programmatically.  So you need an array of the method names that corresponds to the values you have in your given array.  Now, assuming the class with your attributes is called Data.

```<code>attrs = [:name, :date1, :date2, :event]
result = a.map do |e|
  d = Data.new
  e.each.with_index do |v, i|
    d.send(attrs[i], v)
  end
  d
end
</code>```

The value result is an array of Data objects populated from your given array.

Of course, if you control the definition of your Data object, the best things would be to give it an initialize method that takes an array of values.

Body:
I have a 2D array:

a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]

I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".

This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:

class Schedule_info
   arrt_accessor :name, :date1, :date2, :event

   def initialize arr
       #I would like this loop to contain all 4 attr assignments
       arr.each {|i| instance_variable_set(:name, i[0])}

Body:
It sounds like you want to call the attribute accessor method that corresponds to each array value.  You use send to call methods programmatically.  So you need an array of the method names that corresponds to the values you have in your given array.  Now, assuming the class with your attributes is called Data.

attrs = [:name, :date1, :date2, :event]
result = a.map do |e|
  d = Data.new
  e.each.with_index do |v, i|
    d.send(attrs[i], v)
  end
  d
end

The value result is an array of Data objects populated from your given array.

Of course, if you control the definition of your Data object, the best things would be to give it an initialize method that takes an array of values.


问:
Azure function proxy returns error 500
Currently I am having Azure API app located in UK but I would like to create a Proxy in HK for my users in china to access the servers without much performance impact in connecting the DB server that's allocated in EU.

I just setting up the proxy functionality on Azure function, which is located in East Asia. Unfortunately, I kept getting error code 500 with the api request though postman.

How can I trace the error which is causing error code 500?

答:
Adding to Hamid's Answer,

When you add the header "Proxy-Trace-Enabled: true" to the request, you will see a Response Header "Proxy-Trace-Location" giving a link to access the trace log for that request. The link also gives the Trace ID for the particular call.

Title: Azure function proxy returns error 500


问:
SQL QUERY to count repeats with 2 conditions

To find repeated items only when when it satisfies two conditions. In this example count repeats of item type for each customer_id only when it has order size "Big" and its corresponding date is before other instances. This first condition and repeats can be achieved by using this code.

```<code>Select Customer_id, Item_Type, COUNT(*)
from table
group by Customer_id, Item_Type
having count(*) > 1 and sum(case when Order_Size = 'Big' then 1 else 0 end) > 0;
</code>```

how do I include date aspect as well to this?

答:
I would do this as:</p>

```<code>select t.customer_id, t.item_type, count(*)
from (select t.*,
             min(case when OrderSize = 'Big' then date end) over (partition by customer_id, item_type) as min_big
      from t
     ) t
where date > min_big
group by t.customer_id, t.item_type;
</code>```

Body:
To find repeated items only when when it satisfies two conditions. In this example count repeats of item type for each customer_id only when it has order size "Big" and its corresponding date is before other instances. This first condition and repeats can be achieved by using this code.

Select Customer_id, Item_Type, COUNT(*)
from table
group by Customer_id, Item_Type
having count(*) > 1 and sum(case when Order_Size = 'Big' then 1 else 0 end) > 0;

how do I include date aspect as well to this?

Body:
I would do this as:

select t.customer_id, t.item_type, count(*)
from (select t.*,
             min(case when OrderSize = 'Big' then date end) over (partition by customer_id, item_type) as min_big
      from t
     ) t
where date > min_big
group by t.customer_id, t.item_type;


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
What you did is shallow copy, if you have pointers in your MyGame class, then a deep copy is a MUST!.
I suggest implementing a function or a set of functiions inside MyGame that will take care of saving its own data to a file,and you will only need to call it.

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?


问:
ArrayIndexOutOfBounds while setting values of cells in JTable
I'm creating a JTable from user input.  There is a selection of radio buttons in the GUI and when a one is selected it needs to update all values of a column in the table.

I'm getting an arrayIndexOutofBounds Error with this.  Not entirely sure what I'm doing wrong.  Any input would be appreciated as this is my first time using a jtable and it's been harder than I figured it would be.

Code where I'm getting an error:

```<code>class RadioListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(oneRadio.isSelected())
        {
            payAMT = payAMT * .01;
            for(int i = 1; i < outputTable.getRowCount(); i++)
            {
                outputTable.setValueAt(payAMT,i,4);
            }

        }
</code>```

Code:

```<code>//JTableCreation

model = new DefaultTableModel(new String[] {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"}, 0);
    outputTable = new JTable();
    outputTable.setModel(model);
    JScrollPane scroll = new JScrollPane(outputTable);
</code>```

More Code
     //Adding Entries to JTable

```<code>class clickListener implements ActionListener
{
    @SuppressWarnings("unchecked")
    public void actionPerformed(ActionEvent e)
    {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;

        try
        {
            empNum = Integer.parseInt(empNumField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Employee ID.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hourlyRate = Double.parseDouble(basePayField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hourly Pay Rate.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hoursWorked = Double.parseDouble(hrsField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hours Worked.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }

        payAMT = calculatePay(hourlyRate, hoursWorked);

        Object[] newRecord = {empNum,hourlyRate,hoursWorked,payAMT};
        model.addRow(newRecord);

        totalPayAMT += payAMT;
        totalPayLabel.setText("Total Employee Pay: "+totalPayAMT);
    }
}
</code>```

答:
You need to start your iteration of the JTable at 0. Rows and Columns of a JTable are 0 based. When you start your for loop at 1 you're not really starting at the first row like you might think, you're actually starting at row 2. Where you're also falling into confusion is with the JTable.getRowCount() method. This method will return the actual number of rows currently contained within your JTable so you need to adjust its value (subtract 1) in order to use it for an iteration, for example:

```<code>int cnt = outputTable.getRowCount();
if(oneRadio.isSelected() && cnt > 0) {
    payAMT = payAMT * .01;
    for(int i = 0; i < cnt - 1; i++) {
        outputTable.setValueAt(payAMT, i, 4);
    }
}
</code>```

Body:
I'm creating a JTable from user input.  There is a selection of radio buttons in the GUI and when a one is selected it needs to update all values of a column in the table.

I'm getting an arrayIndexOutofBounds Error with this.  Not entirely sure what I'm doing wrong.  Any input would be appreciated as this is my first time using a jtable and it's been harder than I figured it would be.

Code where I'm getting an error:

class RadioListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(oneRadio.isSelected())
        {
            payAMT = payAMT * .01;
            for(int i = 1; i < outputTable.getRowCount(); i++)
            {
                outputTable.setValueAt(payAMT,i,4);
            }

        }

Code:

//JTableCreation

model = new DefaultTableModel(new String[] {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"}, 0);
    outputTable = new JTable();
    outputTable.setModel(model);
    JScrollPane scroll = new JScrollPane(outputTable);

More Code
     //Adding Entries to JTable

class clickListener implements ActionListener
{
    @SuppressWarnings("unchecked")
    public void actionPerformed(ActionEvent e)
    {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;

        try
        {
            empNum = Integer.parseInt(empNumField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Employee ID.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hourlyRate = Double.parseDouble(basePayField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hourly Pay Rate.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hoursWorked = Double.parseDouble(hrsField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hours Worked.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }

        payAMT = calculatePay(hourlyRate, hoursWorked);

        Object[] newRecord = {empNum,hourlyRate,hoursWorked,payAMT};
        model.addRow(newRecord);

        totalPayAMT += payAMT;
        totalPayLabel.setText("Total Employee Pay: "+totalPayAMT);
    }
}

Body:
You need to start your iteration of the JTable at 0. Rows and Columns of a JTable are 0 based. When you start your for loop at 1 you're not really starting at the first row like you might think, you're actually starting at row 2. Where you're also falling into confusion is with the JTable.getRowCount() method. This method will return the actual number of rows currently contained within your JTable so you need to adjust its value (subtract 1) in order to use it for an iteration, for example:

int cnt = outputTable.getRowCount();
if(oneRadio.isSelected() && cnt > 0) {
    payAMT = payAMT * .01;
    for(int i = 0; i < cnt - 1; i++) {
        outputTable.setValueAt(payAMT, i, 4);
    }
}


问:
Print a string (up to 10 chars) as a diamond
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

```<code>public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}
</code>```

答:
The below should help

```<code>    int halfSize;
    int p = 0;
    boolean is_bottom;
    String message;
    // System.out.println("Please enter a string: ");
    // Scanner input = new Scanner(System.in);

    message = "12345";
    is_bottom = false;

    //System.out.println((int)Math.ceil(message.length() / 2) + 1);
    halfSize = message.length() / 2;
     for (int i = 0; i < message.length(); i++) {
         //Print spaces
          for (int j = 0; j < message.length(); j++) {
            if (j == halfSize || (j <= (halfSize + p) && j >= (halfSize - p)))
              System.out.print(message.charAt(j));
              else
              System.out.print("*");
          }

          if (is_bottom == false) {
        if (p >= halfSize)
        is_bottom = true;
       }

       if (is_bottom == false)
       p++;
       else
       p--;

       System.out.println();
       }
</code>```

I is the rows
j is the columns
and the if statement is your main logic to print the characters in the right location

I added a static string for the message so you can see the result faster, just uncomment your code to ask for input.

Also make sure to do a check that the length of the string is an odd number, if not then throw an error message stating that it is an invalid string

It is much faster and neater and easier to understand than to have many for loops and if statements. :) hope you enjoy java as much as I did

Body:
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}

Body:
The below should help

    int halfSize;
    int p = 0;
    boolean is_bottom;
    String message;
    // System.out.println("Please enter a string: ");
    // Scanner input = new Scanner(System.in);

    message = "12345";
    is_bottom = false;

    //System.out.println((int)Math.ceil(message.length() / 2) + 1);
    halfSize = message.length() / 2;
     for (int i = 0; i < message.length(); i++) {
         //Print spaces
          for (int j = 0; j < message.length(); j++) {
            if (j == halfSize || (j <= (halfSize + p) && j >= (halfSize - p)))
              System.out.print(message.charAt(j));
              else
              System.out.print("*");
          }

          if (is_bottom == false) {
        if (p >= halfSize)
        is_bottom = true;
       }

       if (is_bottom == false)
       p++;
       else
       p--;

       System.out.println();
       }

I is the rows
j is the columns
and the if statement is your main logic to print the characters in the right location

I added a static string for the message so you can see the result faster, just uncomment your code to ask for input.

Also make sure to do a check that the length of the string is an odd number, if not then throw an error message stating that it is an invalid string

It is much faster and neater and easier to understand than to have many for loops and if statements. :) hope you enjoy java as much as I did


问:
Responsive Google Maps API v3 - Automatically display all markers on small screens
I'm designing a little webapp that includes Google Maps API in Full Screen. The webapp is intended to be used successfuly in mobile devices (even small devices). Actually I fetch some coordinates from my Database using AJAX and place them in the map.

I push the coordinates in an array locations using AJAX and then I do the following:

```<code>var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 11,
  center: new google.maps.LatLng(37.262577, -115.8314989),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
    position: google.maps.ControlPosition.BOTTOM_LEFT
  }
});

var infowindow = new google.maps.InfoWindow();

var marker, i;
for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    //locations[i][1] is lang
    //locations[i][2] is lng
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}
</code>```

How can I convert this script in responsive? I want to see all my Markers on the screen, mobile screens <= 768px (width), I can't find any generic handler  to smartly resize (zoom in/out) the map in order to view all markers in the screen.

Thanks for reading!

答:
Your best bet is making a LatLngBounds object and extending it with every couple of coordinates you want to show. Then, just call fitBounds() on your map object, with your bounds as argument, like follows :

var marker, i;
var bounds = new google.maps.LatLngBounds()
for (i = 0; i < locations.length; i++) {
  var coords =  new google.maps.LatLng(parseFloat(locations[i][1]), parseFloat(locations[i][2]))
  marker = new google.maps.Marker({
    //locations[i][1] is lang
    //locations[i][2] is lng
    position: coords,
    map: map
  });

  bounds.extend(coords);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

map.fitBounds(bounds);```

If you want to apply only if needed, then you have to compare the variable bounds you created with map.getBounds(), by comparing their extremities : getNorthEast() and getSouthWest() coordinates.

Body:
I'm designing a little webapp that includes Google Maps API in Full Screen. The webapp is intended to be used successfuly in mobile devices (even small devices). Actually I fetch some coordinates from my Database using AJAX and place them in the map.

I push the coordinates in an array locations using AJAX and then I do the following:

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 11,
  center: new google.maps.LatLng(37.262577, -115.8314989),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
    position: google.maps.ControlPosition.BOTTOM_LEFT
  }
});

var infowindow = new google.maps.InfoWindow();

var marker, i;
for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    //locations[i][1] is lang
    //locations[i][2] is lng
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

How can I convert this script in responsive? I want to see all my Markers on the screen, mobile screens <= 768px (width), I can't find any generic handler  to smartly resize (zoom in/out) the map in order to view all markers in the screen.

Thanks for reading!

Body:
Your best bet is making a LatLngBounds object and extending it with every couple of coordinates you want to show. Then, just call fitBounds() on your map object, with your bounds as argument, like follows :

var marker, i;
var bounds = new google.maps.LatLngBounds()
for (i = 0; i < locations.length; i++) {
  var coords =  new google.maps.LatLng(parseFloat(locations[i][1]), parseFloat(locations[i][2]))
  marker = new google.maps.Marker({
    //locations[i][1] is lang
    //locations[i][2] is lng
    position: coords,
    map: map
  });

  bounds.extend(coords);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

map.fitBounds(bounds);

If you want to apply only if needed, then you have to compare the variable bounds you created with map.getBounds(), by comparing their extremities : getNorthEast() and getSouthWest() coordinates.


问:
Rendering Layouts with Backbone.js
If you were to build a single page web application (SPWA) using Backbone.js and jQuery with--for example--two controllers that each required a unique page layouts, how would you render the layout?

ControllerA is a three column layout.

ControllerB is a two column layout.

The default route activates ControllerA.Welcome() -- the initial rendering.

Both controllers have different views rendered within their columns that take advantage of all the Backbone.js model/view goodness.

The Problem

When the user requests a route mapped to ControllerB, the entire page layout needs to change to no longer use the ControllerA layout. This would hide ControllerA's layout and show ControllerB's layout -- or, render the layout if not already in the DOM.

My First Thought

Would you use a Backbone.js view to render the layout, and then, render each column with it's model-bound views?

My Second Thought

Would you add a setup/layout method to your controller that used jQuery to render the layout and then allow the action responsible for the route do it's thing? Using jQuery within the controller feels a little off to me, but, I want the controller to be responsible for ensuring the right layout is visible for it's routes.

Here is a snippet for my second thought:

```<code>var Controller = Backbone.Controller.extend
({
    routes :
    {
       "" : "welcome" // default action
    }
    /** Constructor **/
    ,initialize: function(options)
    {
        console.log('Workspace initialized');
    }
    // LAYOUT
    ,renderLayout : function ()
    {
        console.log('Rendering Layout.');
        var $ = window.$;
        var layout = require('js/layout/app/big_menu');
        $(layout.parent).html(layout.html);
    }
    // ACTIONS
    /** Default Action **/
    ,welcome : function ()
    {
        this.renderLayout();
        console.log('Do the whole model/view thing...');
    }
});
</code>```

Thank You

Thanks for taking the time to respond. I appreciate it!

答:
I prefer to have the skeleton of the application laid out on the page already. So you have the complete layout with the different elements on the page and you create your backbone view against those elements so they are correctly laid out.

This works well when you have a single layout, things get fun when you have multiple. You could put all layouts on the page and hide the different configurations depending on your logic. You can see the layout has being the initial view of an hierarchy. So you render the layout and then have the views load.

There is no real one way of doing this. There are pros and cons for each. One thing I would not do is render the layout in the controller. I put all rendering and html in views so I can deal with logic on the controller and model (think MVC here).

Title: Rendering Layouts with Backbone.js

Body:
If you were to build a single page web application (SPWA) using Backbone.js and jQuery with--for example--two controllers that each required a unique page layouts, how would you render the layout?

ControllerA is a three column layout.

ControllerB is a two column layout.

The default route activates ControllerA.Welcome() -- the initial rendering.

Both controllers have different views rendered within their columns that take advantage of all the Backbone.js model/view goodness.

The Problem

When the user requests a route mapped to ControllerB, the entire page layout needs to change to no longer use the ControllerA layout. This would hide ControllerA's layout and show ControllerB's layout -- or, render the layout if not already in the DOM.

My First Thought

Would you use a Backbone.js view to render the layout, and then, render each column with it's model-bound views?

My Second Thought

Would you add a setup/layout method to your controller that used jQuery to render the layout and then allow the action responsible for the route do it's thing? Using jQuery within the controller feels a little off to me, but, I want the controller to be responsible for ensuring the right layout is visible for it's routes.

Here is a snippet for my second thought:

var Controller = Backbone.Controller.extend
({
    routes :
    {
       "" : "welcome" // default action
    }
    /** Constructor **/
    ,initialize: function(options)
    {
        console.log('Workspace initialized');
    }
    // LAYOUT
    ,renderLayout : function ()
    {
        console.log('Rendering Layout.');
        var $ = window.$;
        var layout = require('js/layout/app/big_menu');
        $(layout.parent).html(layout.html);
    }
    // ACTIONS
    /** Default Action **/
    ,welcome : function ()
    {
        this.renderLayout();
        console.log('Do the whole model/view thing...');
    }
});

Thank You

Thanks for taking the time to respond. I appreciate it!


问:
To include or not include missing values in statistical analysis?
I have some data I'm calculating frequencies, means, and medians on. Of course, some of the data is missing.

I have not been including the missing values, but I've noticed that my results for my calculations for frequencies and chi-squared tests are sometimes vastly different than that of my boss'. He kept the missing values in and I did not. My boss' isn't a statistician, by the way.

So I guess my question is, should I keep missing values or not? And why would I want to or not want to keep them in my calculations.

Here is a sample of what I'm doing:

Evaluate proportion of patients with or without insurance
Evaluate proportion of patients grouped by Insurance Status and whether or not they tested ER positive
Evaluate proportion of patients grouped by Insurance Status and subdivided by Race

EXAMPLE:

```<code>         Insurance Status   Yes     No
ERstatus

yes                          50     112

no                           23     87
</code>```

Any help would be appreciated. Thanks!

答: Yes of course. You should eliminate mistakes (miscounts and etc errors) from result computing. There are some rules for its processing. But there is no sense to include 'mistakes' in result...</p>

Body:
I have some data I'm calculating frequencies, means, and medians on. Of course, some of the data is missing.

I have not been including the missing values, but I've noticed that my results for my calculations for frequencies and chi-squared tests are sometimes vastly different than that of my boss'. He kept the missing values in and I did not. My boss' isn't a statistician, by the way.

So I guess my question is, should I keep missing values or not? And why would I want to or not want to keep them in my calculations.

Here is a sample of what I'm doing:

Evaluate proportion of patients with or without insurance
Evaluate proportion of patients grouped by Insurance Status and whether or not they tested ER positive
Evaluate proportion of patients grouped by Insurance Status and subdivided by Race

EXAMPLE:

         Insurance Status   Yes     No
ERstatus

yes                          50     112

no                           23     87

Any help would be appreciated. Thanks!


问:
Is there any way to swap columns in visual composer on mobile responsive?
Is there any way to swap columns in visual composer on mobile responsive?
I want to know it. such as we can swap columns in bootstrap using push or pull class. so can we make something like this in visual composer? i have uploaded images for assistance.

Actual Image: http://imgur.com/a/a1rqp

What i want: http://imgur.com/a/AA9aD

答:
Change your structure a little bit, I believe it just drag and drop thing in Visual Composer.
whatever you want to show in second div, put at first place and give float:right for desktop and float:none for mobile.

here is JsFiddle,

div{
  width:50%;
  background:blue;
  float:right;
  color:white
}
@media (max-width: 700px) {
  .first{
    background:red;
    float:none;
  }
  div{
    width:100%
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">First</div>
<div class="second">second</div></code>```

Body:
Change your structure a little bit, I believe it just drag and drop thing in Visual Composer.
whatever you want to show in second div, put at first place and give float:right for desktop and float:none for mobile.

here is JsFiddle,

div{
  width:50%;
  background:blue;
  float:right;
  color:white
}
@media (max-width: 700px) {
  .first{
    background:red;
    float:none;
  }
  div{
    width:100%
  }
}

<div class="first">First</div>
<div class="second">second</div>


问:
Make small changes to multiple functions without affecting cell reference
What is the best way to change ">" to ">=" in 100+ formulas such as:

```<code>=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$A$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$B$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$C$2),"1","0")
</code>```

Would I need some VBA code?

答:
As Scott_Craner stated, a simple Find/Replace should work.

Save a version of your data in case you misjudged where the search subject is in your data.

Highlight the cells with the formulas you wish to change.

Press Ctrl and the F keys (or click on "Find&Select" in the Home tab in the "Editing" group and select Replace from the drop-down)

In the Find and Replace dialog box, make sure you are on the Replace tab.

In the "Find what:" box, type ">" without quotes (note, if there are other > symbols in some formulas, you can distinguish these with some repetitive text before and after)

In the "Replace with:" box, type "<" without quotes (note, if you included other text to specify certain instances of ">", make sure you include all the text that should also be replaced)

Hit the "Replace All" button.

Your spreadsheet formulas should now be as you'd like them. If they're not, thank goodness you saved another version first. Find/Replace is very powerful, so make sure to limit the scope by selecting the cells you want searched and being sure that Excel will find only those data you wish to change.

If you are interested in VBA, you could use it here. But Excel already has a powerful, user-friendly tool at your disposal.

Body:
What is the best way to change ">" to ">=" in 100+ formulas such as:

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$A$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$B$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$C$2),"1","0")

Would I need some VBA code?


问:
DAE model not showing applied textures within iOS app
I am using a few DAE models in a SceneKit scene in my app.  However, textures do not show up on the models in the application even though they are shown in Xcode.  I am also using the textures that I include in the app's asset catalogue.

Here is the texture I applying to the diffuse channel of the model. I am dragging this to the model in Xcode to apply it, and Xcode shows the model with the texture in its model view.

And the model itself:
https://www.dropbox.com/s/lzqkgoumu9yshcf/amalthea.dae?dl=0
The model was exported (in Blender) from this Blender file:

https://www.dropbox.com/s/kt3n9f2kn6w6cij/amalthea.blend?dl=0

I am loading the model into my scene as follows:

```<code>let scene = SCNScene(named: "amalthea.dae")
</code>```

Anything obvious that I am overlooking?

答:
Revised answer:
After downloading  the dae file.

The most likely cause is that your textures are not on a path that is reachable relative to the model location.

The texture reference in the dae file is:

```<code> <init_from>Assets.xcassets/jupiter/amalthea/amaltheamap.imageset/amalthea.jpg</init_from>
</code>```

I think it should be relative to model location.  Try changing the texture reference in the dae (using any text editor) to just "amalthea.jpg".  Then copy the jpg to same folder where the model is.

```<code> <init_from>amalthea.jpg</init_from>
</code>```

A more detailed discussion can be found here.

Body:
I am using a few DAE models in a SceneKit scene in my app.  However, textures do not show up on the models in the application even though they are shown in Xcode.  I am also using the textures that I include in the app's asset catalogue.

Here is the texture I applying to the diffuse channel of the model. I am dragging this to the model in Xcode to apply it, and Xcode shows the model with the texture in its model view.

And the model itself:
https://www.dropbox.com/s/lzqkgoumu9yshcf/amalthea.dae?dl=0
The model was exported (in Blender) from this Blender file:

https://www.dropbox.com/s/kt3n9f2kn6w6cij/amalthea.blend?dl=0

I am loading the model into my scene as follows:

let scene = SCNScene(named: "amalthea.dae")

Anything obvious that I am overlooking?

Body:
Revised answer:
After downloading  the dae file.

The most likely cause is that your textures are not on a path that is reachable relative to the model location.

The texture reference in the dae file is:

 <init_from>Assets.xcassets/jupiter/amalthea/amaltheamap.imageset/amalthea.jpg</init_from>

I think it should be relative to model location.  Try changing the texture reference in the dae (using any text editor) to just "amalthea.jpg".  Then copy the jpg to same folder where the model is.

 <init_from>amalthea.jpg</init_from>

A more detailed discussion can be found here.