答:
You can try with flexbox:

Note you need to use 100% on html and body  and also your footer element at the same level of nav and core

html,body {
  margin: 0;
  height: 100%;
}
.container {
  background: orange;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
#nav {
  flex: 0 0 auto;
  height: 55px;
}
#core {
  flex: 1 0 auto;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div id=nav>
    NAV
  </div>
  <div id=core>
    <div id=content>
      <div id=tophea>
        TOP Content
      </div>
      <div id=msgs>
        MSG Content
      </div>
    </div>
  </div>
  <div id="footer">
    Footer <br> footer
  </div>
</div></code>```

Title: Height 100% and css issue with footer

Body:
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

NAV

           TOP Content

       MSG Content

    Footer

and css like this :

#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

Body:
You can try with flexbox:

Note you need to use 100% on html and body  and also your footer element at the same level of nav and core

html,body {
  margin: 0;
  height: 100%;
}
.container {
  background: orange;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
#nav {
  flex: 0 0 auto;
  height: 55px;
}
#core {
  flex: 1 0 auto;
  background: red;
}

<div class="container">
  <div id=nav>
    NAV
  </div>
  <div id=core>
    <div id=content>
      <div id=tophea>
        TOP Content
      </div>
      <div id=msgs>
        MSG Content
      </div>
    </div>
  </div>
  <div id="footer">
    Footer <br> footer
  </div>
</div>


来源: stackexchange

问:
Load header and footer from Module in Laravel
I have created a module in Laravel and im using views on that module, my structure is this:

Modules

```<code> -> MyModule
 ->->Controllers
 ->->Views
 ->->->MyModule.blade.php
</code>```

But i have the headers and footer done on resources->views->layouts->base.blade.php

So how can i call this one so i can use the same base layout in all modules? it is possible on Laravel 5?

Already tried this

```<code>@include('layouts.base')
</code>```

but im getting

Trying to get property of non-object (View: ... resources\views\layouts\base.blade.php

Thank you.

答:
The structure of blade is relative to the views folder in the the resources folder.

Thus making your @include() have a structure like the this:

```<code>@include('DIRECTORY.BLADE')
</code>```

and you can include your various blade contents by using @yield()

```<code>@yield('YIELD_FIELD_NAME')
</code>```

If you are trying to have blades extent from that layout you would call that at the top of the blade files you want to extend off it.

```<code>@extends('DIRECTORY.BLADE')
</code>```

This is an example blade file that can extend your layout if your layout contains the @yield('content') tag in it.

example.blade.php

```<code>@extends('layouts.base')

@section('content')

  YOUR BLADES HTML/CONTENT

@endsection
</code>```

https://laravel.com/docs/5.4/blade#defining-a-layout

How to add Auth middleware to controller:

```<code>/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}
</code>```

Here is an example Controller:
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/UsersManagementController.php

Here is an example of a view that uses that controller:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/usersmanagement/show-user.blade.php

Here is an example of the template that view uses:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/layouts/app.blade.php

Here is the routing file for the above examples:
https://github.com/jeremykenedy/laravel-auth/blob/master/routes/web.php

ContentLicense: CC BY-SA 3.0

Body:
I have created a module in Laravel and im using views on that module, my structure is this:

Modules

 -> MyModule
 ->->Controllers
 ->->Views
 ->->->MyModule.blade.php

But i have the headers and footer done on resources->views->layouts->base.blade.php

So how can i call this one so i can use the same base layout in all modules? it is possible on Laravel 5?

Already tried this

@include('layouts.base')

but im getting

Trying to get property of non-object (View: ... resources\views\layouts\base.blade.php

Thank you.

Body:
The structure of blade is relative to the views folder in the the resources folder.

Thus making your @include() have a structure like the this:

@include('DIRECTORY.BLADE')

and you can include your various blade contents by using @yield()

@yield('YIELD_FIELD_NAME')

If you are trying to have blades extent from that layout you would call that at the top of the blade files you want to extend off it.

@extends('DIRECTORY.BLADE')

This is an example blade file that can extend your layout if your layout contains the @yield('content') tag in it.

example.blade.php

@extends('layouts.base')

@section('content')

  YOUR BLADES HTML/CONTENT

@endsection

https://laravel.com/docs/5.4/blade#defining-a-layout

How to add Auth middleware to controller:

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

Here is an example Controller:
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/UsersManagementController.php

Here is an example of a view that uses that controller:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/usersmanagement/show-user.blade.php

Here is an example of the template that view uses:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/layouts/app.blade.php

Here is the routing file for the above examples:
https://github.com/jeremykenedy/laravel-auth/blob/master/routes/web.php


问:
Php curl multiple queries
i would like to open all the page ids of the website starting with http://website.com/page.php?id=1 and ending with id=1000

take the data via preg_match and record it somewhere or .txt or .sql

bellow is the curl function i'm using at the moment please kindly advise the full code that will get this job done.

```<code>function curl($url)
    {

    $POSTFIELDS = 'name=admin&password=guest&submit=save';
    $reffer = "http://google.com/";
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
    $cookie_file_path = "C:/Inetpub/wwwroot/spiders/cookie/cook"; // Please set your Cookie File path. This file must have CHMOD 777 (Full Read / Write Option).

    $ch = curl_init();  // Initialize a CURL session.
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);  // The URL to fetch. You can also set this when initializing a session with curl_init().
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); // The contents of the "User-Agent: " header to be used in a HTTP request.
    curl_setopt($ch, CURLOPT_POST, 1); //TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
    curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS); //The full data to post in a HTTP "POST" operation.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
    curl_setopt($ch, CURLOPT_REFERER, $reffer); //The contents of the "Referer: " header to be used in a HTTP request.
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); // The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); // The name of a file to save all internal cookies to when the connection closes.
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;

   }
</code>```

答:
You can try it with the function file_put_contents and a loop calling your function.

```<code>$file = "data.txt";
$website_url = "http://website.com/page.php?id=";

