问:
How to watch object changes with rxjs 5
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

```<code>let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')
</code>```

However, I'm sure there is more elegant way of doing it.
Any Ideas?

答:
I would suggest using something similar to redux approach, when changes to the object can be made in predefined way:

function factory(reducerByType, initialState) {
  const action$ = new Rx.Subject();
  const state$ = action$
    .startWith(initialState)
    .scan((state, action) => {
      if (reducerByType.hasOwnProperty(action.type)) {
        return reducerByType[action.type](state, action);
      }

      return state;
    })
    .distinctUntilChanged();

  return {
    action$,
    state$,
    dispatch: action => action$.next(action)
  }
}

const {state$, dispatch} = factory({
  ADD: (state, action) =>  state + action.number,
  SUBTRACT: (state, action) =>  state - action.number,
}, 0);

state$.subscribe(val => console.log(val));

dispatch({
  type: 'ADD',
  number: 10,
});

dispatch({
  type: 'SUBTRACT',
  number: 15,
});

dispatch({
  type: 'SUBTRACT',
  number: 0,
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script></code>```

Title: How to watch object changes with rxjs 5

Body:
I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before,
yet the answer is irrelevant since RXjs verion 5 do not include the ofObjectChanges in it's API anymore.

I've looked at some "hacks" like creating an observer which return a function:

let myObservable =  new Observable((observer) => {
  return (data) => {
    observer.next(data)
  }
})
//...
myObservable.subscribe()('someData')

However, I'm sure there is more elegant way of doing it.
Any Ideas?

Body:
I would suggest using something similar to redux approach, when changes to the object can be made in predefined way:

function factory(reducerByType, initialState) {
  const action$ = new Rx.Subject();
  const state$ = action$
    .startWith(initialState)
    .scan((state, action) => {
      if (reducerByType.hasOwnProperty(action.type)) {
        return reducerByType[action.type](state, action);
      }

      return state;
    })
    .distinctUntilChanged();

  return {
    action$,
    state$,
    dispatch: action => action$.next(action)
  }
}

const {state$, dispatch} = factory({
  ADD: (state, action) =>  state + action.number,
  SUBTRACT: (state, action) =>  state - action.number,
}, 0);

state$.subscribe(val => console.log(val));

dispatch({
  type: 'ADD',
  number: 10,
});

dispatch({
  type: 'SUBTRACT',
  number: 15,
});

dispatch({
  type: 'SUBTRACT',
  number: 0,
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>


来源: stackexchange

问:
PHP preg_replace string
I was using ereg_replace function to replace all tags in my HTML with blank. Tags in my case look like this: {{AGE}} {{NAME}} {{EMAIL_ADDRESS}}

I was using this sentence (was removed in PHP 7):

```<code>$my_string = ereg_replace("\{\{[a-zA-Z_0-9]+\}\}", "", $my_string);
</code>```

Now I would like to use alternative sentence to ereg_replace and I tried with this:

```<code>$my_string = preg_replace("\{\{[a-zA-Z_0-9]+\}\}", "", $my_string);
</code>```

It throws out error. Looks like 1st parameter for preg is not same as for ereg. Can someone tell me how to fix it to replace all tags which have format {{something here}}

Thanks.

答:
With preg_*-functions, your expressions require a delimiter (some character at the beginning and end of your expression that tells the underlying engine where your expression ends and any optional modifiers begin).

Most developers use / for a delimiter, so:

```<code>$my_string = preg_replace("/\{\{[a-zA-Z_0-9]+\}\}/", "", $my_string);
</code>```

Although I don't think the { and } characters have special meaning in regular expressions, so you might be able to get away with not escaping them:

```<code>$my_string = preg_replace("/{{[a-zA-Z_0-9]+}}/", "", $my_string);
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP preg_replace string

Body:
I was using ereg_replace function to replace all tags in my HTML with blank. Tags in my case look like this: {{AGE}} {{NAME}} {{EMAIL_ADDRESS}}

I was using this sentence (was removed in PHP 7):

$my_string = ereg_replace("\{\{[a-zA-Z_0-9]+\}\}", "", $my_string);

Now I would like to use alternative sentence to ereg_replace and I tried with this:

$my_string = preg_replace("\{\{[a-zA-Z_0-9]+\}\}", "", $my_string);

It throws out error. Looks like 1st parameter for preg is not same as for ereg. Can someone tell me how to fix it to replace all tags which have format {{something here}}

Thanks.

Body:
With preg_*-functions, your expressions require a delimiter (some character at the beginning and end of your expression that tells the underlying engine where your expression ends and any optional modifiers begin).

Most developers use / for a delimiter, so:

$my_string = preg_replace("/\{\{[a-zA-Z_0-9]+\}\}/", "", $my_string);

Although I don't think the { and } characters have special meaning in regular expressions, so you might be able to get away with not escaping them:

$my_string = preg_replace("/{{[a-zA-Z_0-9]+}}/", "", $my_string);


问:
$modal.modal is not a function in FooTable
I am following this Tutorial.

Here is my code (I've excluded my table HTML):

```<code>@model IEnumerable<JMWebApp.Models.Job>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Job Manager";
}

<div class="modal fade" id="editor-modal" tabindex="-1" role="dialog" aria-labelledby="editor-title">
    <style scoped>
        .form-group.required .control-label:after {
            content:"*";
            color:red;
            margin-left: 4px;
        }
    </style>
    <div class="modal-dialog" role="document">
        <form class="modal-content form-horizontal" id="editor">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">x</span></button>
                <h4 class="modal-title" id="editor-title">Add Row</h4>
            </div>
            <div class="modal-body">
                <input type="number" id="id" name="id" class="hidden"/>
            </div>
            <div class="form-group required">
                <label for="reference" class="col-sm-3 control-label">Reference</label>
                <div class="col-sm-9">
                    <input type="text" class="form-control" id="reference" name="reference" placeholder="Reference" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Save Changes</button>
                <button type="button" class="btn btn-default">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript">
    jQuery(function($) {
        var $modal = $('#editor-modal'),
            $editor = $('#editor'),
            $editorTitle = $('#editor-title'),
            ft = FooTable.init('#editing-example',
                {
                    editing: {
                        editRow: function(row) {
                            var values = row.val();
                            $editor.find('#id').val(values.id);
                            $editor.find('#reference').val(values.reference);
                            $modal.data('row', row);
                            $modal.modal('show');
                            $editorTitle.text('Edit row #' + values.id);
                        }
                    }
                });
    });
</script>
</code>```

In my Layout file I define my scripts as so:

```<code><head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/scripts/jquery-1.10.2.min.js"></script>
    <script src="~/scripts/footable.min.js"></script>
    <link href="~/Content/site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/footable.bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/footable.fontawesome.css" rel="stylesheet" type="text/css" />
</head>
</code>```

I am having two issues with this. First of all the icons on the 'FooTable' are not displaying correctly, they just look like jumbled characters. I did read an answer before that there are a number of font files I needed to include.

I tried that but it didn't work, also I couldn't find any guidance on the FooTable website to include these icons.

Secondly I'm getting an error $modal.modal is not a function when I am attempting to edit the rows and show the modal. I also read a few answers to this in that my jQuery must be resolved before bootstrap, but as far as I can see in my Layout the scripts are loaded correctly.

I'd appreciate any help.

答:
bootstrap.min.js will be helpful for you, kindly read the below

Modal is defined in bootstrap.js not jQuery. It's also important to note that bootstrap actually needs jQuery to define the modal function, so it's vital that you include jQuery before including bootstrap's javascript. To avoid the error just be sure to include jQuery then bootstrap's javascript before you call the modal function.

Source: https://stackoverflow.com/a/28173513/3397630

Hope it was helpful

Thanks

Karthik

Body:
I am following this Tutorial.

Here is my code (I've excluded my table HTML):

@model IEnumerable<JMWebApp.Models.Job>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Job Manager";
}

        <form class="modal-content form-horizontal" id="editor">

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">x</button>

Add Row

                <input type="number" id="id" name="id" class="hidden"/>

                Reference

                    <input type="text" class="form-control" id="reference" name="reference" placeholder="Reference" required>

                <button type="submit" class="btn btn-primary">Save Changes</button>
                <button type="button" class="btn btn-default">Cancel</button>

        </form>

In my Layout file I define my scripts as so:

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="~/Content/site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/footable.bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/footable.fontawesome.css" rel="stylesheet" type="text/css" />

I am having two issues with this. First of all the icons on the 'FooTable' are not displaying correctly, they just look like jumbled characters. I did read an answer before that there are a number of font files I needed to include.

I tried that but it didn't work, also I couldn't find any guidance on the FooTable website to include these icons.

Secondly I'm getting an error $modal.modal is not a function when I am attempting to edit the rows and show the modal. I also read a few answers to this in that my jQuery must be resolved before bootstrap, but as far as I can see in my Layout the scripts are loaded correctly.

I'd appreciate any help.


问:
Selecting a specific image from CardImage List bot framework
I'm currently building a bot with the ability to build a dynamic carousel of hero cards, however I haven't found many examples that show to specify which image to use on which card.

```<code>public async Task Styles(IDialogContext context, LuisResult result)
        {
            InfoClass IC = new InfoClass();
            int count = IC.BuildArray().Length;
            PolaroidObject[] glasses = IC.BuildArray();
            int x = 0;
            var reply = context.MakeMessage();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            //Storing Images into variables
            List<CardImage> images = new List<CardImage>();
            CardImage Ci1 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci2 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/01/20035406lbuc/high-res/20035406lbuc_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci3 = new CardImage("https://polaroideyewear.com/en/sunglasses/pld/2017/PLD-4049-S.html");
            CardImage Ci4 = new CardImage("https://polaroideyewear.com/en/sunglasses/pld/2017/PLD-4050-S.html");
            CardImage Ci5 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003940010ex/high-res/2003940010ex_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci6 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci7 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            images.Add(Ci1);
            images.Add(Ci2);
            images.Add(Ci3);
            images.Add(Ci4);
            images.Add(Ci5);
            images.Add(Ci6);
            images.Add(Ci7);
            for (int z = 1; z <= count; z++)
            {
                HeroCard hc = new HeroCard()
                {
                    Title = glasses[x].Shape,
                    Images = images
                };
                reply.Attachments.Add(hc.ToAttachment());
                x++;
            }
            await context.PostAsync(reply);
            context.Wait(MessageReceived);
        }
</code>```

This is my current way of doing it, this works however it only loads the first image in the list. I'm looking for a way to use something like you would an array where you could specify "Images = images[z]".

Also on a side note, I'm not sure about the best way to save these images, I have got a folder with the images and a get/set class. I was hoping to call them in the same way I'm doing the shape, however it complains and asks for a List<CardImage> rather than a string.

答:
You need to attach one image to each card, rather than the whole list - something like this, assuming x is the index:

```<code>HeroCard hc = new HeroCard()
{
    Title = glasses[x].Shape,
    Images = new List<CardImage> { images[x] }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently building a bot with the ability to build a dynamic carousel of hero cards, however I haven't found many examples that show to specify which image to use on which card.

public async Task Styles(IDialogContext context, LuisResult result)
        {
            InfoClass IC = new InfoClass();
            int count = IC.BuildArray().Length;
            PolaroidObject[] glasses = IC.BuildArray();
            int x = 0;
            var reply = context.MakeMessage();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            //Storing Images into variables
            List<CardImage> images = new List<CardImage>();
            CardImage Ci1 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci2 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/01/20035406lbuc/high-res/20035406lbuc_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci3 = new CardImage("https://polaroideyewear.com/en/sunglasses/pld/2017/PLD-4049-S.html");
            CardImage Ci4 = new CardImage("https://polaroideyewear.com/en/sunglasses/pld/2017/PLD-4050-S.html");
            CardImage Ci5 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003940010ex/high-res/2003940010ex_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci6 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            CardImage Ci7 = new CardImage("https://polaroideyewear.com/content/dam/products/brands/pld/2017/04/2003960807lm/high-res/2003960807lm_p00.jpg/_jcr_content/renditions/cq5dam.web.1280.1280.jpeg");
            images.Add(Ci1);
            images.Add(Ci2);
            images.Add(Ci3);
            images.Add(Ci4);
            images.Add(Ci5);
            images.Add(Ci6);
            images.Add(Ci7);
            for (int z = 1; z <= count; z++)
            {
                HeroCard hc = new HeroCard()
                {
                    Title = glasses[x].Shape,
                    Images = images
                };
                reply.Attachments.Add(hc.ToAttachment());
                x++;
            }
            await context.PostAsync(reply);
            context.Wait(MessageReceived);
        }

This is my current way of doing it, this works however it only loads the first image in the list. I'm looking for a way to use something like you would an array where you could specify "Images = images[z]".

Also on a side note, I'm not sure about the best way to save these images, I have got a folder with the images and a get/set class. I was hoping to call them in the same way I'm doing the shape, however it complains and asks for a List<CardImage> rather than a string.

Body:
You need to attach one image to each card, rather than the whole list - something like this, assuming x is the index:

HeroCard hc = new HeroCard()
{
    Title = glasses[x].Shape,
    Images = new List<CardImage> { images[x] }
};


问:
Cannot find CurvedChildLayoutManager in Android Wear com.google.android.support:wearable:2.0.0
I want to create a Curved Layout in Android Wear. This is the tutorial.

In this web, Google let me create a class MyLauncherChildLayoutManager extends CurvedChildLayoutManager, but I can't find the CurvedChildLayoutManager in my Android studio.

I find the API with android.support.wearable.view, and this CurvedChildLayoutManager class is included in list.
This is the Api web: CurvedChildLayoutManager

This is my module gradle dependencies

```<code>dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.google.android.support:wearable:+'
  compile 'com.google.android.gms:play-services-wearable:+'
  //this provided is auto create when I create my android wear project, I try to annotation it,but also can't find
  provided 'com.google.android.wearable:wearable:+'
}
</code>```

But in my Android studio External Libraries directory -> wearable-2.0.0, I can't find CurvedChildLayoutManager class.

Why can't I find? This wearable library version is the latest version.
Please help me, thanks.

答: In the SDK manager, make sure you have the latest versions of the Android Support Library and the Android Support Repository. Then use version 2.0.2: (com.google.android.support:wearable:2.0.2) and it should be there :)</p>

Body:
I want to create a Curved Layout in Android Wear. This is the tutorial.

In this web, Google let me create a class MyLauncherChildLayoutManager extends CurvedChildLayoutManager, but I can't find the CurvedChildLayoutManager in my Android studio.

I find the API with android.support.wearable.view, and this CurvedChildLayoutManager class is included in list.
This is the Api web: CurvedChildLayoutManager

This is my module gradle dependencies

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.google.android.support:wearable:+'
  compile 'com.google.android.gms:play-services-wearable:+'
  //this provided is auto create when I create my android wear project, I try to annotation it,but also can't find
  provided 'com.google.android.wearable:wearable:+'
}

But in my Android studio External Libraries directory -> wearable-2.0.0, I can't find CurvedChildLayoutManager class.

Why can't I find? This wearable library version is the latest version.
Please help me, thanks.


问:
query_exec(SELECT * FROM myTable) fails on pyqt5
i have a function like below

```<code>def updateExpenseEntryToDb (self):
    self.day = self.line_edit1.text()
    self.category = self.line_edit2.text()
    self.amount = self.line_edit3.text()

    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('expenses.db')
    db.open()
    query = QSqlQuery()
    query.exec_("create table expense(date DATE primary key, "
     "category varchar(20), amount varchar(20))")
    query.exec_("insert into expense (date,category,amount) values('%s','%s','%s')" % (self.day, self.category, self.amount))
    db.close()

    db1 = QSqlDatabase.addDatabase('QSQLITE')
    db1.setDatabaseName('expenses.db')
    db1.open()
    query1 = QSqlQuery()
    query1.exec_("SELECT date, category, amount FROM expenses.expense")

    while (query1.next()):
        extractedDate = query1.value(0).toString()
        extractedcategory = query1.value(1).toString()
        extractedAmount = query1.value(2).toString()
        self.line_edit1.setText(extractedDate)
        self.line_edit2.setText(extractedcategory)
        self.line_edit3.setText(extractedAmount)
    db1.close()
</code>```

Insertion of values into DB works but not the retrieval of info from DB. What am i doing wrong ? seems like select query doesnt retrieve anything at all

答:
Put query.first() before while (query1.next()): But, the first row won't be used.

Better:

```<code>query.first()
while query.isValid():
    # Your Code
    query.next()
</code>```

Body:
i have a function like below

def updateExpenseEntryToDb (self):
    self.day = self.line_edit1.text()
    self.category = self.line_edit2.text()
    self.amount = self.line_edit3.text()

    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('expenses.db')
    db.open()
    query = QSqlQuery()
    query.exec_("create table expense(date DATE primary key, "
     "category varchar(20), amount varchar(20))")
    query.exec_("insert into expense (date,category,amount) values('%s','%s','%s')" % (self.day, self.category, self.amount))
    db.close()

    db1 = QSqlDatabase.addDatabase('QSQLITE')
    db1.setDatabaseName('expenses.db')
    db1.open()
    query1 = QSqlQuery()
    query1.exec_("SELECT date, category, amount FROM expenses.expense")

    while (query1.next()):
        extractedDate = query1.value(0).toString()
        extractedcategory = query1.value(1).toString()
        extractedAmount = query1.value(2).toString()
        self.line_edit1.setText(extractedDate)
        self.line_edit2.setText(extractedcategory)
        self.line_edit3.setText(extractedAmount)
    db1.close()

Insertion of values into DB works but not the retrieval of info from DB. What am i doing wrong ? seems like select query doesnt retrieve anything at all

Body:
Put query.first() before while (query1.next()): But, the first row won't be used.

Better:

query.first()
while query.isValid():
    # Your Code
    query.next()


问:
Display folders and files in a GUI using python
I have to create a program that lists selected folders in my computer, and then if the user clicks on the folder name, the list of files in the folder will pop out.

The folder names must be in button form. I have a non gui program for listing the folders and files that I want and I want these to be displayed in a GUI and this where I am stuck. Is there a module in python that lets you create a GUI to display folders and files in them?

答:
In python, you have the common GUI libraries like PyGtk (3 or 2) or PyQt (4 or 5).

http://www.pygtk.org/
https://wiki.python.org/moin/PyQt

Those integrate already what you need to provide a way to browse your files in your system (no need to recreate that, the Widgets and Dialogs already exist).


问:
AOSP Build Error - make fails
When I try to run mm, make or even make clobber I get the error below. I have followed the instructions from Google and have searched for the issue on the Internet. I haven't found anything that helps solve my problem. Can anybody advise as to what might be the problem here?

The source was downloaded 23/11/2016. I'm running Ubtuntu 14.04.5. I've install OpenJDK 8. I've downloaded the Nexus 6P (angler) binaries for Android (3429405) and run them from the root directory. I have make 3.81. When I run 'make clobber' as advised here, it produces the error below. I've narrowed the problem down to a go file (module.go) but I can't see how to fix it.

```<code>x@x-VirtualBox:~/WORKING_DIRECTORY$ make clobber
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=7.0
TARGET_PRODUCT=aosp_arm
TARGET_BUILD_VARIANT=eng
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a
TARGET_CPU_VARIANT=generic
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86_64
HOST_2ND_ARCH=x86
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.4.0-31-generic-x86_64-with-Ubuntu-14.04-trusty
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=NYC
OUT_DIR=out
AUX_OS_VARIANT_LIST=
============================================
ninja: no work to do.
[1/27] compile out/soong/.bootstrap/soong-android/pkg/android/soong/android.a
FAILED: out/soong/.bootstrap/soong-android/pkg/android/soong/android.a
GOROOT='./prebuilts/go/linux-x86' ./prebuilts/go/linux-x86/pkg/tool/linux_amd64/compile -o out/soong/.bootstrap/soong-android/pkg/android/soong/android.a -p android/soong/android -complete -I out/soong/.bootstrap/blueprint-parser/pkg -I out/soong/.bootstrap/blueprint-deptools/pkg -I out/soong/.bootstrap/blueprint-pathtools/pkg -I out/soong/.bootstrap/blueprint-proptools/pkg -I out/soong/.bootstrap/blueprint/pkg -I out/soong/.bootstrap/blueprint-bootstrap-bpdoc/pkg -I out/soong/.bootstrap/blueprint-bootstrap/pkg -I out/soong/.bootstrap/soong/pkg -I out/soong/.bootstrap/soong-env/pkg -pack build/soong/android/androidmk.go build/soong/android/arch.go build/soong/android/config.go build/soong/android/defaults.go build/soong/android/defs.go build/soong/android/expand.go build/soong/android/hooks.go build/soong/android/makevars.go build/soong/android/module.go build/soong/android/mutator.go build/soong/android/onceper.go build/soong/android/package_ctx.go build/soong/android/paths.go build/soong/android/prebuilt.go build/soong/android/register.go build/soong/android/util.go build/soong/android/variable.go build/soong/android/env.go
build/soong/android/module.go:526: unknown blueprint.BuildParams field 'Deps' in struct literal
[2/27] compile out/soong/.bootstrap/so...g-android/test/android/soong/android.a
FAILED: out/soong/.bootstrap/soong-android/test/android/soong/android.a
GOROOT='./prebuilts/go/linux-x86' ./prebuilts/go/linux-x86/pkg/tool/linux_amd64/compile -o out/soong/.bootstrap/soong-android/test/android/soong/android.a -p android/soong/android -complete -I out/soong/.bootstrap/blueprint-parser/pkg -I out/soong/.bootstrap/blueprint-deptools/pkg -I out/soong/.bootstrap/blueprint-pathtools/pkg -I out/soong/.bootstrap/blueprint-proptools/pkg -I out/soong/.bootstrap/blueprint/pkg -I out/soong/.bootstrap/blueprint-bootstrap-bpdoc/pkg -I out/soong/.bootstrap/blueprint-bootstrap/pkg -I out/soong/.bootstrap/soong/pkg -I out/soong/.bootstrap/soong-env/pkg -pack build/soong/android/androidmk.go build/soong/android/arch.go build/soong/android/config.go build/soong/android/defaults.go build/soong/android/defs.go build/soong/android/expand.go build/soong/android/hooks.go build/soong/android/makevars.go build/soong/android/module.go build/soong/android/mutator.go build/soong/android/onceper.go build/soong/android/package_ctx.go build/soong/android/paths.go build/soong/android/prebuilt.go build/soong/android/register.go build/soong/android/util.go build/soong/android/variable.go build/soong/android/env.go build/soong/android/expand_test.go build/soong/android/paths_test.go build/soong/android/prebuilt_test.go
build/soong/android/module.go:526: unknown blueprint.BuildParams field 'Deps' in struct literal
ninja: build stopped: subcommand failed.
make: *** [run_soong] Error 1

#### make failed to build some targets (1 seconds) ####
</code>```

答:
unknown blueprint.BuildParams field Deps in struct literal

The Deps and Depfile fields has been added into BuildParams struct (ninja_defs.go file) on 22th Nov 2016 as per aa873e1 commit (PR: #135), so I believe your Blueprint sources are out-of-date. Try updating it, verify the content of ninja_defs.go file and re-try again.

Title: AOSP Build Error - make fails

Body:
When I try to run mm, make or even make clobber I get the error below. I have followed the instructions from Google and have searched for the issue on the Internet. I haven't found anything that helps solve my problem. Can anybody advise as to what might be the problem here?

The source was downloaded 23/11/2016. I'm running Ubtuntu 14.04.5. I've install OpenJDK 8. I've downloaded the Nexus 6P (angler) binaries for Android (3429405) and run them from the root directory. I have make 3.81. When I run 'make clobber' as advised here, it produces the error below. I've narrowed the problem down to a go file (module.go) but I can't see how to fix it.

x@x-VirtualBox:~/WORKING_DIRECTORY$ make clobber
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=7.0
TARGET_PRODUCT=aosp_arm
TARGET_BUILD_VARIANT=eng
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a
TARGET_CPU_VARIANT=generic
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86_64
HOST_2ND_ARCH=x86
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.4.0-31-generic-x86_64-with-Ubuntu-14.04-trusty
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=NYC
OUT_DIR=out
AUX_OS_VARIANT_LIST=
============================================
ninja: no work to do.
[1/27] compile out/soong/.bootstrap/soong-android/pkg/android/soong/android.a
FAILED: out/soong/.bootstrap/soong-android/pkg/android/soong/android.a
GOROOT='./prebuilts/go/linux-x86' ./prebuilts/go/linux-x86/pkg/tool/linux_amd64/compile -o out/soong/.bootstrap/soong-android/pkg/android/soong/android.a -p android/soong/android -complete -I out/soong/.bootstrap/blueprint-parser/pkg -I out/soong/.bootstrap/blueprint-deptools/pkg -I out/soong/.bootstrap/blueprint-pathtools/pkg -I out/soong/.bootstrap/blueprint-proptools/pkg -I out/soong/.bootstrap/blueprint/pkg -I out/soong/.bootstrap/blueprint-bootstrap-bpdoc/pkg -I out/soong/.bootstrap/blueprint-bootstrap/pkg -I out/soong/.bootstrap/soong/pkg -I out/soong/.bootstrap/soong-env/pkg -pack build/soong/android/androidmk.go build/soong/android/arch.go build/soong/android/config.go build/soong/android/defaults.go build/soong/android/defs.go build/soong/android/expand.go build/soong/android/hooks.go build/soong/android/makevars.go build/soong/android/module.go build/soong/android/mutator.go build/soong/android/onceper.go build/soong/android/package_ctx.go build/soong/android/paths.go build/soong/android/prebuilt.go build/soong/android/register.go build/soong/android/util.go build/soong/android/variable.go build/soong/android/env.go
build/soong/android/module.go:526: unknown blueprint.BuildParams field 'Deps' in struct literal
[2/27] compile out/soong/.bootstrap/so...g-android/test/android/soong/android.a
FAILED: out/soong/.bootstrap/soong-android/test/android/soong/android.a
GOROOT='./prebuilts/go/linux-x86' ./prebuilts/go/linux-x86/pkg/tool/linux_amd64/compile -o out/soong/.bootstrap/soong-android/test/android/soong/android.a -p android/soong/android -complete -I out/soong/.bootstrap/blueprint-parser/pkg -I out/soong/.bootstrap/blueprint-deptools/pkg -I out/soong/.bootstrap/blueprint-pathtools/pkg -I out/soong/.bootstrap/blueprint-proptools/pkg -I out/soong/.bootstrap/blueprint/pkg -I out/soong/.bootstrap/blueprint-bootstrap-bpdoc/pkg -I out/soong/.bootstrap/blueprint-bootstrap/pkg -I out/soong/.bootstrap/soong/pkg -I out/soong/.bootstrap/soong-env/pkg -pack build/soong/android/androidmk.go build/soong/android/arch.go build/soong/android/config.go build/soong/android/defaults.go build/soong/android/defs.go build/soong/android/expand.go build/soong/android/hooks.go build/soong/android/makevars.go build/soong/android/module.go build/soong/android/mutator.go build/soong/android/onceper.go build/soong/android/package_ctx.go build/soong/android/paths.go build/soong/android/prebuilt.go build/soong/android/register.go build/soong/android/util.go build/soong/android/variable.go build/soong/android/env.go build/soong/android/expand_test.go build/soong/android/paths_test.go build/soong/android/prebuilt_test.go
build/soong/android/module.go:526: unknown blueprint.BuildParams field 'Deps' in struct literal
ninja: build stopped: subcommand failed.
make: *** [run_soong] Error 1

#### make failed to build some targets (1 seconds) ####


问:
passing a null datetime to reportparameter class?
How can I put a null value on datetime variable type?

I tried to make it nullable value, but I need to use it in ReportParameter() method to send it to my report but ReportParameter() constructor cannot take a nullable value and the ReportParameter() take just a string values!

答: you can create FailIfNull() extension method for this purpose. Please look here for more information about extension methods.</p>

ContentLicense: CC BY-SA 2.5


问:
Getting Gmail API access and ID token, but refresh token is NULL
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

```<code>    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}
</code>```

答:
Gmail API only gives the refresh token the first time you ask for the users permission. (At least this is what happens to me).

Go to: https://myaccount.google.com/permissions?pli=1, remove the authorization to your app and run your code. You should receive the refresh token.

Body:
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}


问:
Elastic Search : Does it maintain inverted and non inverted indexes both internally?
I was reading about elastic search. It looks like it maintain inverted index on all terms in all the documents. But does it also maintain normal indexing, i.e. from document id to document? Also, as it maintains lot of indexing on all fields and for all terms, so does it take too much memory?
Eg. when compared to DynamoDb, where say, I made indexes on only 2 fields and here it form indexes on each and every term, which would be more memory efficient?</p>

答:
Dynamo and ES are very different beasts.  A few examples:

in ES, you can specify how to index every field and search on every field.

in Dynamo, you can only have up to 5 indexes, everything else is a full scan

in ES, you control your cluster settings

Dynamo the "cluster" is managed for you, but you need to be really smart about how you partition your data.

in ES, you can query for exactly what you want, do aggregations on the server, get stats, really cool stuff.

in Dynamo you can't even do an "order by"


问:
Making dropdown list in kivy. 'NoneType' object has no attribute 'add_widget'
I already used available topics to improve my code but still something doesn't work. Running code gives me Attribute error:'NoneType' object has no attribute 'add_widget'.

```<code>class Datownik(DropDown):
    pass

class ZleceniaPojedyncze(Screen):
    dzienButton = ObjectProperty(None)
    miesiacButton = ObjectProperty(None)
    top_layout = ObjectProperty(Screen)   <------ changed
    rokButton = ObjectProperty(None)
    dd_btn = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(ZleceniaPojedyncze, self).__init__(*args, **kwargs)
        self.drop_down = Datownik()

        dropdown = DropDown()
        notes = ['alpha', 'beta', 'gamma', 'delta']
        for note in notes:

            btn = Button(text='bcda', size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

        mainbutton = Button(text='abcd')
        print("yay")

        mainbutton.bind(on_release=dropdown.open(self)) <--added self param.

        dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))

        self.top_layout.add_widget(mainbutton)