for(i = 1; i <= 1000; i++){
    file_put_contents($file, curl($website_url.i), FILE_APPEND);
}
</code>```

Title: Php curl multiple queries

Body:
i would like to open all the page ids of the website starting with http://website.com/page.php?id=1 and ending with id=1000

take the data via preg_match and record it somewhere or .txt or .sql

bellow is the curl function i'm using at the moment please kindly advise the full code that will get this job done.

function curl($url)
    {

    $POSTFIELDS = 'name=admin&password=guest&submit=save';
    $reffer = "http://google.com/";
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
    $cookie_file_path = "C:/Inetpub/wwwroot/spiders/cookie/cook"; // Please set your Cookie File path. This file must have CHMOD 777 (Full Read / Write Option).

    $ch = curl_init();  // Initialize a CURL session.
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_URL, $url);  // The URL to fetch. You can also set this when initializing a session with curl_init().
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); // The contents of the "User-Agent: " header to be used in a HTTP request.
    curl_setopt($ch, CURLOPT_POST, 1); //TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
    curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS); //The full data to post in a HTTP "POST" operation.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
    curl_setopt($ch, CURLOPT_REFERER, $reffer); //The contents of the "Referer: " header to be used in a HTTP request.
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); // The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); // The name of a file to save all internal cookies to when the connection closes.
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;

   }

Body:
You can try it with the function file_put_contents and a loop calling your function.

$file = "data.txt";
$website_url = "http://website.com/page.php?id=";

for(i = 1; i <= 1000; i++){
    file_put_contents($file, curl($website_url.i), FILE_APPEND);
}


问:
Path.GetRandomFileName vs Path.GetTempFileName
Base on recommendation from https://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename(v=vs.110).aspx
I have replaced  GetTempFileName with GetRandomFileName to get a name for the temp file. And it cause a problem. Sometimes GetRandomFileName return not a file name but location in System32 folder. And of cause users with no admin rights are having an error that file is not found.
Do I missed anything?

Here is a code:

string tempFileName = Path.GetRandomFileName();
FileStream tempFileStream = null;
tempFileStream = File.Open(tempFileName, FileMode.Create, FileAccess.ReadWrite);

later on when I try to access that file by code:

```<code>FileInfo fileInfo = new FileInfo(tempFileName);
</code>```

I have an error:

System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\25ddubwt.qsc' is denied.

I realised that when user initiate a program by using menu from Windows/Start button current directory for the application will be System32

答:
GetTempFileName() returns a full path, GetRandomFileName() does not.

If you assume GetRandomFileName() has a path and write to it the file may well end up in System32 if thats the current directory.

To fix create a full path:

```<code>string fname = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
</code>```

Body:
Base on recommendation from https://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename(v=vs.110).aspx
I have replaced  GetTempFileName with GetRandomFileName to get a name for the temp file. And it cause a problem. Sometimes GetRandomFileName return not a file name but location in System32 folder. And of cause users with no admin rights are having an error that file is not found.
Do I missed anything?

Here is a code:

string tempFileName = Path.GetRandomFileName();
FileStream tempFileStream = null;
tempFileStream = File.Open(tempFileName, FileMode.Create, FileAccess.ReadWrite);

later on when I try to access that file by code:

FileInfo fileInfo = new FileInfo(tempFileName);

I have an error:

System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\25ddubwt.qsc' is denied.

I realised that when user initiate a program by using menu from Windows/Start button current directory for the application will be System32

Body:
GetTempFileName() returns a full path, GetRandomFileName() does not.

If you assume GetRandomFileName() has a path and write to it the file may well end up in System32 if thats the current directory.

To fix create a full path:

string fname = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());


问:
Get all tags with count from all documents elasticsearch
I've got index mp_v1 with source fields: id and tags. "Tags" field contains all tags in document in string.

Example:

```<code>{
        "_index": "mp_v1",
        "_type": "mp",
        "_id": "5",
        "_score": 1,
        "_source": {
          "id": 5,
          "tags": "tag1 black blue"
        }
}
</code>```

How can I get from elastic search tags with occurances in all documents? For example if I have two documents, the first one with tags "tag1 black blue" and second with tags "blue square" it should return: blue: 2, tag1: 1, black: 1, square: 1

答:
You can simply use a simple term aggregation to get the same with fielddata enabled (dirty way).

But would suggest to use breaking down the field and then perform aggregation.

Body:
I've got index mp_v1 with source fields: id and tags. "Tags" field contains all tags in document in string.

Example:

{
        "_index": "mp_v1",
        "_type": "mp",
        "_id": "5",
        "_score": 1,
        "_source": {
          "id": 5,
          "tags": "tag1 black blue"
        }
}

How can I get from elastic search tags with occurances in all documents? For example if I have two documents, the first one with tags "tag1 black blue" and second with tags "blue square" it should return: blue: 2, tag1: 1, black: 1, square: 1


问:
How to count word frequency from a Pandas Dataframe- Python
I currently created a Pandas Dataframe from a dictionary.
The Dataframe looks something like:

```<code>      URL         TITLE
0   /xxxx.xx   Hi this is word count
1   /xxxx.xx   Hi this is Stack Overflow
2   /xxxx.xx   Stack Overflow Questions
</code>```

I want to add a new column to this table, which lists the number of frequency the word "Stack Overflow" appears. So for example, it would be like:

```<code>      URL         TITLE                          COUNT
0   /xxxx.xx   Hi this is word count               0
1   /xxxx.xx   Hi this is Stack Overflow           1
2   /xxxx.xx   Stack Overflow Questions            1
</code>```

The count function does not seem to work for dictionaries, but only for strings.  Would there bean easy way to do this?

答:
The count() method on dataframes is good at counting occurrences of a single values such as "Stack Overflow".

To do frequency analysis of multiple values, consider using collection.Counter(data) and its .most_common(k) method.

Body:
I currently created a Pandas Dataframe from a dictionary.
The Dataframe looks something like:

      URL         TITLE
0   /xxxx.xx   Hi this is word count
1   /xxxx.xx   Hi this is Stack Overflow
2   /xxxx.xx   Stack Overflow Questions

I want to add a new column to this table, which lists the number of frequency the word "Stack Overflow" appears. So for example, it would be like:

      URL         TITLE                          COUNT
0   /xxxx.xx   Hi this is word count               0
1   /xxxx.xx   Hi this is Stack Overflow           1
2   /xxxx.xx   Stack Overflow Questions            1

The count function does not seem to work for dictionaries, but only for strings.  Would there bean easy way to do this?


问:
How can I send a message down a websocket running in a thread from tkinter?
I have a server script running:

```<code>async def give_time(websocket,path):
    while True:
        await websocket.send(str(datetime.datetime.now()))
        await asyncio.sleep(3)

start_server = websockets.serve(give_time, '192.168.1.32', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
</code>```

which is working fine, just sending the current time every 3 seconds.

I can receive that string from the client which runs this code:

```<code>async def hello(): #takes whatever text comes through the websocket and displays it in the socket_text label.

    async with websockets.connect('ws://wilsons.lan:8765') as ws:
        while True:
            text = await ws.recv()
            logger.info('message received through websocket:{}'.format(text))
            socket_text.configure(text=text) #socket_text is a tkinter object

loop = asyncio.new_event_loop()

def socketstuff():
    asyncio.set_event_loop(loop)
    asyncio.get_event_loop().run_until_complete(hello())

t = threading.Thread(target=socketstuff,daemon=True)
</code>```

It runs in a thread so that I can run tkinter.mainloop in the main thread. This is the first time I ever used threading so I may be getting it wrong, but it seems to work at present.

What I need to do, is to be able to send a message down the websocket based on a tkinter event - currently just clicking a button next to a text box, but eventually more complex things. The clicking part works fine.

I'm having a lot of trouble with the sending of the message. I've tried a lot of different things, with and without async and await, although that may have just been panic.

The main problem seems to be that I can't access ws from outside that hello() function. This makes sense as I'm using the with context manager. However, if I just use ws = websockets.connect('ws://host') then I get a websockets.py35.client.Connect object which wen I try to use the send (or indeed recv) methods, I get a object has no attribute 'send' error.

I hope this is enough info - will happily post anything else required!

答:
It turns out that the best way of solving this is not to use threads.

This post helped me solve it. It shows that you can run, in a coroutine, one iteration of the tkinter mainloop:

```<code>async def do_gui(root,interval=0.05):
    while True:
        root.update()
        await asyncio.sleep(interval)
</code>```

However, the best way of getting a tkinter event to spawn a websocket message is to use asyncio.queue. Making the tkinter callback add an item to the queue using put_nowait() and having a coroutine which runs at the same time as do_gui which uses await queue.get() to get the message from the queue works for me.

Body:
I have a server script running:

async def give_time(websocket,path):
    while True:
        await websocket.send(str(datetime.datetime.now()))
        await asyncio.sleep(3)

start_server = websockets.serve(give_time, '192.168.1.32', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

which is working fine, just sending the current time every 3 seconds.

I can receive that string from the client which runs this code:

async def hello(): #takes whatever text comes through the websocket and displays it in the socket_text label.

    async with websockets.connect('ws://wilsons.lan:8765') as ws:
        while True:
            text = await ws.recv()
            logger.info('message received through websocket:{}'.format(text))
            socket_text.configure(text=text) #socket_text is a tkinter object

loop = asyncio.new_event_loop()

def socketstuff():
    asyncio.set_event_loop(loop)
    asyncio.get_event_loop().run_until_complete(hello())

t = threading.Thread(target=socketstuff,daemon=True)

It runs in a thread so that I can run tkinter.mainloop in the main thread. This is the first time I ever used threading so I may be getting it wrong, but it seems to work at present.

What I need to do, is to be able to send a message down the websocket based on a tkinter event - currently just clicking a button next to a text box, but eventually more complex things. The clicking part works fine.

I'm having a lot of trouble with the sending of the message. I've tried a lot of different things, with and without async and await, although that may have just been panic.

The main problem seems to be that I can't access ws from outside that hello() function. This makes sense as I'm using the with context manager. However, if I just use ws = websockets.connect('ws://host') then I get a websockets.py35.client.Connect object which wen I try to use the send (or indeed recv) methods, I get a object has no attribute 'send' error.

I hope this is enough info - will happily post anything else required!

Body:
It turns out that the best way of solving this is not to use threads.

This post helped me solve it. It shows that you can run, in a coroutine, one iteration of the tkinter mainloop:

async def do_gui(root,interval=0.05):
    while True:
        root.update()
        await asyncio.sleep(interval)

However, the best way of getting a tkinter event to spawn a websocket message is to use asyncio.queue. Making the tkinter callback add an item to the queue using put_nowait() and having a coroutine which runs at the same time as do_gui which uses await queue.get() to get the message from the queue works for me.


问:
Formula or functions to find Upper Quartile and Lower Quartile in SQL Server
I am trying to get the upper quartile, median and lower quartile in SQL Server. Is there any function or formula? Please advice - many thanks </p>

答: you can use NTILE function with the Over clause ordering the data by any appropriate column in your table/


问:
What is happening in this short program?
```<code>import random

class Die:
    face_value=1

    def show(self):
        return "["+str(self.face_value)+"]"

    def getFaceValue(self):
        return self.face_value

    def roll(self):
        self.face_value=random.randint(1,6)
</code>```

答:
simply put you're declaring a class named "Die" and defining 3 functions which do the following:

show: returns a string with the face value of the die in brackets

getFaceValue: get the face value of the die

roll: gets a random number between 1 and 6, essentially rolling the die


问:
getting 404 error for bower components
I am trying to run my application using gulp task runner and i have installed few bower components and angular is one of them

When i try to run the application I am getting errors :

In index.html:

```<code><script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="bower_components/bootstrap-accessibility-plugin/plugins/js/bootstrap-accessibility.js"></script>
<script src="bower_components/mediaelement/build/mediaelement-and-player.js"></script>
<script src="bower_components/angular-socialshare/dist/angular-socialshare.min.js"></script>
</code>```

I have also included the path but still getting the same errors.

答:
Test 404 error urls from console by run those into the browser. It will ensure that files were available in the location or not.

Use relative path in all files if index.html and bower_components are in same location.

Ex : ./bower_components/jquery/dist/jquery.js

When your angular code start executing, angular does not exist.

AngularJS: Uncaught ReferenceError: angular is not defined

you are trying to access a variable called angular which is not defined.

Title: getting 404 error for bower components

Body:
I am trying to run my application using gulp task runner and i have installed few bower components and angular is one of them

When i try to run the application I am getting errors :

In index.html:

I have also included the path but still getting the same errors.


问:
How to preserve method parameters on every exception
For every possible exception I would like to include some information’s.
This information’s are parameters of method where exception happened.

What is best practice to preserve this information’s?

Maybe something like this?

```<code>private object TestMethod(object value1, object value2)
{
    try
    {
        object res = null;
        // complex some logic with many possible exceptions.
        return res;
    }
    catch (Exception e)
    {
        throw new Exception($"value1 = {JsonConvert.SerializeObject(value1)}, value1 = {JsonConvert.SerializeObject(value1)}", e);
    }
}
</code>```

Edit:

My solution:

Example how to use:

```<code>public async Task<IActionResult> Post([FromBody]MachineConfigurationDto machineDto)
    {
        try
        {
            // Some complex logic
            // . . .
            return new OkResult();
        }
        catch (Exception ex)
        {
            ex.AddExceptionParameter(this, nameof(machineDto), machineDto.ToJson());
            throw;
        }
    }
</code>```

Exception helper:

```<code>public static class ExceptionHelper
    {
        public static Exception AddExceptionParameter<T>(this Exception ex, object currentClass, string key, T value, [CallerMemberName]string methodName = "") where T : struct
        {
            return ex.AddExceptionParameter(currentClass, methodName, key, value.ToString());
        }

        public static Exception AddExceptionParameter(this Exception ex, object currentClass, string key, string value, [CallerMemberName]string methodName = "")
        {
            if (value == null)
            {
                value = "null";
            }

            if (currentClass == null)
            {
                currentClass = "No class";
            }

            if (methodName == null)
            {
                methodName = "No method";
            }

            if (key == null)
            {
                key = "No key";
            }

            var className = string.Empty;
            try
            {
                className = currentClass.GetType().Name;
            }
            catch
            {
                className = "No class name";
            }

            ex.Data.Add($"{className}.{methodName} : {key}", value);
            return ex;
        }
    }
</code>```

ToJson method:

```<code> public static class JsonContentExtension
    {
        public static string ToJson(this object obj)
        {
            try
            {
                return JsonConvert.SerializeObject(obj);
            }
            catch
            {
                return $"Object {obj.ToString()} is not serializable.";
            }
        }
    }
</code>```

How to log details:

```<code>public override void OnException(ExceptionContext context)
    {
            var message = LogExceptionData(context.Exception.Data, context.Exception.Message);
            _logger.LogError(1, context.Exception, message);
            // . . .
    }

private string LogExceptionData(IDictionary data, string message)
        {
            if (message == null)
            {
                message = "No message";
            }

            if (data == null || data.Count == 0)
            {
                return message;
            }

            var errorData = $"{message}{Environment.NewLine}";
            errorData += $"Method parameters:{Environment.NewLine}";
            var i = 1;
            foreach (DictionaryEntry item in data)
            {
                var key = item.Key ?? "null";
                var value = item.Value ?? "null";
                errorData += $"[{i}] => {key} = {value}{Environment.NewLine}";
                i++;
            }
            errorData += $"Details:";

            return errorData;
        }
</code>```

答:
First point, it is not best practice to throw System.Exception from your code. You should create custom exception type.

Second, You can use Exception.Data property to pass more information with exception (ex in your case parameter details). Hope this help.

```<code>catch (Exception e)
    {
        // If using general exception
        var customException = new CustomException();
        customException.Data.Add(nameof(value1), JsonConvert.SerializeObject(value1))
         throw customException;
    }
</code>```

Or

```<code>catch (Exception e)
    {
        // If using general exception
         e.Data.Add(nameof(value1), JsonConvert.SerializeObject(value1))
         throw e;
    }
</code>```

Should not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

Body:
For every possible exception I would like to include some information’s.
This information’s are parameters of method where exception happened.

What is best practice to preserve this information’s?

Maybe something like this?

private object TestMethod(object value1, object value2)
{
    try
    {
        object res = null;
        // complex some logic with many possible exceptions.
        return res;
    }
    catch (Exception e)
    {
        throw new Exception($"value1 = {JsonConvert.SerializeObject(value1)}, value1 = {JsonConvert.SerializeObject(value1)}", e);
    }
}

Edit:

My solution:

Example how to use:

public async Task<IActionResult> Post([FromBody]MachineConfigurationDto machineDto)
    {
        try
        {
            // Some complex logic
            // . . .
            return new OkResult();
        }
        catch (Exception ex)
        {
            ex.AddExceptionParameter(this, nameof(machineDto), machineDto.ToJson());
            throw;
        }
    }

Exception helper:

public static class ExceptionHelper
    {
        public static Exception AddExceptionParameter<T>(this Exception ex, object currentClass, string key, T value, [CallerMemberName]string methodName = "") where T : struct
        {
            return ex.AddExceptionParameter(currentClass, methodName, key, value.ToString());
        }

        public static Exception AddExceptionParameter(this Exception ex, object currentClass, string key, string value, [CallerMemberName]string methodName = "")
        {
            if (value == null)
            {
                value = "null";
            }

            if (currentClass == null)
            {
                currentClass = "No class";
            }

            if (methodName == null)
            {
                methodName = "No method";
            }

            if (key == null)
            {
                key = "No key";
            }

            var className = string.Empty;
            try
            {
                className = currentClass.GetType().Name;
            }
            catch
            {
                className = "No class name";
            }

            ex.Data.Add($"{className}.{methodName} : {key}", value);
            return ex;
        }
    }

ToJson method:

 public static class JsonContentExtension
    {
        public static string ToJson(this object obj)
        {
            try
            {
                return JsonConvert.SerializeObject(obj);
            }
            catch
            {
                return $"Object {obj.ToString()} is not serializable.";
            }
        }
    }

How to log details:

public override void OnException(ExceptionContext context)
    {
            var message = LogExceptionData(context.Exception.Data, context.Exception.Message);
            _logger.LogError(1, context.Exception, message);
            // . . .
    }

private string LogExceptionData(IDictionary data, string message)
        {
            if (message == null)
            {
                message = "No message";
            }

            if (data == null || data.Count == 0)
            {
                return message;
            }

            var errorData = $"{message}{Environment.NewLine}";
            errorData += $"Method parameters:{Environment.NewLine}";
            var i = 1;
            foreach (DictionaryEntry item in data)
            {
                var key = item.Key ?? "null";
                var value = item.Value ?? "null";
                errorData += $"[{i}] => {key} = {value}{Environment.NewLine}";
                i++;
            }
            errorData += $"Details:";

            return errorData;
        }

Body:
First point, it is not best practice to throw System.Exception from your code. You should create custom exception type.

Second, You can use Exception.Data property to pass more information with exception (ex in your case parameter details). Hope this help.

catch (Exception e)
    {
        // If using general exception
        var customException = new CustomException();
        customException.Data.Add(nameof(value1), JsonConvert.SerializeObject(value1))
         throw customException;
    }

Or

catch (Exception e)
    {
        // If using general exception
         e.Data.Add(nameof(value1), JsonConvert.SerializeObject(value1))
         throw e;
    }

Should not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.


问:
Can I execute Two different Classes from same jar file?
I have a project where in one package I have made Server and in Second Package I made Client. It is working fine. I want to create a Jar file. Is it possible to run Client and Server Separately from same jar file?

I have used jar file where there is only one main and when I run jar file, it automatically runs that class. Now here I will be having 2 executable classes. I want to pack them in only one jar and then want to run both from that same jar file. Is it possible? Any Suggestions, links will be of great help.

答:
Assuming both your Server and Client classes have main methods, you can execute them from the command line using the following:

java -cp jarFile.jar package1.Server

java -cp jarFile.jar package2.Client

ContentLicense: CC BY-SA 2.5


问:
How to store variables values in a class i.e "settings"?
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

```<code>public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}
</code>```

Controller class:

```<code>public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}
</code>```

And crème de la crème, problematic class:

```<code>public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}
</code>```

答:
The problem is you are instantiating Setting class twice. You set the

```<code>    settings.setDiamonds(true); //in one instance
</code>```

and you expect to retrive this value in second instance in class ProblematicOne.
Try to solve this by instantiating Settings only once in Controller class and pass the same to ProblematicOne. Frame your code such that you instantiate

```<code>    private Setting settings = new Settings();
</code>```

only once in your whole application. Consider making this class singleton. Read about singleton instantiation here
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

Body:
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}

Controller class:

public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}

And crème de la crème, problematic class:

public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}

Body:
The problem is you are instantiating Setting class twice. You set the

    settings.setDiamonds(true); //in one instance

and you expect to retrive this value in second instance in class ProblematicOne.
Try to solve this by instantiating Settings only once in Controller class and pass the same to ProblematicOne. Frame your code such that you instantiate

    private Setting settings = new Settings();

only once in your whole application. Consider making this class singleton. Read about singleton instantiation here
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html


问:
Why `cmd /k` and `cmd /c` remember the history of already finished cmd sub-processes?
Here're the command I've executed:

```<code>>cmd /k
>echo 1
1