</code>```

And here is coresponding kv file:

```<code><Datownik>:
Button:
    text: 'B1'
    height: 44
    on_release: root.select('item1')
Button:
    text: 'B2'
    height: 44
    on_release: root.select('item1')
Button:
    text: 'B3'
    height: 44
    on_release: root.select('item1')

<ZleceniaPojedyncze>:
name: 'zp'
dzienButton: dzienButtonID
dd_btn: btn_ddID
top_layout: topLayoutID
GridLayout:
    id: topLayoutID
    height: self.minimum_height
    row_force_default: 'true'
    row_default_height: 30
    col_force_default: 'true'
    col_default_width: 70
    cols: 4
    padding: 70
    Button:
        id: dzienButtonID
        text: 'day'
    Button:
        id: btn_ddID
        text: 'month'
        on_release: root.drop_down.open(self)
    Button:
        text: 'year'
    Button:
        text: 'back'
        on_release: app.root.current = 'mm'
</code>```

I only want to make it work with one button for now, just dropdown menu, and later i will try to figure out what part do what to configure this menu for my needs, but i guess i mixed things up somehow and cant proceed. Any1 to help?

答: Your top_layout is declared as ObjectProperty(None) and then you're trying to add widgets to it when it is None: self.top_layout.add_widget(mainbutton).

Body:
I already used available topics to improve my code but still something doesn't work. Running code gives me Attribute error:'NoneType' object has no attribute 'add_widget'.

class Datownik(DropDown):
    pass

class ZleceniaPojedyncze(Screen):
    dzienButton = ObjectProperty(None)
    miesiacButton = ObjectProperty(None)
    top_layout = ObjectProperty(Screen)   <------ changed
    rokButton = ObjectProperty(None)
    dd_btn = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(ZleceniaPojedyncze, self).__init__(*args, **kwargs)
        self.drop_down = Datownik()

        dropdown = DropDown()
        notes = ['alpha', 'beta', 'gamma', 'delta']
        for note in notes:

            btn = Button(text='bcda', size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)

        mainbutton = Button(text='abcd')
        print("yay")

        mainbutton.bind(on_release=dropdown.open(self)) <--added self param.

        dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))

        self.top_layout.add_widget(mainbutton)

And here is coresponding kv file:

<Datownik>:
Button:
    text: 'B1'
    height: 44
    on_release: root.select('item1')
Button:
    text: 'B2'
    height: 44
    on_release: root.select('item1')
Button:
    text: 'B3'
    height: 44
    on_release: root.select('item1')

<ZleceniaPojedyncze>:
name: 'zp'
dzienButton: dzienButtonID
dd_btn: btn_ddID
top_layout: topLayoutID
GridLayout:
    id: topLayoutID
    height: self.minimum_height
    row_force_default: 'true'
    row_default_height: 30
    col_force_default: 'true'
    col_default_width: 70
    cols: 4
    padding: 70
    Button:
        id: dzienButtonID
        text: 'day'
    Button:
        id: btn_ddID
        text: 'month'
        on_release: root.drop_down.open(self)
    Button:
        text: 'year'
    Button:
        text: 'back'
        on_release: app.root.current = 'mm'

I only want to make it work with one button for now, just dropdown menu, and later i will try to figure out what part do what to configure this menu for my needs, but i guess i mixed things up somehow and cant proceed. Any1 to help?


问:
"Unable to create process ...\project1.exe" when debugging a Win64 apps in Windows 8
I am using Delphi XE4 Update 1.  When I build and run a simple VCL application compiled with Win64 platform on Windows 8.  I encountered an error:

```<code>"Unable to create process: ...\project1.exe"
</code>```

However, it works if I run the project1.exe without debugging.

I have tried to figure out what happens but failed to rectify the problem.

I have tried these:

Uninstall and reinstall XE4

I run C:\Program Files (x86)\Embarcadero\RAD Studio\11.0\bin\dbkw64_18_0.exe and it flash a while and close without any errors.  Other Window 8 machine will run the program and stay in the desktop.

I reset Window 8 Firewall rules.  When I run the app in debugger, it didn't prompt me the usual firewall rules dialog.

I add a Firewall rules for dbkw64_18_0.exe and but it doesn't work

When I attempt to debug the app with Win64 platform, a new process rmtdbg180.exe is created.  Each attempt to start the app in debugger will create a new rmtdbg180.exe process.  This doesn't happen on other Windows 8 machine.

Anyone has ideas what happen to my machine?

答: Just encountered this issue with Berlin and was able to resolve it by going to the Bin64 folder and resetting the security settings through the advanced settings.</p>

Body:
I am using Delphi XE4 Update 1.  When I build and run a simple VCL application compiled with Win64 platform on Windows 8.  I encountered an error:

"Unable to create process: ...\project1.exe"

However, it works if I run the project1.exe without debugging.

I have tried to figure out what happens but failed to rectify the problem.

I have tried these:

Uninstall and reinstall XE4

I run C:\Program Files (x86)\Embarcadero\RAD Studio\11.0\bin\dbkw64_18_0.exe and it flash a while and close without any errors.  Other Window 8 machine will run the program and stay in the desktop.

I reset Window 8 Firewall rules.  When I run the app in debugger, it didn't prompt me the usual firewall rules dialog.

I add a Firewall rules for dbkw64_18_0.exe and but it doesn't work

When I attempt to debug the app with Win64 platform, a new process rmtdbg180.exe is created.  Each attempt to start the app in debugger will create a new rmtdbg180.exe process.  This doesn't happen on other Windows 8 machine.

Anyone has ideas what happen to my machine?


问:
Memory leak issue in Apache drill CTAS command
I am getting error while executing CTAS command in apache drill.The query works fine when i am running only select command but as soon as I use CTAS command it throws Memory leak issue.

Query :

```<code>create table dfs.test.`temp_count` (user_count) as select t1.data.userParams.imsId as userParams from s3device.`<file>` t1 limit 1
</code>```

Exception :

org.apache.drill.common.exceptions.UserRemoteException: VALIDATION ERROR: A table or view with given name [temp_count9] already exists in schema [dfs.test] [Error Id: 4c54de50-3875-4534-a3bb-c37a96d21ecb on drill-prd]

答:
Its not a memory leak, its saying the table already exist. You can drop and create table again or use a different table name in CTAS.

```<code>drop table dfs.test.`temp_count`;
</code>```

Drill supports only create table and not insert/update. Each CTAS will create directory in the file system. You can either delete the directory directly or use drop table command to delete it.

Body:
I am getting error while executing CTAS command in apache drill.The query works fine when i am running only select command but as soon as I use CTAS command it throws Memory leak issue.

Query :

create table dfs.test.`temp_count` (user_count) as select t1.data.userParams.imsId as userParams from s3device.`<file>` t1 limit 1

Exception :

org.apache.drill.common.exceptions.UserRemoteException: VALIDATION ERROR: A table or view with given name [temp_count9] already exists in schema [dfs.test] [Error Id: 4c54de50-3875-4534-a3bb-c37a96d21ecb on drill-prd]

Body:
Its not a memory leak, its saying the table already exist. You can drop and create table again or use a different table name in CTAS.

drop table dfs.test.`temp_count`;

Drill supports only create table and not insert/update. Each CTAS will create directory in the file system. You can either delete the directory directly or use drop table command to delete it.


问:
GET http://localhost/Roles/Create 500 (Internal Server Error)
I am really not getting why I keep getting an Http Error 500 whenever my RolesController renders logic to its respective View. This is for an MVC5 Application.

Please find the below:

RolesController.cs

```<code>        [Route("/Roles")]
        public ActionResult Index()
        {
            if (TempData["StatusMessage"] != null)
            {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            else
            {
                ViewBag.StatusMessage = "";
            }

            var roles = db.Roles.ToList();
            return View("Index", roles);
        }

        // GET: /Roles/Create
        public ActionResult Create()
        {
          return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Roles");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }
</code>```

View:

```<code>@model User_Manager_Interface.Models.ApplicationRole
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="contenttitle">
    <h2 class="form"><span>Create A New Role</span></h2>
</div>

@using (Html.BeginForm("Create", "Roles", FormMethod.Post, new { @class = "stdform", role = "form" }))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary()

    <p>
        <label>@Html.LabelFor(model => model.Name)</label>
        <span class="field">
            <input type="text" name="name" id="name" class="smallinput" />
        </span>
        @Html.ValidationMessageFor(model => model.Name)
        <small class="desc">Name of the role.</small>
    </p>

    <p>
        <label>@Html.LabelFor(model => model.Description)</label>
        <span class="field">
            <input type="text" name="description" id="description" class="longinput" />
        </span>
        @Html.ValidationMessageFor(model => model.Description)
        <small class="desc">A short description for the role.</small>
    </p>

    <br clear="all" /><br />

    <p class="stdformbutton">
        <button class="submit radius2">Create</button>
        <input type="reset" class="reset radius2" value="Reset Form" />
    </p>
}

@section Scripts {
    @Scripts.Render("~/bundles/forms")
}
</code>```

Model:

```<code> public class ApplicationRole : IdentityRole
    {
        [Display(Name = "Description")]
        [StringLength(100, MinimumLength = 5)]
        public string Description { get; set; }
    }
</code>```

Is it a matter of the compiler not knowing what View to render at runtime? What could I be doing wrong?

UPDATE:

Here is my response header:

```<code>HTTP/1.1 500 Internal Server Error
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTGluZGFcVXNlck1hbmFnZXJcRlNLVXNlck1hbmFnZXJcRlNLX1VzZXJNYW5hZ2VyX1dlYlxSb2xlc1xDcmVhdGU=?=
X-Powered-By: ASP.NET
Date: Mon, 05 Jun 2017 14:12:10 GMT
</code>```

答:
Okay. After almost giving up, I stumbled across this SO post:

asp.net mvc 3 handleerror global filter always shows IIS status 500 page

And looked at @DarinDimitrov 's solution.

So I did the following:

I enabled <customErrors mode="On" /> in my web.config

I added this function to my ErrorController.cs:

public ActionResult Index()
{
    throw new Exception("error");
}

Made sure the contents of my Error.cshtml file has more than 1KB in size in order to render the view.

And that fixed the problem. And as a result, this also solved this pending SO post of mine which could be found here: Object Moved Here - RedirectToAction

Body:
I am really not getting why I keep getting an Http Error 500 whenever my RolesController renders logic to its respective View. This is for an MVC5 Application.

Please find the below:

RolesController.cs

        [Route("/Roles")]
        public ActionResult Index()
        {
            if (TempData["StatusMessage"] != null)
            {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            else
            {
                ViewBag.StatusMessage = "";
            }

            var roles = db.Roles.ToList();
            return View("Index", roles);
        }

        // GET: /Roles/Create
        public ActionResult Create()
        {
          return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Roles");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

View:

@model User_Manager_Interface.Models.ApplicationRole
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Create A New Role

@using (Html.BeginForm("Create", "Roles", FormMethod.Post, new { @class = "stdform", role = "form" }))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary()

        @Html.LabelFor(model => model.Name)

            <input type="text" name="name" id="name" class="smallinput" />

        @Html.ValidationMessageFor(model => model.Name)
        Name of the role.

        @Html.LabelFor(model => model.Description)

            <input type="text" name="description" id="description" class="longinput" />

        @Html.ValidationMessageFor(model => model.Description)
        A short description for the role.

        <button class="submit radius2">Create</button>
        <input type="reset" class="reset radius2" value="Reset Form" />

}

@section Scripts {
    @Scripts.Render("~/bundles/forms")
}

Model:

 public class ApplicationRole : IdentityRole
    {
        [Display(Name = "Description")]
        [StringLength(100, MinimumLength = 5)]
        public string Description { get; set; }
    }

Is it a matter of the compiler not knowing what View to render at runtime? What could I be doing wrong?

UPDATE:

Here is my response header:

HTTP/1.1 500 Internal Server Error
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTGluZGFcVXNlck1hbmFnZXJcRlNLVXNlck1hbmFnZXJcRlNLX1VzZXJNYW5hZ2VyX1dlYlxSb2xlc1xDcmVhdGU=?=
X-Powered-By: ASP.NET
Date: Mon, 05 Jun 2017 14:12:10 GMT


问:
awk command: adding prefix to an csv file
I am trying to add an prefix to my csv file. Below is the source csv

```<code>  A,B
121ABC,London
2212ABC,Paris
312ABC,Tokyo
</code>```

I am using the following  awk command

```<code>$ awk -F=',' -vOFS=',' '{$2="AC_"$2; print}' t.csv >t1.csv
</code>```

But, the output is somewhat adding another column to the csv file.

```<code>A,B,AC_
121ABC,London,AC_
2212ABC,Paris,AC_
312ABC,Tokyo,AC_
</code>```

Any pointers as to where the error is?

答:
You can use this awk:

```<code>awk 'BEGIN{FS=OFS=","} {$2 = "AC_" $2} 1' file

A,AC_B
121ABC,AC_London
2212ABC,AC_Paris
312ABC,AC_Tokyo
</code>```

Body:
I am trying to add an prefix to my csv file. Below is the source csv

  A,B
121ABC,London
2212ABC,Paris
312ABC,Tokyo

I am using the following  awk command

$ awk -F=',' -vOFS=',' '{$2="AC_"$2; print}' t.csv >t1.csv

But, the output is somewhat adding another column to the csv file.

A,B,AC_
121ABC,London,AC_
2212ABC,Paris,AC_
312ABC,Tokyo,AC_

Any pointers as to where the error is?

Body:
You can use this awk:

awk 'BEGIN{FS=OFS=","} {$2 = "AC_" $2} 1' file

A,AC_B
121ABC,AC_London
2212ABC,AC_Paris
312ABC,AC_Tokyo


问:
What do you recommend using for graphically visualizing a WSDL?
I'm looking for a good solution for graphically viewing a SOAP-based web service and possibly interacting with it (for testing purposes). Online (browser-based) solutions would be interesting too.</p>

答:
I have used SOAP UI with success in the past:

http://www.soapui.org/information/WSDL_Test.html?gclid=CMOpgKnAjpgCFRBbagodxyzOqg

It allows you test methods and to see if your WSDL passes current standards.

OwnerDisplayName: Abdullah Jibaly

OwnerDisplayName: Loukas


问:
Learning MIPS: Creating a simple program to read numbers and print them
I'm struggling with learning MIPS right now, and I'm finding it isn't as easy as C++ was.

Right now, I'm to edit/write a program that will take ten number's from a user, then print those numbers out at the end with commas between them, and no comma after the last number. Example:

```<code>Enter a number 1
Enter a number 2
Enter a number 9
Enter a number 11
Enter a number 99
Enter a number 12
Enter a number 24
Enter a number 90
Enter a number 17
Enter a number 82
1, 2, 9, 11, 99, 12, 24, 90, 7, 82
</code>```

This is the given code:

```<code>    .data
    .space 40                 # set aside 40 bytes for 10 integers
prompt:
    .asciiz "Enter a number " # address 0x10010028
comma:
    .asciiz ", "              # address 0x10010038

.globl main
.text
main:
    lui $a0, 0x1001 # get start of data segment
    jal getdata     # call getdata function

    lui $a0, 0x1001 # get start of data segment
    jal print       # call print function

    ori $v0, $0, 10 # set command to exit
    syscall         # end program

getdata:
    addi $sp, $sp, -4    # allocate space on stack
    sw $ra, 0($sp)       # save $ra
    ori $t1, $a0, 0      # address of array

    lui $t1, 0x1001      # start of data
    ori $a0, $a0, 0x0028 # address of prompt
    ori $t0, $0, 10      # counter

top:
    beq $t0, $0, ret     # while not 0

    jal printstr         # call function to print prompt
    ori $v0, $0, 5       # set command to read integer
    syscall              # read int
    sw $v0, 0($t1)       # save int in memory
    addi $t1, $t1, 4     # increment to next location

    addi $t0, $t0, -1    # decrement counter
    j top                # repeat

ret:
    lw $ra, 0($sp)       # restore return address
    addi $sp, $sp, 4     # clean up stack
    jr $ra               # return from call

    # print
    # parameter: $a0 holds address of list in memory
    # purpose: print the list separated by commas
print:
    #to be completed
    jr $ra

    # printstr
    # paramters: $a0 holds address of string to print
    # purpose: print the string parameter
printstr:
    #to be completed
    jr $ra
</code>```

Where I believe I'm struggling at is the "print" portion. I have the
following for printstr: and for getdata:

```<code>printstr:
    ori $v0, $0, 4  # command to print string at $a0
    syscall
    jr $ra          # return from call

getdata:
    addi $sp, $sp, -4    # allocate space on stack
    sw $ra, 0($sp)       # save $ra
    ori $t1, $a0, 0      # address of array

    lui $t1, 0x1001      # start of data
    ori $a0, $a0, 0x0028 # address of prompt
    ori $t0, $0, 10      # counter
</code>```

And then this is the code I've been trying to use for the loop...

```<code>print:
    addi $t2, $t2, 10
    addi $t0, $t0, 1      # Enter into the loop by increment 1
    ori $v0, $0, 4        # Print the 1st value and then loop
                          # start from the 2nd value

    syscall

    jal loop # Jump to loop

loop:
    beq $t0, $t2, end  # checks if t2=t0, if it does then ends the program
    lui $t3, 0x1001    # loads the upper limit of t3 to 1001
    or $a0, $0, $t3    # sets the upper limit of a0 to 1001
    ori $v0, $0, 1     # sets v0 to print integer
    syscall            # prints integer
    addi $t3, $t3, 4   # moves t3 to the next address

    ori $a0, $a0, 0x0038  # sets a0 to the address of comma
    ori $v0, $0, 4        # Print string at $a0
    syscall
    addi $t0, $t0, 1      # increases the value at t0 by 1
    jr $ra
</code>```

However, when I run the program it spits out "268500992, ,". So I'm not getting my input numbers or the correct number of commas even. I know that means that my loop isn't running all the way through. I'm not supposed to use and pseudo code, and only what I've learned so far - so array's are out of the question.

Can someone help me figure out what I'm missing? Does it have something to do with the stack values (which I don't completely understand)?

答:
OK, I think your code for printstr is correct, and getdata also looks fine (a little odd, but you didn't write that, yes?) The bugs are all in print.  I'm not going to spell it out for you, because this is homework, but the structure of the loop in print should be very similar to the structure of the loop in getdata:

```<code>    # on entry, $a0 = address of integer array
print:
    ori $t0, $0, 10      # counter
    ori $t1, $a0, 0      # t1 points to current array element

print_loop:
    ### if this isn't the first iteration, print ", "
    ### load value at $t1 into $a0
    ### print the integer in $a0

    addi $t1, $t1, 4     # advance to next array element
    addi $t0, $t0, -1    # decrement counter
    bne  $t0, $0, print_loop

    ### print a carriage return

    jr $ra               # return from call
</code>```

Each thing prefixed by ### is a placeholder for code you need to write.

Body:
I'm struggling with learning MIPS right now, and I'm finding it isn't as easy as C++ was.

Right now, I'm to edit/write a program that will take ten number's from a user, then print those numbers out at the end with commas between them, and no comma after the last number. Example:

Enter a number 1
Enter a number 2
Enter a number 9
Enter a number 11
Enter a number 99
Enter a number 12
Enter a number 24
Enter a number 90
Enter a number 17
Enter a number 82
1, 2, 9, 11, 99, 12, 24, 90, 7, 82

This is the given code:

    .data
    .space 40                 # set aside 40 bytes for 10 integers
prompt:
    .asciiz "Enter a number " # address 0x10010028
comma:
    .asciiz ", "              # address 0x10010038

.globl main
.text
main:
    lui $a0, 0x1001 # get start of data segment
    jal getdata     # call getdata function

    lui $a0, 0x1001 # get start of data segment
    jal print       # call print function

    ori $v0, $0, 10 # set command to exit
    syscall         # end program

getdata:
    addi $sp, $sp, -4    # allocate space on stack
    sw $ra, 0($sp)       # save $ra
    ori $t1, $a0, 0      # address of array

    lui $t1, 0x1001      # start of data
    ori $a0, $a0, 0x0028 # address of prompt
    ori $t0, $0, 10      # counter

top:
    beq $t0, $0, ret     # while not 0

    jal printstr         # call function to print prompt
    ori $v0, $0, 5       # set command to read integer
    syscall              # read int
    sw $v0, 0($t1)       # save int in memory
    addi $t1, $t1, 4     # increment to next location

    addi $t0, $t0, -1    # decrement counter
    j top                # repeat

ret:
    lw $ra, 0($sp)       # restore return address
    addi $sp, $sp, 4     # clean up stack
    jr $ra               # return from call

    # print
    # parameter: $a0 holds address of list in memory
    # purpose: print the list separated by commas
print:
    #to be completed
    jr $ra

    # printstr
    # paramters: $a0 holds address of string to print
    # purpose: print the string parameter
printstr:
    #to be completed
    jr $ra

Where I believe I'm struggling at is the "print" portion. I have the
following for printstr: and for getdata:

printstr:
    ori $v0, $0, 4  # command to print string at $a0
    syscall
    jr $ra          # return from call

getdata:
    addi $sp, $sp, -4    # allocate space on stack
    sw $ra, 0($sp)       # save $ra
    ori $t1, $a0, 0      # address of array

    lui $t1, 0x1001      # start of data
    ori $a0, $a0, 0x0028 # address of prompt
    ori $t0, $0, 10      # counter

And then this is the code I've been trying to use for the loop...

print:
    addi $t2, $t2, 10
    addi $t0, $t0, 1      # Enter into the loop by increment 1
    ori $v0, $0, 4        # Print the 1st value and then loop
                          # start from the 2nd value

    syscall

    jal loop # Jump to loop

loop:
    beq $t0, $t2, end  # checks if t2=t0, if it does then ends the program
    lui $t3, 0x1001    # loads the upper limit of t3 to 1001
    or $a0, $0, $t3    # sets the upper limit of a0 to 1001
    ori $v0, $0, 1     # sets v0 to print integer
    syscall            # prints integer
    addi $t3, $t3, 4   # moves t3 to the next address

    ori $a0, $a0, 0x0038  # sets a0 to the address of comma
    ori $v0, $0, 4        # Print string at $a0
    syscall
    addi $t0, $t0, 1      # increases the value at t0 by 1
    jr $ra

However, when I run the program it spits out "268500992, ,". So I'm not getting my input numbers or the correct number of commas even. I know that means that my loop isn't running all the way through. I'm not supposed to use and pseudo code, and only what I've learned so far - so array's are out of the question.

Can someone help me figure out what I'm missing? Does it have something to do with the stack values (which I don't completely understand)?

Body:
OK, I think your code for printstr is correct, and getdata also looks fine (a little odd, but you didn't write that, yes?) The bugs are all in print.  I'm not going to spell it out for you, because this is homework, but the structure of the loop in print should be very similar to the structure of the loop in getdata:

    # on entry, $a0 = address of integer array
print:
    ori $t0, $0, 10      # counter
    ori $t1, $a0, 0      # t1 points to current array element

print_loop:
    ### if this isn't the first iteration, print ", "
    ### load value at $t1 into $a0
    ### print the integer in $a0

    addi $t1, $t1, 4     # advance to next array element
    addi $t0, $t0, -1    # decrement counter
    bne  $t0, $0, print_loop

    ### print a carriage return

    jr $ra               # return from call

Each thing prefixed by ### is a placeholder for code you need to write.


问:
Scale a PNG in Unity5? - Bountie
Surprisingly in Unity, for years the only way to simply scale an actual PNG is to use the very awesome library http://wiki.unity3d.com/index.php/TextureScale

Example below

How do you scale a PNG using Unity5 functions? There must be a way now with new UI and so on.

So, scaling actual pixels (such as in Color[]) or literally a PNG file, perhaps downloaded from the net.

(BTW if you're new to Unity, the Resize call is unrelated. It merely changes the size of an array.)

```<code>public WebCamTexture wct;

public void UseFamousLibraryToScale()
    {
    // take the photo. scale down to 256
    // also  crop to a central-square

    WebCamTexture wct;
    int oldW = wct.width; // NOTE example code assumes wider than high
    int oldH = wct.height;

    Texture2D photo = new Texture2D(oldW, oldH,
          TextureFormat.ARGB32, false);
    //consider WaitForEndOfFrame() before GetPixels
    photo.SetPixels( 0,0,oldW,oldH, wct.GetPixels() );
    photo.Apply();

    int newH = 256;
    int newW = Mathf.FloorToInt(
           ((float)newH/(float)oldH) * oldW );

    // use a famous Unity library to scale
    TextureScale.Bilinear(photo, newW,newH);

    // crop to central square 256.256
    int startAcross = (newW - 256)/2;
    Color[] pix = photo.GetPixels(startAcross,0, 256,256);
    photo = new Texture2D(256,256, TextureFormat.ARGB32, false);
    photo.SetPixels(pix);
    photo.Apply();
    demoImage.texture = photo;

    // consider WriteAllBytes(
    //   Application.persistentDataPath+"p.png",
    //   photo.EncodeToPNG()); etc
    }
</code>```

Just BTW it occurs to me I'm probably only talking about scaling down here (as you often have to do to post an image, create something on the fly or whatever.)  I guess, there would not often be a need to scale up in size an image; it's pointless quality-wise.

答:
If you're okay with stretch-scaling, actually there's simpler way by using a temporary RenderTexture and Graphics.Blit. If you need it to be Texture2D, swapping RenderTexture.active temporarily and read its pixels to Texture2D should do the trick. For example:</p>

```<code>public Texture2D ScaleTexture(Texture src, int width, int height){
    RenderTexture rt = RenderTexture.GetTemporary(width, height);
    Graphics.Blit(src, rt);

    RenderTexture currentActiveRT = RenderTexture.active;
    RenderTexture.active = rt;
    Texture2D tex = new Texture2D(rt.width,rt.height);

    tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
    tex.Apply();

    RenderTexture.ReleaseTemporary(rt);
    RenderTexture.active = currentActiveRT;

    return tex;
}
</code>```

Title: Scale a PNG in Unity5? - Bountie

Body:
Surprisingly in Unity, for years the only way to simply scale an actual PNG is to use the very awesome library http://wiki.unity3d.com/index.php/TextureScale

Example below

How do you scale a PNG using Unity5 functions? There must be a way now with new UI and so on.

So, scaling actual pixels (such as in Color[]) or literally a PNG file, perhaps downloaded from the net.

(BTW if you're new to Unity, the Resize call is unrelated. It merely changes the size of an array.)

public WebCamTexture wct;

public void UseFamousLibraryToScale()
    {
    // take the photo. scale down to 256
    // also  crop to a central-square

    WebCamTexture wct;
    int oldW = wct.width; // NOTE example code assumes wider than high
    int oldH = wct.height;

    Texture2D photo = new Texture2D(oldW, oldH,
          TextureFormat.ARGB32, false);
    //consider WaitForEndOfFrame() before GetPixels
    photo.SetPixels( 0,0,oldW,oldH, wct.GetPixels() );
    photo.Apply();

    int newH = 256;
    int newW = Mathf.FloorToInt(
           ((float)newH/(float)oldH) * oldW );

    // use a famous Unity library to scale
    TextureScale.Bilinear(photo, newW,newH);

    // crop to central square 256.256
    int startAcross = (newW - 256)/2;
    Color[] pix = photo.GetPixels(startAcross,0, 256,256);
    photo = new Texture2D(256,256, TextureFormat.ARGB32, false);
    photo.SetPixels(pix);
    photo.Apply();
    demoImage.texture = photo;

    // consider WriteAllBytes(
    //   Application.persistentDataPath+"p.png",
    //   photo.EncodeToPNG()); etc
    }

Just BTW it occurs to me I'm probably only talking about scaling down here (as you often have to do to post an image, create something on the fly or whatever.)  I guess, there would not often be a need to scale up in size an image; it's pointless quality-wise.

Body:
If you're okay with stretch-scaling, actually there's simpler way by using a temporary RenderTexture and Graphics.Blit. If you need it to be Texture2D, swapping RenderTexture.active temporarily and read its pixels to Texture2D should do the trick. For example:

public Texture2D ScaleTexture(Texture src, int width, int height){
    RenderTexture rt = RenderTexture.GetTemporary(width, height);
    Graphics.Blit(src, rt);

    RenderTexture currentActiveRT = RenderTexture.active;
    RenderTexture.active = rt;
    Texture2D tex = new Texture2D(rt.width,rt.height);

    tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
    tex.Apply();

    RenderTexture.ReleaseTemporary(rt);
    RenderTexture.active = currentActiveRT;

    return tex;
}


答:
You're setting FS to =, instead of ,. Use -F',' or -v FS=',' but not -F=','.

Since you require , for both input and output field separators you should be setting them together to that value in one place rather than setting them both separately to the same value:

```<code>awk 'BEGIN{FS=OFS=","} {$2="AC_"$2; print}' t.csv >t1.csv
</code>```

Title: awk command: adding prefix to an csv file

Body:
You're setting FS to =, instead of ,. Use -F',' or -v FS=',' but not -F=','.

Since you require , for both input and output field separators you should be setting them together to that value in one place rather than setting them both separately to the same value:

awk 'BEGIN{FS=OFS=","} {$2="AC_"$2; print}' t.csv >t1.csv


问:
Alter Stored Procedure
I currently have a stored procedure that I want to take on a flexible number of arguments. Does anyone know if that is possible?

```<code>ALTER PROCEDURE myStoredProc
    (@variable1 INT,
     @variable2 INT,
     @variable3 INT)
</code>```

The example above, I have 3 parameters. But is it possible to have N number? And in the body have loops that go over the N number of variables for some sort of execution?

Thank you.

答:
In SqlServer you can use Xml Parameter and pass all parameters as a Xml.
Your procedure looks like this :

```<code>Create procedure myStoredProc (@xml xml)
as
SELECT
c.value('(.)', 'VARCHAR(8000)') AS paramvalue
FROM   @xml.nodes('/Root/param') T(c)
GO
</code>```

This procedure parse simply the input Xml and selects all parameters.

And you can call your stored procedure with a Xml Parameter as following

```<code>DECLARE @xml xml
SET @xml='<Root>
    <param>1</param>
    <param>2</param>
    <param>3</param>
</Root>'

exec myStoredProc @xml
</code>```

Title: Alter Stored Procedure

Body:
I currently have a stored procedure that I want to take on a flexible number of arguments. Does anyone know if that is possible?

ALTER PROCEDURE myStoredProc
    (@variable1 INT,
     @variable2 INT,
     @variable3 INT)

The example above, I have 3 parameters. But is it possible to have N number? And in the body have loops that go over the N number of variables for some sort of execution?

Thank you.

Body:
In SqlServer you can use Xml Parameter and pass all parameters as a Xml.
Your procedure looks like this :

Create procedure myStoredProc (@xml xml)
as
SELECT
c.value('(.)', 'VARCHAR(8000)') AS paramvalue
FROM   @xml.nodes('/Root/param') T(c)
GO

This procedure parse simply the input Xml and selects all parameters.

And you can call your stored procedure with a Xml Parameter as following

DECLARE @xml xml
SET @xml='<Root>
    <param>1</param>
    <param>2</param>
    <param>3</param>
</Root>'

exec myStoredProc @xml


问:
how to print row in CVS file in one line?
I have a CSV file that contains two columns and I want to print the contents of the second column.

For example: (from this)

```<code>for row in file1:
    print(row[1])
</code>```

to this:

```<code>print([row[1] for row in file1])
</code>```

The problem is that it doesn't print anything. Can anyone tell me where I'm wrong?

答:
Try:

```<code>[print(row[1]) for row in file1]
</code>```

Edit:

To avoid printing first line (which is mostly header) do

```<code>next(file1)
[print(row[1]) for row in file1]
</code>```

Body:
I have a CSV file that contains two columns and I want to print the contents of the second column.

For example: (from this)

for row in file1:
    print(row[1])

to this:

print([row[1] for row in file1])

The problem is that it doesn't print anything. Can anyone tell me where I'm wrong?

Body:
Try:

[print(row[1]) for row in file1]

Edit:

To avoid printing first line (which is mostly header) do

next(file1)
[print(row[1]) for row in file1]


问:
how to catch android force to close
Now i am working json application.The Force close message occured the app is crosed.  so

how to catch force to close error in try catch exception.Help me.....

答:
While defining your message give : throws JSONException
and put the code that raises exception inside try block.
After try block, give Catch statement as :</p>

```<code>catch(Exception e) {
    throw new JSONException(e.getMessage());
}
</code>```

Title: how to catch android force to close

Body:
While defining your message give : throws JSONException
and put the code that raises exception inside try block.
After try block, give Catch statement as :

catch(Exception e) {
    throw new JSONException(e.getMessage());
}


问:
How to change a radio button value from a textbox value
i would love to have the textbox value as my radio button value. For example, if I type "1" in the textbox, then the radio button value would change to "1".I hope i could find answers here. By the way, i am using Joomla, and if there are javascripts, pls tell me where to paste it. thanks so much!!! </p>

答:
Never mind, i solved it :D
here it is.

$('#textbox').keyup(function(event){
     var value = $(this).val();
     $('#radio').val(value);
  });

you also need to change the value of your #radio to the id of your textbox e.g


问:
Why does my application stop working?
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

            }
        }
    );
}
</code>```

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )

答:
Declare this: LinearLayout layout = (LinearLayout) findViewById(R.id.layout); Out side of your onClick listener.

Also Try this for your random number generator between 1 and 4

```<code>Random r = new Random();
int i1 = r.nextInt((4 - 1) + 1) + 1;
</code>```

Title: Why does my application stop working?

Body:
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

            }
        }
    );
}

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )

Body:
Declare this: LinearLayout layout = (LinearLayout) findViewById(R.id.layout); Out side of your onClick listener.

Also Try this for your random number generator between 1 and 4

Random r = new Random();
int i1 = r.nextInt((4 - 1) + 1) + 1;


问:
Golang Unmarshal same level XML elements into array
I have XML that I would like to unmarshal the address info into its on array as part of my struct:

```<code><customer>
    ...
    <dob>1990-10-01</dob>
    <address1>555 Hollywood Blvd</address1>
    <city>Hollywood</city>
    <state>CA</state>
    <zipCode>99999</zipCode>
    <alternateAddress1>575 Hollywood St</alternateAddress1>
    <alternateCity>Los Angeles</alternateCity>
    <alternateState>CA</alternateState>
    <alternateZipCode>12345</alternateZipCode>
    ....
</customer>
</code>```

My attempt at a struct:

```<code>    type Test struct {
      CustProfile struct {
        DOB string `xml:"birthDate" json:"dob"`
        Address []struct {
            PrimaryAddress struct {
                Street string `xml:"address1" json:"line1"`
                City string `xml:"city" json:"city"`
                State string `xml:"state" json:"state"`
                ZipCode string `xml:"zipCode" json:"zip"`
                IsPrimaryAddress string `json:"isPrimaryAddress"`
            }
            AlternateAddress struct {
                Street string `xml:"alternateAddress1" json:"line1"`
                City string `xml:"alternateCity" json:"city"`
                State string `xml:"alternateState" json:"state"`
                ZipCode string `xml:"alternateZipCode" json:"zip"`
                IsPrimaryAddress string `json:"isPrimaryAddress"`
            }
        } `json:"address"`
    } `xml:"customer" json:"custProfile"`
  }
</code>```