>echo 2
2

>echo 3
3

>exit /b

>cmd /c "doskey /history"
echo 1
echo 2
echo 3
exit /b

>
</code>```

(tested on windows 7x64) According tho the process explorer the cmd /k starts a sub-process (not a thread). So after process is exited I would expect that it will clear his things from the memory. This thing happens on 3/4/.. spawned cmds , for /f , with called batch file.

答:
Short version:

The console window handles the command history

Detailed:

The processes of a command prompt window is as follows:

conhost.exe

  --- doskey.exe

  ------ cmd.exe

  --------- any sub-processes (In your case cmd /k)

As on Microsoft technet:

... If you exit and then restart a program from the same Command Prompt window, the command history from the previous program session is available.

  You must run Doskey.exe before you start a program. You cannot use doskey command-line options from a program's command prompt, even if the program has a shell command.

Doskey is executed under conhost.exe, the process that displays the command prompt window. This enables it to monitor keystrokes for all sub-processes and threads.

When you call cmd from within another process, the root CMD process handles the doskey history

Update:

As commented by MC ND, in Windows XP/2003/Vista/2008 the command history is handled by csrss.exe. From Windows 7 upwards, conhost.exe handles the command history - more here

Body:
Here're the command I've executed:

>cmd /k
>echo 1
1

>echo 2
2

>echo 3
3

>exit /b

>cmd /c "doskey /history"
echo 1
echo 2
echo 3
exit /b

>

(tested on windows 7x64) According tho the process explorer the cmd /k starts a sub-process (not a thread). So after process is exited I would expect that it will clear his things from the memory. This thing happens on 3/4/.. spawned cmds , for /f , with called batch file.


问:
angular2 d3.event.sourceEvent does not exist
trying to do drag function using d3 on angular2 I found a sample but in JS and trying to use it in ng2 however I have a problem with .sourceEvent it says its not part of the d3.event property.

js type :  https://bl.ocks.org/mbostock/6123708

public canvas = d3.select('my-app')
        .append('canvas')
        .attr('width', this.width)
        .attr('height', this.height)
        .attr('class', 'canvas');

    public drag = d3.behavior.drag()
        .on("drag", this.dragstart);

    dragstart (d) {
       d3.event.sourceEvent.stopPropagation();
        d3.select(this).classed("dragging", true);
    }```

答:
Try to use d3.event.stopPropagation() instead.

And predicting your next error... d3.select(this) won't work in Angular2 because the this keyword is related to an Angular component. Use d3.select(d3.event.target).


问:
ASP.NET application architecture: bet practice for lenghty background processes?
I'll try to be brief.

What is the best practice for calling a routine from an asp.net web application that initiates a lengthy 'background' process that must be run?

For example, I want to click a button on my webpage that says "Run data conversion" (for example). This data conversion routine may take 20-40 minutes to run, so it seems to me putting all that code into a asp.net web page is not the way to go....there is no need to run this background process thru the IIS server. A sperate service or app etc seemx the way to go...

The web app, and the background process will both run on my dedicated Win2003 server so I have lots of options - but what is the best one?

答: If you control the server, I would suggest creating a windows service - take the data conversion task outside of ASP.NET altogether; you wouldn't want ASP.NET restarting halfway through a 40 minutes conversion routine.</p>

OwnerDisplayName: MrEd

LastEditorDisplayName: splattne

OwnerDisplayName: TerryRoquito


问:
How do I return a List to JSON along with hard coded roots
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

```<code>public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}
</code>```

This works well at returning the following JSON:

```<code>[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]
</code>```

But now I want to return the following JSON (hard-coded for now, I will change the values later):

```<code>{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}
</code>```

How can I adapt my code to do that?

答:
Looks like you're using a jQuery grid like jQuery Bootgrid at least by the look of the output you need.

If thats the case, you can do the following.

1 Create the Data Types you need

Input that comes to the controller

```<code>   public class RequestData
        {
            public int current { get; set; }
            public string rowCount { get; set; }
        /*Any other fields that come from the api*/
        }
</code>```

The output you need

```<code> public class ResponseData<T> where T : class
    {
        public int current { get; set; } // current page
        public int rowCount { get; set; } // rows per page
        public T rows { get; set; } // items
        public int total { get; set; } // total rows for whole query
    }
</code>```

2 Put everything together

```<code>public JsonResult IndexJson(RequestData model)
{
    var contacts = (from x in db.ContactSet
    select new
    {
        x.AccountId,
        x.FirstName,
        x.LastName,
        x.FullName,
        x.JobTitle,
        x.ParentCustomerId,
        x.EMailAddress1,
        x.Telephone1,
        x.MobilePhone,
        x.Fax,
        x.GenderCode,
        x.BirthDate
    }).ToList();

    var tResult =
        ResponseData<YourObjectType>()
        {
            current = model.current,
            rowCount = model.rowCount,
            rows = contacts,
            total = contacts.Count
         };

    return Json(tResult, JsonRequestBehavior.AllowGet);
}
</code>```

Body:
I'm not entirely sure how to define this question but basically I'm developing an ASP.Net application where I am generating a JsonResult called IndexJson.

My code is as follows:

public JsonResult IndexJson()
{
    var contacts = (from x in db.ContactSet
                   select new
                   {
                       x.AccountId,
                       x.FirstName,
                       x.LastName,
                       x.FullName,
                       x.JobTitle,
                       x.ParentCustomerId,
                       x.EMailAddress1,
                       x.Telephone1,
                       x.MobilePhone,
                       x.Fax,
                       x.GenderCode,
                       x.BirthDate
                   }).ToList();

    return Json(contacts, JsonRequestBehavior.AllowGet);
}

This works well at returning the following JSON:

[{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...]

But now I want to return the following JSON (hard-coded for now, I will change the values later):

{
  "current": 1,
  "rowCount": 10,
  "rows": [{/*contact info*/}, {/*contact info*/}, {/*contact info*/}, ...],
  "total": 1123
}

How can I adapt my code to do that?

Body:
Looks like you're using a jQuery grid like jQuery Bootgrid at least by the look of the output you need.

If thats the case, you can do the following.

1 Create the Data Types you need

Input that comes to the controller

   public class RequestData
        {
            public int current { get; set; }
            public string rowCount { get; set; }
        /*Any other fields that come from the api*/
        }

The output you need

 public class ResponseData<T> where T : class
    {
        public int current { get; set; } // current page
        public int rowCount { get; set; } // rows per page
        public T rows { get; set; } // items
        public int total { get; set; } // total rows for whole query
    }

2 Put everything together

public JsonResult IndexJson(RequestData model)
{
    var contacts = (from x in db.ContactSet
    select new
    {
        x.AccountId,
        x.FirstName,
        x.LastName,
        x.FullName,
        x.JobTitle,
        x.ParentCustomerId,
        x.EMailAddress1,
        x.Telephone1,
        x.MobilePhone,
        x.Fax,
        x.GenderCode,
        x.BirthDate
    }).ToList();

    var tResult =
        ResponseData<YourObjectType>()
        {
            current = model.current,
            rowCount = model.rowCount,
            rows = contacts,
            total = contacts.Count
         };

    return Json(tResult, JsonRequestBehavior.AllowGet);
}


问:
get result of overpass api by osmbonuspack
Hi i every one i have used osmbonuspack(for android) for making feature of searching POI, this api offer option to post request to overpass api,i want to get this result in format json.Thank you for advanced.</p>

答: If you want to get the result in JSON then just query Overpass API directly and request JSON as output format. osmbonuspack has support for Overpass API via OverpassAPIProvider but is targeted at converting the results to markers.</p>


问:
Open Library Covers API Rate Limit
I am using PHP / Codeigniter to create a basic library web application. I am retrieving book ISBNs from a MySQL database and displaying the title (from my database) and cover image(from openlibrary.org). I am displaying 10 results per page, however I plan to have a paginated navigation bar on screen so the user can browse multiple pages.

All is working well so far, however looking at the Open Library Covers API Rate Limiting it says that;

The cover access by ids other than CoverID and OLID are rate-limited.
  Currently only 100 requests/IP are allowed for every 5 minutes.

If any IP tries to access more that the allowed limit, the service
  will return "403 Forbidden" status.

So, if I am displaying 10 results per page, that's 10 separate requests? And if 10 different users visit my page simultaneously, am I right in thinking that's 100 separate requests, I've exceeded my limit?

What would be the best way to avoid such a scenario? I've thought of two possibilities;

Use page caching in Codeigniter by adding $this->output->cache($n) in my controller. When I enable this I can see a file is created in application/cache containing the 10 records and corresponding images.

On page load, perform the API lookup then save the returned data (cover image) into my database. I'm not sure how to do this? Any advice appreciated.

Perhaps there is another way to approach this?

My working code is below if that helps.

Model

```<code>public function itemList() {
    $this->db->select('item_id, item_title, item_isbn');
    $this->db->from('item');
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

View

```<code><?php foreach ($items as $item):?>
    <h3><?php echo $item['item_title'] ?></h3>
    <img class="img-responsive thumbnail" src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-M.jpg">
<?php endforeach; ?>
</code>```

Controller

```<code>public function index() {
    $data = array(
        'items' => $this->items_model->itemList()
        );
    $this->load->view('item_view', $data);
}
</code>```

答:
Unless the 10 users are on the same IP address (not likely), each will only count as 10 views. A single user would have to open ten tabs and hit the page within the time limit (or refresh the page several times) to exceed the limit.

If they browse 10 pages within 5 minutes, they will see the error in the images. You can either put a message on the page to explain this, or rate limit how often they can update the page. You might try to cache the images on your site and then display them from there (no limits), but that may violate their TOS.

I went to their site, and they also offer all of the images for download. If you serve them from your site, you will completely avoid the rate limits.

Setting up a program to regularly download the images, un-zip them and download the data file on a regular basis should be an relatively easy task using PHP and curl.

Basically, you would:

Download the six zip archives for each size you want to host (s-Small, m-Medium, and l-Large). They are huge!

Download the index file.

Unzip these into temp folders.

Go through each folder and unzip the .tar files (containing the actual images) into an image folder.

Import the tab delimited index file into a table in your DB.

The documentation on the index file is sketchy, and it isn't clear if you can use an IBSN number to lookup the image filename. That would take some research and testing to work out.

Title: Open Library Covers API Rate Limit

Body:
I am using PHP / Codeigniter to create a basic library web application. I am retrieving book ISBNs from a MySQL database and displaying the title (from my database) and cover image(from openlibrary.org). I am displaying 10 results per page, however I plan to have a paginated navigation bar on screen so the user can browse multiple pages.

All is working well so far, however looking at the Open Library Covers API Rate Limiting it says that;

The cover access by ids other than CoverID and OLID are rate-limited.
  Currently only 100 requests/IP are allowed for every 5 minutes.

If any IP tries to access more that the allowed limit, the service
  will return "403 Forbidden" status.

So, if I am displaying 10 results per page, that's 10 separate requests? And if 10 different users visit my page simultaneously, am I right in thinking that's 100 separate requests, I've exceeded my limit?

What would be the best way to avoid such a scenario? I've thought of two possibilities;

Use page caching in Codeigniter by adding $this->output->cache($n) in my controller. When I enable this I can see a file is created in application/cache containing the 10 records and corresponding images.

On page load, perform the API lookup then save the returned data (cover image) into my database. I'm not sure how to do this? Any advice appreciated.

Perhaps there is another way to approach this?

My working code is below if that helps.

Model

public function itemList() {
    $this->db->select('item_id, item_title, item_isbn');
    $this->db->from('item');
    $query = $this->db->get();
    return $query->result_array();
}

View

<?php foreach ($items as $item):?>

<?php echo $item['item_title'] ?>

    <img class="img-responsive thumbnail" src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-M.jpg">
<?php endforeach; ?>

Controller

public function index() {
    $data = array(
        'items' => $this->items_model->itemList()
        );
    $this->load->view('item_view', $data);
}


问:
Regular expression month validation with text-mask directive
I'm using text-mask angular2 directive with ionic2.I have a month JS regular expression like this /^(0[1-9]|1[0-2])$/.It is working fine.But now I need to apply this for above directive.I have tried like below.But it is not working.Can you tell me why?

```<code>   mask: Array<string | RegExp>;

   constructor(){
     this.mask = [/0[1-9]/, /1[0-2]/];//not working
     //this.mask = [/[1-9]/, /\d/]; //this is working
    }
</code>```

答:
Each element in the array imposes restriction on what char a user can input. It seems they are context-unaware. [/0[1-9]/, /1[0-2]/] means the first symbol can consist of 0 and a digit from 1 to 9 and the second symbol should start with 1 and then be followed with 0, 1 or 2 - which is always false.

You may thus use an approximate mask like

```<code>this.mask = [/[01]/, /\d/];
</code>```

The first placeholder will be valid if 0 or 1 is typed, and the second placeholder will be valid for any digit.

And to make sure the month values are typed, I suggest adding pattern="0[1-9]|1[0-2]" for the on-submit validation.

Body:
I'm using text-mask angular2 directive with ionic2.I have a month JS regular expression like this /^(0[1-9]|1[0-2])$/.It is working fine.But now I need to apply this for above directive.I have tried like below.But it is not working.Can you tell me why?

   mask: Array<string | RegExp>;

   constructor(){
     this.mask = [/0[1-9]/, /1[0-2]/];//not working
     //this.mask = [/[1-9]/, /\d/]; //this is working
    }

Body:
Each element in the array imposes restriction on what char a user can input. It seems they are context-unaware. [/0[1-9]/, /1[0-2]/] means the first symbol can consist of 0 and a digit from 1 to 9 and the second symbol should start with 1 and then be followed with 0, 1 or 2 - which is always false.

You may thus use an approximate mask like

this.mask = [/[01]/, /\d/];

The first placeholder will be valid if 0 or 1 is typed, and the second placeholder will be valid for any digit.

And to make sure the month values are typed, I suggest adding pattern="0[1-9]|1[0-2]" for the on-submit validation.


问:
Height 100% and css issue with footer
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

```<code><div class="container">
<div id=nav>
NAV
</div>
<div id=core>
    <div id=content>
        <div id=tophea>
           TOP Content
        </div>
        <div id=msgs>
       MSG Content
        </div>
    </div>
    <div id="footer">
    Footer
    </div>
    </div>
</div>
</code>```

and css like this :

```<code>#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}
</code>```

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

答:
You can use a flex layout and set the main content area to flex-grow: 1 so it will consume all of the available space between your nav and footer, and that will push the footer to the bottom of the page when there isn't enough content.

body,
.container {
  min-height: 100vh;
  margin: 0;
}

.container,
#core {
  display: flex;
  flex-direction: column;
}

#core,
#content {
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div id=nav>
    NAV
  </div>
  <div id=core>
    <div id=content>
      <div id=tophea>
        TOP Content
      </div>
      <div id=msgs>
        MSG Content
      </div>
    </div>
    <div id="footer">
      Footer
    </div>
  </div>
</div></code>```

Title: Height 100% and css issue with footer

Body:
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

NAV

           TOP Content

       MSG Content

    Footer

and css like this :

#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

Body:
You can use a flex layout and set the main content area to flex-grow: 1 so it will consume all of the available space between your nav and footer, and that will push the footer to the bottom of the page when there isn't enough content.

body,
.container {
  min-height: 100vh;
  margin: 0;
}

.container,
#core {
  display: flex;
  flex-direction: column;
}

#core,
#content {
  flex-grow: 1;
}

<div class="container">
  <div id=nav>
    NAV
  </div>
  <div id=core>
    <div id=content>
      <div id=tophea>
        TOP Content
      </div>
      <div id=msgs>
        MSG Content
      </div>
    </div>
    <div id="footer">
      Footer
    </div>
  </div>
</div>


问:
Delete folder by name from google drive using gdrive
I have read the documentation for gdrive here, but I couldn't find a way to do what I want to do. I want to write a bash script to upload automatically a specific folder from my hard drive. The problem is that when I upload it several times, instead of replacing the old folder by the new one, it generates a new folder with the same name.

I could only find the following partial solutions to my problem:

Use update to replace files. The problem with this partial solution is that new files inside the folder could not get uploaded automatically, and I would have to change the bash script every time a new file is produced in the folder that I want to upload.

Erase the folder by its id from google drive and then upload the folder again. The problem here is that whenever I do this, the id of the uploaded folder chagnes, so I couldn't find a way to write a script to do the work.

I am looking for any method that solves my problem. But the precise questions that could help me are:

Is there a way to delete a folder from google drive (using gdrive) by its name instead of by its id?

Is there a way to get the id of a folder by its name? I guess not, since there can be several folders with the same name (but different ids) uploaded. Or am I missing something?

Is there a way to do a recursive update to renew all files that are already inside the folder uploaded on google drive and in addition upload those that are not yet uploaded?

In case it is relevant, I am using Linux Mint 18.1.

答:
Is there a way to delete a folder from google drive (using gdrive) by its name instead of by its id?

Nope. As your next question observes, there can be multiple such folders.

Is there a way to get the id of a folder by its name? I guess not, since there can be several folders with the same name (but different ids) uploaded. Or am I missing something?

You can get the ids (plural) of all folders with a given name.

gdrive  list -q "name = 'My folder name' and mimeType='application/vnd.google-apps.folder' and trashed=false"

Is there a way to do a recursive update to renew all files that are already inside the folder uploaded on google drive and in addition upload those that are not yet uploaded?

Yes, but obviously not with a single command. You'll need to write a short script using gdrive list and parse (awk works well) the output.


问:
if else statement return a string, error.
why do i get an error, is it because im missing a return after the if checks? could i resolve it by setting one last return to null </p>

```<code>public static String whoWins(rockPaperScissors user, rockPaperScissors computer){

    if(user == ROCK && computer == SCISSORSS){
        return "user wins";
    }
    if(user == PAPER && computer == ROCK){
        return " user wins";
    }
    if(user == SCISSORSS && computer == PAPER){
        return "user wins";
    }
    if(computer == ROCK && user == SCISSORSS){
        return "computer wins";
    }
    if(computer == PAPER && user == ROCK){
        return "computer wins";
    }
    if (computer == SCISSORSS && user == PAPER){
        return "computer wins";
    }
}
</code>```

答:
You get an error because your method does not always return a result. For example, what happens if user == null?

In my opinion, the cleanest way to handle this is to throw an exception because you should not reach the last line. IllegalArgumentException is a good candidate because the problem would come from invalid arguments passed to the method.

```<code>public static String whoWins(rockPaperScissors user, rockPaperScissors computer){
  [...]

  if (computer == SCISSORSS && user == PAPER){
    return "computer wins";
  }

  throw new IllegalArgumentException(...);
}
</code>```

Body:
why do i get an error, is it because im missing a return after the if checks? could i resolve it by setting one last return to null

public static String whoWins(rockPaperScissors user, rockPaperScissors computer){

    if(user == ROCK && computer == SCISSORSS){
        return "user wins";
    }
    if(user == PAPER && computer == ROCK){
        return " user wins";
    }
    if(user == SCISSORSS && computer == PAPER){
        return "user wins";
    }
    if(computer == ROCK && user == SCISSORSS){
        return "computer wins";
    }
    if(computer == PAPER && user == ROCK){
        return "computer wins";
    }
    if (computer == SCISSORSS && user == PAPER){
        return "computer wins";
    }
}

Body:
You get an error because your method does not always return a result. For example, what happens if user == null?

In my opinion, the cleanest way to handle this is to throw an exception because you should not reach the last line. IllegalArgumentException is a good candidate because the problem would come from invalid arguments passed to the method.

public static String whoWins(rockPaperScissors user, rockPaperScissors computer){
  [...]

  if (computer == SCISSORSS && user == PAPER){
    return "computer wins";
  }

  throw new IllegalArgumentException(...);
}


问:
jest snapshot testing: how to ignore part of the snapshot file in jest test results
Problem: ignore some part of the .snap file test results

the question here: there are some components in my test that have a random values and i don't really care about testing them. is there any way to ignore part of my X.snap file? so when i run tests in the future it won't give me test fail results.

答:
Actually, you need to mock the moving parts.

As stated in jest docs:

Your tests should be deterministic. That is, running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data.

If it's something related to time, you could use

```<code>Date.now = jest.fn(() => 1482363367071);
</code>```

Body:
Actually, you need to mock the moving parts.

As stated in jest docs:

Your tests should be deterministic. That is, running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data.

If it's something related to time, you could use

Date.now = jest.fn(() => 1482363367071);


问:
Asset Pipeline not including CSS or JS in Grails 3 on external Tomcat 7/8
When I upload the app.war.original from a 3.2.8 app to a tomcat7 or tomcat8 running on a java 1.8.0_51 server, assets are not included in my source, as if the asset:stylesheet and asset:javascript tags didn't exist in my layout. </p>

<p>The app is running fine with : </p>

```<code>java -D"grails.env"=prod -jar .\build\libs\app-x.y.z.war
</code>```

答: Well, that was quartz-monitor plugin pulling an old version of asset-pipeline in my war file. </p>

Body:
When I upload the app.war.original from a 3.2.8 app to a tomcat7 or tomcat8 running on a java 1.8.0_51 server, assets are not included in my source, as if the asset:stylesheet and asset:javascript tags didn't exist in my layout.

The app is running fine with :