So I'm having a couple of issues here. The first issue is that all the elements are in the same level and from what I figured out so far, since the CustProfile struct is already associated with the customer parent element, I'm not able to reference any child elements inside the Address struct because the path would be customer->?>city,state,etc which will always return null since that path doesn't exist.

The second issue is the way I'm trying to define a default string for IsPrimaryAddress. I tried doing something like this but I'm getting an undefined error.

```<code>var marshalTest Test
...
marshalTest.CustProfile.Address.PrimaryAddress.IsPrimaryAddress = "Y";
marshalTest.CustProfile.Address.AlternateAddress.IsPrimaryAddress = "N";
</code>```

Is it possible to unmarshal this XML into a struct that results in the struct below?

```<code>{
  "custProfile": {
    "dob": "1990-10-01",
    "address": [
      {
        "line1": "555 Hollywood Blvd",
        "city": "HOLLYWOOD",
        "state": "CA",
        "zip": "99999",
        "isPrimaryAddress": "Y"
      },
      {
        "line1": "575 Hollywood St",
        "city": "LOS ANGELES",
        "state": "CA",
        "zip": "12345",
        "isPrimaryAddress": "N"
      }
    ]
}
</code>```

I'm not at all that familiar with XML encoding in Go and the best I've been able to manage is this:

```<code> {
      "custProfile": {
        "dob": "1990-10-01",
        "address": null
      }
 }
</code>```

Any help would be greatly appreciated. Thanks

答: I was able to use a combination of xml parsing with Xquery and json parsing with Gabs to manually construct the struct I wanted. Probably not the cleanest solution but it allowed me to customize the struct to the degree I wanted.</p>

Body:
I have XML that I would like to unmarshal the address info into its on array as part of my struct:

<customer>
    ...
    <dob>1990-10-01</dob>
    <address1>555 Hollywood Blvd</address1>
    <city>Hollywood</city>
    <state>CA</state>
    <zipCode>99999</zipCode>
    <alternateAddress1>575 Hollywood St</alternateAddress1>
    <alternateCity>Los Angeles</alternateCity>
    <alternateState>CA</alternateState>
    <alternateZipCode>12345</alternateZipCode>
    ....
</customer>

My attempt at a struct:

    type Test struct {
      CustProfile struct {
        DOB string `xml:"birthDate" json:"dob"`
        Address []struct {
            PrimaryAddress struct {
                Street string `xml:"address1" json:"line1"`
                City string `xml:"city" json:"city"`
                State string `xml:"state" json:"state"`
                ZipCode string `xml:"zipCode" json:"zip"`
                IsPrimaryAddress string `json:"isPrimaryAddress"`
            }
            AlternateAddress struct {
                Street string `xml:"alternateAddress1" json:"line1"`
                City string `xml:"alternateCity" json:"city"`
                State string `xml:"alternateState" json:"state"`
                ZipCode string `xml:"alternateZipCode" json:"zip"`
                IsPrimaryAddress string `json:"isPrimaryAddress"`
            }
        } `json:"address"`
    } `xml:"customer" json:"custProfile"`
  }