java -D"grails.env"=prod -jar .\build\libs\app-x.y.z.war


答:
You can use calculations in css to help with this.

```<code>#core {
    height: (100vh - 55px)
}
</code>```

100vh is 100% of the viewport, while he 55px is the height of the footer. Add any other elements to the calculation if you give them a height also e.g.

```<code>#header{
    height: 45px
}
#core {
    height: (100vh - 100px)
}
</code>```

Title: Height 100% and css issue with footer

Body:
You can use calculations in css to help with this.

#core {
    height: (100vh - 55px)
}

100vh is 100% of the viewport, while he 55px is the height of the footer. Add any other elements to the calculation if you give them a height also e.g.

#header{
    height: 45px
}
#core {
    height: (100vh - 100px)
}


问:
Does angular4 empower you to generate native mobile code/binary without any external framework which angular2 was not capable of?
What does 'Develop Across All Platforms' in angular4 mean?

https://angular.io says

Learn one way to build applications with Angular and reuse your code
  and abilities to build apps for any deployment target. For web, mobile
  web, native mobile and native desktop.

Does it mean you can generate native android/ios/desktop apps from angular web client project(killing hybrid frameworks like ionic)? Or does it mean you can embed the entire web client inside a android/ios app such that its indistinguishable ? I don't see any reference to generating native apps in documentation though.

答:
This is only a guess, but could it be that the third party code that provides the "native" platform was not yet available at the time of Angular 2 realease (it was only 6 mo ago, after all), but now new versions of ionic and the like have come out for use with Angular 2/4.

In other words perhaps the theory of that capability became reality since the last major release, and therefore warrants mention in new release notes and pr.


问:
Multiple threads and AtomicInteger
I took this code from a tutorial on atomics, it stated :-

"By using AtomicInteger as a replacement for Integer we're able to increment the number concurrently in a thread-safe manor without synchronizing the access to the variable. The method incrementAndGet() is an atomic operation so we can safely call this method from multiple threads."

It said this would return the correct result, 1000 however neither instance reaches 1000, they are usually considerably less, e.g.

```<code>test1 result = 532
test2 result = 128
</code>```

Whats wrong ?

```<code>public class AtomicsTest {

    public static void main(String... args){

        AtomicsTest test = new AtomicsTest();
        test.test1();
        test.test2();
    }

    public void test1() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
        System.out.println("test1 result = "+ atomicInt.get());
        executor.shutdown();
    }

    public void test2() {

        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newFixedThreadPool(2);
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
        System.out.println("test2 result = " + atomicInt.get());
        executor.shutdown();
    }
}
</code>```

答:
Your issue is that you immediately print the value after having submitted the threads, despite not all threads necessarily having completed.

```<code>public void test1() {
    AtomicInteger atomicInt = new AtomicInteger(0);

    ExecutorService executor = Executors.newSingleThreadExecutor();
    IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));

    // All threads submitted (not necessarily finished)

    System.out.println("test1 result = "+ atomicInt.get());

    executor.shutdown();

    // Threads are still not necessarily done
}
</code>```

If you explicitly wait for the executor service to finish before you print the value you should see the result you expect:

```<code>public void test1() {
    try {
        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));

        executor.shutdown();
        // Wait a maximum of ~a million billion years
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.HOURS);

        System.out.println("test1 result = "+ atomicInt.get());
    }
    catch (InterruptedException ex)
    {
        // Oh no!
    }
}
</code>```

Title: Multiple threads and AtomicInteger

Body:
I took this code from a tutorial on atomics, it stated :-

"By using AtomicInteger as a replacement for Integer we're able to increment the number concurrently in a thread-safe manor without synchronizing the access to the variable. The method incrementAndGet() is an atomic operation so we can safely call this method from multiple threads."

It said this would return the correct result, 1000 however neither instance reaches 1000, they are usually considerably less, e.g.

test1 result = 532
test2 result = 128

Whats wrong ?

public class AtomicsTest {

    public static void main(String... args){

        AtomicsTest test = new AtomicsTest();
        test.test1();
        test.test2();
    }

    public void test1() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
        System.out.println("test1 result = "+ atomicInt.get());
        executor.shutdown();
    }

    public void test2() {

        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newFixedThreadPool(2);
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));
        System.out.println("test2 result = " + atomicInt.get());
        executor.shutdown();
    }
}

Body:
Your issue is that you immediately print the value after having submitted the threads, despite not all threads necessarily having completed.

public void test1() {
    AtomicInteger atomicInt = new AtomicInteger(0);

    ExecutorService executor = Executors.newSingleThreadExecutor();
    IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));

    // All threads submitted (not necessarily finished)

    System.out.println("test1 result = "+ atomicInt.get());

    executor.shutdown();

    // Threads are still not necessarily done
}

If you explicitly wait for the executor service to finish before you print the value you should see the result you expect:

public void test1() {
    try {
        AtomicInteger atomicInt = new AtomicInteger(0);

        ExecutorService executor = Executors.newSingleThreadExecutor();
        IntStream.range(0,1000).forEach(i->executor.submit( atomicInt::incrementAndGet ));

        executor.shutdown();
        // Wait a maximum of ~a million billion years
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.HOURS);

        System.out.println("test1 result = "+ atomicInt.get());
    }
    catch (InterruptedException ex)
    {
        // Oh no!
    }
}


问:
Cannot resolve symbole 'input' JAVA
so I want to do a little alround program with quiz etc (won't paste the entire code because its 300 lines of basic stuff), and I want a boolean that repeats a gambling game for me, so when I get to the line:

```<code>String PlayAgain = input.nextLine();
</code>```

I get the error: Cannot resolve symbole 'input'.

The code for the little game is here:

```<code>enter  boolean InGame = true;
        while (InGame == true);

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs() ist eine Methode die den Betrag einer Zahl zurueck gibt.
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = input.nextLine();
        if  (PlayAgain == "Ja");
</code>```

Can you help me?

答:
The variable scan looks like the one you use to store user's input. I suggest you to use this one.

Or to declare Scanner input=new Scanner(System.in) because I cannot see it in the code you posted

Title: Cannot resolve symbole 'input' JAVA

Body:
so I want to do a little alround program with quiz etc (won't paste the entire code because its 300 lines of basic stuff), and I want a boolean that repeats a gambling game for me, so when I get to the line:

String PlayAgain = input.nextLine();

I get the error: Cannot resolve symbole 'input'.

The code for the little game is here:

enter  boolean InGame = true;
        while (InGame == true);

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs() ist eine Methode die den Betrag einer Zahl zurueck gibt.
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = input.nextLine();
        if  (PlayAgain == "Ja");

Can you help me?


问:
Command Line Copy or Delete
I used robocopy to copy just pdf's from an external hard drive and place them on our server.

source destination *.pdf

It copied over all the folders and subfolders even if there wasn't a .pdf file in the folder. Can someone help me either....

a) Delete empty folders or b) Copy over only folders and subfolders that have .pdf's in them?

Thank you!

答:
Try using this ROBOCOPY command for deleting empty folders:

```<code>ROBOCOPY myfolder myfolder /S /MOVE
</code>```

Here source and destination both are 'myfolder'.

Title: Command Line Copy or Delete

Body:
Try using this ROBOCOPY command for deleting empty folders:

ROBOCOPY myfolder myfolder /S /MOVE

Here source and destination both are 'myfolder'.


问:
Submit using jquery in Internet Explorer
I have a bit of a problem submitting my forms in Internet Explorer. It works fine in other browsers like Google Chrome and Firefox.

Here is my code:

```<code>form action="?page=addStorageEngine" method="post" id="createStorage">
   <tr>
       <th>Storagename:</th>
       <td><input type="text" name="givenStorageName" value=""></td>
   </tr>
</form>

<input form="createStorage" type="submit" value="Opprett Lager" href="?page=storageAdm">
</code>```

And here is my jquery code:

```<code>$(function POSTstorageInfo() {

$('#createStorage').submit(function () {
    var url = $(this).attr('action');
    var data = $(this).serialize();

    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: 'json',
        success: function () {
            UpdateStorageTable();
        }
    });
     return false;
  });
});
</code>```

It seems like it won't trigger "submit" function. But how to make this work in IE?