So I'm having a couple of issues here. The first issue is that all the elements are in the same level and from what I figured out so far, since the CustProfile struct is already associated with the customer parent element, I'm not able to reference any child elements inside the Address struct because the path would be customer->?>city,state,etc which will always return null since that path doesn't exist.

The second issue is the way I'm trying to define a default string for IsPrimaryAddress. I tried doing something like this but I'm getting an undefined error.

var marshalTest Test
...
marshalTest.CustProfile.Address.PrimaryAddress.IsPrimaryAddress = "Y";
marshalTest.CustProfile.Address.AlternateAddress.IsPrimaryAddress = "N";

Is it possible to unmarshal this XML into a struct that results in the struct below?

{
  "custProfile": {
    "dob": "1990-10-01",
    "address": [
      {
        "line1": "555 Hollywood Blvd",
        "city": "HOLLYWOOD",
        "state": "CA",
        "zip": "99999",
        "isPrimaryAddress": "Y"
      },
      {
        "line1": "575 Hollywood St",
        "city": "LOS ANGELES",
        "state": "CA",
        "zip": "12345",
        "isPrimaryAddress": "N"
      }
    ]
}

I'm not at all that familiar with XML encoding in Go and the best I've been able to manage is this:

 {
      "custProfile": {
        "dob": "1990-10-01",
        "address": null
      }
 }

Any help would be greatly appreciated. Thanks


问:
Is number recognition on iPhone possible in real-time?
I need to recognise numbers from the camera image on iPhone, in real-time. I know there will be no more than 5 digits on the image.

Is this problem realistic to solve given the computational specifications of the iPhone?
Does anyone have any experience using the Tesseract OCR library, and do you think it could be solved by using it?

答:
Yes. Bender can help you with that. It lets you build and run neural nets on iOS. As it uses Metal under the hood, it runs fast and smooth. It also supports running TensorFlow models directly.

So you can run in Bender an existing model in TensorFlow trained for digit recognition Handwritten Digit Recognition using Convolutional Neural Networks in Python with Keras if you need help

Disclaimer: I worked on this project.


问:
C# - get data between dates
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

```<code>string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));
</code>```

But my reader returns empty, what am I doing wrong?

答:
You have your dates the wrong way around, try this instead:</p>

```<code>SELECT price FROM table WHERE  timestamp >= @yes AND timestamp <= @now;
</code>```

Title: C# - get data between dates

Body:
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));

But my reader returns empty, what am I doing wrong?

Body:
You have your dates the wrong way around, try this instead:

SELECT price FROM table WHERE  timestamp >= @yes AND timestamp <= @now;


问:
How can div maintain the same size when on mobile
I am working on a UI that, when displaying on a mobile device, gets too small for it to be used properly.

I have the size of the div fixed in pixels, and it keeps the size if the window is resized, but when I test it on mobile mode on chrome or on a actual mobile device, it shrinks. How can I stop it from behaving like that?

答:
Without being able to see your code it's hard to give you the correct specifics. That said, there are two common places to start, these are:

This meta tag will allow mobile browsers render pages in a virtual "window" (the viewport), usually wider than the screen, so they don't need to squeeze every page layout into a tiny window.

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

CSS media queries will give you the flexibility to change how your page appears at different screen sizes.

Body:
Without being able to see your code it's hard to give you the correct specifics. That said, there are two common places to start, these are:

This meta tag will allow mobile browsers render pages in a virtual "window" (the viewport), usually wider than the screen, so they don't need to squeeze every page layout into a tiny window.

<meta name="viewport" content="width=device-width, initial-scale=1">

CSS media queries will give you the flexibility to change how your page appears at different screen sizes.


问:
Genetic algorithms: How to do crossover in "subset" problems?
I have a problem which I am trying to solve with genetic algorithms. The problem is selecting some subset (say 4) of 100 integers (these integers are just ids that represent something else). Order does not matter, the solution to the problem is a SET of integers not an ordered list. I have a good fitness function but am having trouble with the crossover function.