答:
Change this:

```<code>$('#createStorage').submit(function () {
</code>```

to this:

```<code>$(document.body).on('click', '#createStorage', function (e) {
</code>```

The submit action will not be valid outside of the form tag

Body:
I have a bit of a problem submitting my forms in Internet Explorer. It works fine in other browsers like Google Chrome and Firefox.

Here is my code:

form action="?page=addStorageEngine" method="post" id="createStorage">

       Storagename:
       <input type="text" name="givenStorageName" value="">

</form>

<input form="createStorage" type="submit" value="Opprett Lager" href="?page=storageAdm">

And here is my jquery code:

$(function POSTstorageInfo() {

$('#createStorage').submit(function () {
    var url = $(this).attr('action');
    var data = $(this).serialize();

    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: 'json',
        success: function () {
            UpdateStorageTable();
        }
    });
     return false;
  });
});

It seems like it won't trigger "submit" function. But how to make this work in IE?

Body:
Change this:

$('#createStorage').submit(function () {

to this:

$(document.body).on('click', '#createStorage', function (e) {

The submit action will not be valid outside of the form tag


问:
Making a NxN tic tac toe GUI wpf c#
I am making a NxN tic tac toe game in WPF c#. I want user to enter Rows and Column count(NxN), and my code will generate those number of columns and rows. I can't figure it out, how will I produce that number of rows and columns dynamically. I have posted my XAML code, is there a way that I can loop my XAML code?
    thanks</p>

```<code><Grid x:Name="Container">
    <!-- First here i want to make N columns-->
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <!-- Here i want to make N rows-->
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!-- Then here i want to add that number of buttons in N x N columns and rows -->
    <Button x:Name="Button0_0" Grid.Row="0" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button0_1" Grid.Row="0" Grid.Column="1" Click="Button_Click" />
    <Button x:Name="Button0_2" Grid.Row="0" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button1_0" Grid.Row="1" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button1_1" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button1_2" Grid.Row="1" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button2_0" Grid.Row="2" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button2_1" Grid.Row="2" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button2_2" Grid.Row="2" Grid.Column="2" Click="Button_Click"/>
</Grid>
</code>```

答:
As Zohar has mentioned you could use the code behind to add child GridColumn's to the Grid.ColumnDefinitions, and then add Button's to the Container Grid. Its an easy approach, but it means using code behind which causes many frowns.

Personally I would rather create a Behaviour and attach it to the Grid. Have your behaviour bind to an integer of Rows and Columns on your viewmodel, and then add ColumnDefinitions and RowDefinitions to the AssociatedObject. Behaviours are a great way to encapsulate reusable features, and eliminates the need for writing code behind.

This chap demonstrates how to create behaviours that bind to your model, and also how to attach them to an element in the view.

http://julmar.com/blog/programming/playing-with-wpf-behaviors-a-watermarktext-behavior/

Title: Making a NxN tic tac toe GUI wpf c#

Body:
I am making a NxN tic tac toe game in WPF c#. I want user to enter Rows and Column count(NxN), and my code will generate those number of columns and rows. I can't figure it out, how will I produce that number of rows and columns dynamically. I have posted my XAML code, is there a way that I can loop my XAML code?
    thanks

<Grid x:Name="Container">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button x:Name="Button0_0" Grid.Row="0" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button0_1" Grid.Row="0" Grid.Column="1" Click="Button_Click" />
    <Button x:Name="Button0_2" Grid.Row="0" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button1_0" Grid.Row="1" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button1_1" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button1_2" Grid.Row="1" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button2_0" Grid.Row="2" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button2_1" Grid.Row="2" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button2_2" Grid.Row="2" Grid.Column="2" Click="Button_Click"/>
</Grid>


问:
How to not minify a single variable?
In my case, using AngularJS, i have a json with some configurations that can be used in controllers.
The problem happens when i minify the application and the controller variables name does not match with the json.

Is there a way to not minify a single variabe?

My code:
setting.json

```<code>{
   "settings": {
      "adIndex": 3
    }
}
</code>```

controller:

```<code>function settingsService($q, $http, $log) {
  var settings = {
    adIndex: 0
  };

  var service = {
    init: init,
    getAdIndex: getAdIndex
  };
  return service;

  function init() {
    var deferred = $q.defer();

    $http.get('assets/settings/settings.json').then(function(response) {
      var loaded = response.data.settings;
      if (loaded) {
        settings = angular.extend(settings, loaded);
      }
      deferred.resolve(settings);
    }, function(error) {
      $log.info('Error loading settings', error);
      deferred.reject(error);
    });

    return deferred.promise;
  }

  function getAdIndex() {
    return settings.adIndex;
  }
}
</code>```

UPDATE

After your suggestions i made some changes on code, but the problem not yet resolved.
The code in controller is now:

```<code>function settingsService($q, $http, $log) {
  var settings = {
    'adIndex': 0
  };

  var service = {
    init: init,
    getAdIndex: getAdIndex
  };
  return service;

  function init() {
    var deferred = $q.defer();

    $http.get('assets/settings/settings.json').then(function(response) {
      var loaded = response.data['settings'];
      if (loaded) {
        settings = angular.extend(settings, loaded);
      }
      deferred.resolve(settings);
    }, function(error) {
      $log.info('Error loading settings', error);
      deferred.reject(error);
    });

    return deferred.promise;
  }

  function getAdIndex() {
    $log.debug('Object: ', settings); // result: settings { adIndex: 3 }
    $log.debug('Value: ', settings['adIndex']); // result: 0
    return settings['adIndex'];
  }
}
</code>```

How can 'adIndex' have 2 different values in logs?

答:
```<code>  var settings = {
    "adIndex": 0  // quotes around the key, JSON style
  };
</code>```

Not 100% sure how your minifier will handle this, but usually they can not modify string values. If the above doesn't work, you can do something slightly more verbose:

```<code>var settings = {};
settings['adIndex'] = 0;
</code>```

In this case, the variable settings will be minified, but the string 'adIndex' will remain unchanged.

Title: How to not minify a single variable?

Body:
In my case, using AngularJS, i have a json with some configurations that can be used in controllers.
The problem happens when i minify the application and the controller variables name does not match with the json.

Is there a way to not minify a single variabe?

My code:
setting.json

{
   "settings": {
      "adIndex": 3
    }
}

controller:

function settingsService($q, $http, $log) {
  var settings = {
    adIndex: 0
  };

  var service = {
    init: init,
    getAdIndex: getAdIndex
  };
  return service;

  function init() {
    var deferred = $q.defer();

    $http.get('assets/settings/settings.json').then(function(response) {
      var loaded = response.data.settings;
      if (loaded) {
        settings = angular.extend(settings, loaded);
      }
      deferred.resolve(settings);
    }, function(error) {
      $log.info('Error loading settings', error);
      deferred.reject(error);
    });

    return deferred.promise;
  }

  function getAdIndex() {
    return settings.adIndex;
  }
}

UPDATE

After your suggestions i made some changes on code, but the problem not yet resolved.
The code in controller is now:

function settingsService($q, $http, $log) {
  var settings = {
    'adIndex': 0
  };

  var service = {
    init: init,
    getAdIndex: getAdIndex
  };
  return service;

  function init() {
    var deferred = $q.defer();

    $http.get('assets/settings/settings.json').then(function(response) {
      var loaded = response.data['settings'];
      if (loaded) {
        settings = angular.extend(settings, loaded);
      }
      deferred.resolve(settings);
    }, function(error) {
      $log.info('Error loading settings', error);
      deferred.reject(error);
    });

    return deferred.promise;
  }

  function getAdIndex() {
    $log.debug('Object: ', settings); // result: settings { adIndex: 3 }
    $log.debug('Value: ', settings['adIndex']); // result: 0
    return settings['adIndex'];
  }
}

How can 'adIndex' have 2 different values in logs?

Body:
  var settings = {
    "adIndex": 0  // quotes around the key, JSON style
  };

Not 100% sure how your minifier will handle this, but usually they can not modify string values. If the above doesn't work, you can do something slightly more verbose:

var settings = {};
settings['adIndex'] = 0;

In this case, the variable settings will be minified, but the string 'adIndex' will remain unchanged.