I want to be able to mate the following two chromosomes:

[1 2 3 4] and
[3 4 5 6] into something useful. Clearly I cannot use the typical crossover function because I could end up with duplicates in my children which would represent invalid solutions. What is the best crossover method in this case.

答:
I don't really know what you mean on "typical crossover", but I think you could use a crossover similar to what is often used for permutations:

take m ints from the first parent (m < n, where n is the number of ints in your sets)

scan the second and fill your subset from it with (n-m) ints that are free (not in the subset already).

This way you will have n ints from the first and n-m ints from the second parent, without duplications.

Sounds like a valid crossover for me :-).

I guess it might be beneficial not to do either steps on ordered sets (or using an iterator where the order of returned elements correlates somehow with the natural ordering of ints), otherwise either smaller or higher numbers will get a higher chance to be in the child making your search biased.

If it is the best method depends on the problem you want to solve...


问:
Discovering Hazelcast Cluster Groups
I'm using a couple of Hazelcast clusters for separate purposes and don't want them to interact so have used different cluster groups. I've written a simple monitor application to keep track of the members of each cluster, but wondered if there's a way of determining which cluster groups are reachable? The monitor connects as a client and I've had to hard code cluster group names in my application configuration so it can attempt to create a connection with each. That's fine for the moment with only two groups but as my usage expands it would be helpful if I could programmatically determine all the clusters available for connection - is this possible?

Thanks

答:
Group names are the credentials for the Clusters. Unless you know the name, you won't be able to connect to it.

We have a similar use-case and are handling this by maintaining a property of list of group names and just looping through them to check the connections. This requires you to either have a common group password or retrieve the corresponding passwords from other source.

Title: Discovering Hazelcast Cluster Groups


问:
How to make sure a button click is process by a webpage before continuing with automation selenium
I'm trying to automate the login process to a webpage using selenium and chrome driver. The webpage login button element looks like this;

```<code><div class="button small"><a class="btn-login" href="#">Login</a></div>
</code>```

So I click it using the following;

```<code>bot.FindElement(By.LinkText("Login")).Click()
</code>```

Where 'bot' is my chrome driver. This works, 100% of the time it clicks the button. I'd now like to automate the next step of the processes but here's where I hit a snag. Clicking the button doesn't load a new webpage, it just runs a script on the page where I need to click another button (basically select what area I want to log into). How can I wait until the webpage has processed the first click so I can process the next click. When I try the next click I get this error;

```<code>System.InvalidOperationException: 'unknown error: Element <a class="area-select" href="/page/area/start">...</a> is not clickable at point (542, 318). Other element would receive the click: <div class="right login">...</div>

 (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.15063 x86_64)'
</code>```

I don't really know what this error means. It looks like it's saying the button I want to click isn't clickable (but I can manually click it in the browser) so I assume it means the element isn't activated when I send the command? If so how can I wait until this?

答: Try to insert some hard wait or apply some implicit wait for that particular element befire clicking</p>

Body:
I'm trying to automate the login process to a webpage using selenium and chrome driver. The webpage login button element looks like this;

Login

So I click it using the following;

bot.FindElement(By.LinkText("Login")).Click()

Where 'bot' is my chrome driver. This works, 100% of the time it clicks the button. I'd now like to automate the next step of the processes but here's where I hit a snag. Clicking the button doesn't load a new webpage, it just runs a script on the page where I need to click another button (basically select what area I want to log into). How can I wait until the webpage has processed the first click so I can process the next click. When I try the next click I get this error;

System.InvalidOperationException: 'unknown error: Element ... is not clickable at point (542, 318). Other element would receive the click:
...

 (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.15063 x86_64)'

I don't really know what this error means. It looks like it's saying the button I want to click isn't clickable (but I can manually click it in the browser) so I assume it means the element isn't activated when I send the command? If so how can I wait until this?