问:
How to avoid crashes due to missing string entries?
I have an app translated in 3 languages: English, German, Polish

So I have these three folders for the languages in the project:

```<code>values
strings.xml

values-en
strings.xml

values-de
strings.xml

values-pl
strings.xml
</code>```

I have realized that If I put all strings into values folder and have some strings missing in the Polish version that the app crashes when accessing the missing strings in the Polish version.

I would have expected that the system just gets the string from the default values folder if it does not find it in values-pl folder.

Is there any way to catch these potential missing string crashes? EVen if I could get a warning in the compiler that the string in any language is missing would be OK?

EDIT AND ADDITION

In fact another string was missing in the default too.... so thanks for the answer/comments!

But now I have also tested the case where there is a string simply missing in the default strings.xml file only BUT present in all the other files. I do not get any warning or anything else.

So in this case if ALL the strings are present in de,en,pl but one is missing in default, then the app crashes in China for example (I understand of course because the default is missing).

BUT what bothers me is that I do not find any way to check the completeness of all referenced strings in code. This is how I access the missing string:

```<code>context.getString(R.string.MYTRING_abc),
</code>```

答:
In Android Studio:

```<code>Settings -> Editor -> Inspections -> (search for or find) Incomplete translation
</code>```

Set to info or warning. Error prevents the app from being created when you press create signed APK.

In my own experience, I only get this error when I create a build (non-debug through USB debugging, meaning when it is a signed build) but changing the incomplete translation to warning (so I get a notification it isn't finished, but it isn't ignored in case I just forgot) (or info for that matter) allows the app to be built and it functions just like in debug where incomplete translations go to the default value.

But if you experience the error in debug as well, this should still work and prevent crashing in APK creation

Body:
I have an app translated in 3 languages: English, German, Polish

So I have these three folders for the languages in the project:

values
strings.xml

values-en
strings.xml

values-de
strings.xml

values-pl
strings.xml

I have realized that If I put all strings into values folder and have some strings missing in the Polish version that the app crashes when accessing the missing strings in the Polish version.

I would have expected that the system just gets the string from the default values folder if it does not find it in values-pl folder.

Is there any way to catch these potential missing string crashes? EVen if I could get a warning in the compiler that the string in any language is missing would be OK?

EDIT AND ADDITION

In fact another string was missing in the default too.... so thanks for the answer/comments!

But now I have also tested the case where there is a string simply missing in the default strings.xml file only BUT present in all the other files. I do not get any warning or anything else.

So in this case if ALL the strings are present in de,en,pl but one is missing in default, then the app crashes in China for example (I understand of course because the default is missing).

BUT what bothers me is that I do not find any way to check the completeness of all referenced strings in code. This is how I access the missing string:

context.getString(R.string.MYTRING_abc),

Body:
In Android Studio:

Settings -> Editor -> Inspections -> (search for or find) Incomplete translation

Set to info or warning. Error prevents the app from being created when you press create signed APK.

In my own experience, I only get this error when I create a build (non-debug through USB debugging, meaning when it is a signed build) but changing the incomplete translation to warning (so I get a notification it isn't finished, but it isn't ignored in case I just forgot) (or info for that matter) allows the app to be built and it functions just like in debug where incomplete translations go to the default value.

But if you experience the error in debug as well, this should still work and prevent crashing in APK creation


来源: stackexchange

问:
Converting an ArrayList<someObjects> to an HTML table
I have a couple of ArrayLists with variable length and sometimes null. This ArrayList contains a bunch of objects.
The table should have columns based on (some) attributes of the object. And the table should be displayed on a jsp.

I have two ideas, one is to use a JSTL tag the other is to use JavaScript. And library suggestions are welcome.

答:
JSTL is the standard, preferred way (unless you need to load it via ajax, for example)</p>

```<code><table>
<tr><td>Foo header</td><td>Bar header</td></tr>
<c:forEach items="${yourRequestScopedArrayList}" var="obj">
    <tr>
       <td>${obj.foo}</td>
       <td>${obj.bar}</td>
    </tr>
</c:forEach>
</table>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
JSTL is the standard, preferred way (unless you need to load it via ajax, for example)

<table>
<tr><td>Foo header</td><td>Bar header</td></tr>
<c:forEach items="${yourRequestScopedArrayList}" var="obj">
    <tr>
       <td>${obj.foo}</td>
       <td>${obj.bar}</td>
    </tr>
</c:forEach>
</table>


问:
Add prefix to EditorFor for all elements
I have the following model:

```<code>public class CaseFormViewModel
{
    public int ID { get; set; }
    public int AppID { get; set; }

    public CaseGeneralFormViewModel General { get; set; }

    public CaseMedicalFormViewModel Medical { get; set; }

    public CaseLegalFormViewModel Legal { get; set; }

    public CaseCommentsFormViewModel Comments { get; set; }

    public List<UploadedDocumentModel> Attachments { get; set; }

    public string AzureStorage { get; set; }

}

public class CaseGeneralFormViewModel : CaseGeneralViewModelBase
{
    [Required]
    public new string PatientName { get; set; }
</code>```

also I have a view with model CaseFormViewModel and have a Partial View with model CaseGeneralFormViewModel. View loads this partial View:

```<code>@Html.Partial("PartialCaseGeneralForm", Model.General)
</code>```

Partial View has the following string:

```<code>@Html.ValidationMessageFor(model => model.PatientName)
</code>```

then, when I post this view to the controller method:

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateCase(int AppID, CHFN.Models.CaseFormViewModel model)
    {
</code>```

model.General is null. I understand why, because PatientName should have id="General.PatientName" instead of id="PatientName", but how can I add that prefix to the all elements on page?

I see some ability to do it : modify post controller method to:

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateCase(int AppID, CaseGeneralFormViewModel general)
    {
</code>```

but first at all, code is dirty (structure of internal classes are broken), secondly - any class (i.e. CaseGeneralFormViewModel) can have 2 properties of the same class (i.e.

```<code>public Class1 Prop1 { get; set; }
public Class1 Prop2 { get; set; }
</code>```

). How to solve it - I don't know....

答:
In asp.net core mvc</p>

```<code>public static class HtmlHelperPartialExtensions
{
    public static IHtmlContent PartialWithPrefix(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var htmlFieldPrefix = (string.Empty.Equals(prefix) ? "." : "") + prefix;
        return htmlHelper.Partial(partialViewName, model, new ViewDataDictionary(htmlHelper.ViewData) { TemplateInfo = { HtmlFieldPrefix = htmlFieldPrefix } });
    }

    public static Task<IHtmlContent> PartialWithPrefixAsync(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var htmlFieldPrefix = (string.Empty.Equals(prefix) ? "." : "") + prefix;
        return htmlHelper.PartialAsync(partialViewName, model, new ViewDataDictionary(htmlHelper.ViewData) {TemplateInfo = {HtmlFieldPrefix = htmlFieldPrefix}});
    }

    public static IHtmlContent PartialWithPrefixFor<TModel, TProperty>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string prefix = ExpressionHelper.GetExpressionText(expression);
        object model = ExpressionMetadataProvider.FromLambdaExpression(expression, helper.ViewData, helper.MetadataProvider).Model;
        return PartialWithPrefix(helper, partialViewName, model, prefix);
    }

    public static Task<IHtmlContent> PartialWithPrefixForAsync<TModel, TProperty>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string prefix = ExpressionHelper.GetExpressionText(expression);
        object model = ExpressionMetadataProvider.FromLambdaExpression(expression, helper.ViewData, helper.MetadataProvider).Model;
        return PartialWithPrefixAsync(helper, partialViewName, model, prefix);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following model:

public class CaseFormViewModel
{
    public int ID { get; set; }
    public int AppID { get; set; }

    public CaseGeneralFormViewModel General { get; set; }

    public CaseMedicalFormViewModel Medical { get; set; }

    public CaseLegalFormViewModel Legal { get; set; }

    public CaseCommentsFormViewModel Comments { get; set; }

    public List<UploadedDocumentModel> Attachments { get; set; }

    public string AzureStorage { get; set; }

}

public class CaseGeneralFormViewModel : CaseGeneralViewModelBase
{
    [Required]
    public new string PatientName { get; set; }

also I have a view with model CaseFormViewModel and have a Partial View with model CaseGeneralFormViewModel. View loads this partial View:

@Html.Partial("PartialCaseGeneralForm", Model.General)

Partial View has the following string:

@Html.ValidationMessageFor(model => model.PatientName)

then, when I post this view to the controller method:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateCase(int AppID, CHFN.Models.CaseFormViewModel model)
    {

model.General is null. I understand why, because PatientName should have id="General.PatientName" instead of id="PatientName", but how can I add that prefix to the all elements on page?

I see some ability to do it : modify post controller method to:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateCase(int AppID, CaseGeneralFormViewModel general)
    {

but first at all, code is dirty (structure of internal classes are broken), secondly - any class (i.e. CaseGeneralFormViewModel) can have 2 properties of the same class (i.e.

public Class1 Prop1 { get; set; }
public Class1 Prop2 { get; set; }

). How to solve it - I don't know....

Body:
In asp.net core mvc

public static class HtmlHelperPartialExtensions
{
    public static IHtmlContent PartialWithPrefix(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var htmlFieldPrefix = (string.Empty.Equals(prefix) ? "." : "") + prefix;
        return htmlHelper.Partial(partialViewName, model, new ViewDataDictionary(htmlHelper.ViewData) { TemplateInfo = { HtmlFieldPrefix = htmlFieldPrefix } });
    }

    public static Task<IHtmlContent> PartialWithPrefixAsync(this IHtmlHelper htmlHelper, string partialViewName, object model, string prefix)
    {
        var htmlFieldPrefix = (string.Empty.Equals(prefix) ? "." : "") + prefix;
        return htmlHelper.PartialAsync(partialViewName, model, new ViewDataDictionary(htmlHelper.ViewData) {TemplateInfo = {HtmlFieldPrefix = htmlFieldPrefix}});
    }

    public static IHtmlContent PartialWithPrefixFor<TModel, TProperty>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string prefix = ExpressionHelper.GetExpressionText(expression);
        object model = ExpressionMetadataProvider.FromLambdaExpression(expression, helper.ViewData, helper.MetadataProvider).Model;
        return PartialWithPrefix(helper, partialViewName, model, prefix);
    }

    public static Task<IHtmlContent> PartialWithPrefixForAsync<TModel, TProperty>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
    {
        string prefix = ExpressionHelper.GetExpressionText(expression);
        object model = ExpressionMetadataProvider.FromLambdaExpression(expression, helper.ViewData, helper.MetadataProvider).Model;
        return PartialWithPrefixAsync(helper, partialViewName, model, prefix);
    }
}


问:
Updating Custom Interactive Map
I'm running into an issue. I'm trying to rewrite an old flash/xml map using CSS. I have a big jpg of the map, which is the background. I'm able to lay the icons out, where they need to be.

The problem I'm having is centering the whole thing on the page. Ideally, the map would be centered and the user would be able to click and drag the background image to look at the various sections, the way Google Maps or something works.

How can I do this, or what is this effect called, so I can google it more in depth. Searching "map" at all gives results about customizing Google Maps. Which isn't what I'm trying to do. I'm thinking it'll involve absolute positioning and and viewports, but I don't know exactly how to code it.

Should I just make a frame?

答: It looks like Leaflet will probably solve the problem. http://leafletjs.com/ </p>

Title: Updating Custom Interactive Map


问:
Access main package from other package
I want to access the main package from another package, but this is impossible because the main file isn't in a directory. I already tried putting the main file in a directory, but when I try to import it I get this error:

import "../main" is a program, not an importable package

The reason that I want this because I have a tcp server and a webserver that work together. The webserver can get the tcp server via the main package and the tcp server can get the webserver via the main package.

I already got it working with the webserver and tcpserver reading from each other(without the main package in the middle), but I want to keep some parts of the application at one place.

Is the the thing I want possible(Via the main package)? Or is it just stupid.

答: You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).

ContentLicense: CC BY-SA 4.0

Title: Access main package from other package


问:
How to encrypt to Django default pbkdf2_sha256 encryption?
I want to encrypt the user input password to compare with the original password in some view. I tried importing and apply encrypt method:

```<code>import passlib.hash.django_pbkdf2_sha256
</code>```

But it doesn't have that module?

答:
You may be looking for set_password

```<code>from models import User
new_user = User.objects.create(username='new_user', email='example@example.com')
new_user.set_password('newpassword')
</code>```

Alternatively, you can use make_password

```<code>from django.contrib.auth.hashers import make_password
from models import User
first_pass = User.objects.all()[0].password.split('$')
hasher = first_pass[0]
salt = first_pass[1]  # grabbing salt from the first password of the database
make_password('newpassword', salt, hasher)
</code>```

Body:
I want to encrypt the user input password to compare with the original password in some view. I tried importing and apply encrypt method:

import passlib.hash.django_pbkdf2_sha256

But it doesn't have that module?

Body:
You may be looking for set_password

from models import User
new_user = User.objects.create(username='new_user', email='example@example.com')
new_user.set_password('newpassword')

Alternatively, you can use make_password

from django.contrib.auth.hashers import make_password
from models import User
first_pass = User.objects.all()[0].password.split('$')
hasher = first_pass[0]
salt = first_pass[1]  # grabbing salt from the first password of the database
make_password('newpassword', salt, hasher)


问:
How do I dynamically add environment variables to zsh prompt?
EDIT: Original title said "bash prompt", but I use "zsh". I accepted @Artur R. Czechowski's answer because it was correct in a bash context and I was able to make mine work with his help. PROMPT is now '   ${ENV}${ENV:+ } %F{249}${PWD/#$HOME/~} %{$fg[green]%}'○'  ', just adding the bit about ENV was all I needed.

ORIGINAL POST: As part of my job, I change environment variables frequently. So frequently that I feel I'm going to inevitably going to forget which one I'm in and do something I shouldn't. In case it's relevant to you answering my question, I change environment by running a shell script and my current bash prompt is PROMPT='   %F{249}${PWD/#$HOME/~} %{$fg[green]%}'○'  '.

If I'm in a virtual environment, such as venv, then my prompt gets prefaced with (.venv). How do I get something similar with an environment variable such as DB_HOST or whatever variable I want? If DB_HOST changes, I want the bash prompt to change right away and persist.

答:
PROMPT_COMMAND is your answer. Example:

```<code>myprompt() {
    PS1="${DB_HOST}${DB_HOST:+ }\u@\h:\w\$ "
}

PROMPT_COMMAND=myprompt
</code>```

It will always display current value of DB_HOST variable.

Body:
PROMPT_COMMAND is your answer. Example:

myprompt() {
    PS1="${DB_HOST}${DB_HOST:+ }\u@\h:\w\$ "
}

PROMPT_COMMAND=myprompt

It will always display current value of DB_HOST variable.


问:
wpf , binding and datacontext
This is my ViewModel -

```<code> public class ViewModel
{
    public ObservableCollection<Person> Persons { get; set; }
}
</code>```

and this is Class Person:

```<code>public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

Now, every time one of the persons's FirstName is changing I want to do some tasks,
lets say raise a messagebox.

How do I do that ?

答:
You need to implement INotifyPropertyChanged on your viewmodel, and raise the property changed event when setting your persons collection. This will allow you listen for the fact that it has changed.

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

Title: wpf , binding and datacontext

Body:
This is my ViewModel -

 public class ViewModel
{
    public ObservableCollection<Person> Persons { get; set; }
}

and this is Class Person:

public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Now, every time one of the persons's FirstName is changing I want to do some tasks,
lets say raise a messagebox.

How do I do that ?


问:
changing static variables from another method in java
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

```<code>public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}
</code>```

答:
The problem comes from your second method. You pass changeX, changeY, and changeZ but try to set the values of x, y, and z. The variables x, y, and z are not within the scope of this method and therefore the program will throw an error.

Moreover, this methodology will not work regardless of these names. Java does not allow you to change the values of primitives when you pass them to a new method. The best solution is probably to put them in an array and change the second method to accept an array. The body of your first method may now look like

```<code>int [] intarray = new int[3];
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
change(intarray);
System.out.println(intarray[0]);
System.out.println(intarray[1]);
System.out.println(intarray[2]);
</code>```

and the second method would become

```<code>private static void change(int [] changeArray) {
    changeArray[0] *= 2;
    changeArray[1] += 2;
    changeArray[2] /= 2;
}
</code>```

(The *=, +=, and /= operators are shorthand for what you were doing above.

Body:
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}

Body:
The problem comes from your second method. You pass changeX, changeY, and changeZ but try to set the values of x, y, and z. The variables x, y, and z are not within the scope of this method and therefore the program will throw an error.

Moreover, this methodology will not work regardless of these names. Java does not allow you to change the values of primitives when you pass them to a new method. The best solution is probably to put them in an array and change the second method to accept an array. The body of your first method may now look like

int [] intarray = new int[3];
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
change(intarray);
System.out.println(intarray[0]);
System.out.println(intarray[1]);
System.out.println(intarray[2]);

and the second method would become

private static void change(int [] changeArray) {
    changeArray[0] *= 2;
    changeArray[1] += 2;
    changeArray[2] /= 2;
}

(The *=, +=, and /= operators are shorthand for what you were doing above.


问:
VS code version for CentOS 5 or 6?
Can I ask if there is a version of VS Code that works for CentOS 5 or 6? When trying installing VS, I encountered this error message

Many thanks in advance!

答: Unfortunately you cannot install VS Code on a CentOS 5 or 6 machine.  The requirements state that only CentOS 7 is supported due to the GLIBC issue you ran into above.</p>

Title: VS code version for CentOS 5 or 6?


问:
AngularJS disable double click
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

```<code><div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    <a class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</a>
</div>
</code>```

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

答:
What about using a simple behaviour directive?

function oneTimeCallDirective($timeout) {
  var httpCallMock = (cb = () => 'ok') => $timeout(cb, 5000);

  return function oneTimeCallPostLink(iScope, iElement) {
    let busy = false;

    return iElement
      .on('click dblclick', function(event) {
        if(busy) {
          return event.preventDefault();
        }

        busy = true;

        console.info('Well, Calling.');

        return httpCallMock()
          .then(() => {
            console.log('You Can Start Calling Again');
          })
          .finally(() => {
            busy = false;
          })
        ;
      })
    ;
  };
}

angular
  .module('test', [])
  .directive('oneTimeCall', oneTimeCallDirective)
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="test">
  <button one-time-call>Click Here</button>
</section></code>```

Title: AngularJS disable double click

Body:
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    {{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

Body:
What about using a simple behaviour directive?

function oneTimeCallDirective($timeout) {
  var httpCallMock = (cb = () => 'ok') => $timeout(cb, 5000);

  return function oneTimeCallPostLink(iScope, iElement) {
    let busy = false;

    return iElement
      .on('click dblclick', function(event) {
        if(busy) {
          return event.preventDefault();
        }

        busy = true;

        console.info('Well, Calling.');

        return httpCallMock()
          .then(() => {
            console.log('You Can Start Calling Again');
          })
          .finally(() => {
            busy = false;
          })
        ;
      })
    ;
  };
}

angular
  .module('test', [])
  .directive('oneTimeCall', oneTimeCallDirective)
;

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="test">
  <button one-time-call>Click Here</button>
</section>


问:
React Native - Difference between onChange vs onChangeText of TextInput
I'm not sure when to use onChange vs onChangeText in a TextInput component. I know onChangeText accepts the changed text as an arg in the callback, but is that why you would use onChangeText, since you can then update state within the callback?

答:
UPDATE 26.08.2019

Since the initial version of the answer, TextInput's API has changed, and answer below is no longer valid. I haven't worked with react-native for more than 2 years now, so I can't really tell which version had these changes.

Regarding the answer, onChangeText is still a simple prop, that gives whatever is the value of the input field on every change.

onChange on the other hand, passes an event with { nativeEvent: { eventCount, target, text} } (as mentioned in the comment to this answer). Now, I cannot tell with confidence, why do you need eventCount and target. I can only state, that eventCount is increased every time you interact with TextInput component (character added, removed, all deleted, value pasted) and target is a unique integer for that TextInput field. And text is the same value as in onChangeText

So basically, I would suggest to use onChangeText, as a more straight forward prop.

If you want to accomplish functionality like in the old answer(below), you can create custom component, that wraps TextInput and receives custom properties and passes them to the onChange prop later. Example below:

```<code>const MyTextInput = ({ value, name, type, onChange }) => {
  return (
    <TextInput
      value={value}
      onChangeText={text => onChange({ name, type, text })}
    />
  );
};
</code>```

And then use it whenever you need to use TextInput

```<code>handleChange(event) {
    const {name, type, text} = event;
    let processedData = text;
    if(type==='text') {
        processedData = value.toUpperCase();
    } else if (type==='number') {
        processedData = value * 2;
    }
    this.setState({[name]: processedData})
}

<MyTextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<MyTextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>

</code>```

OLD ANSWER

onChangeText is basically a simplified version of onChange, so you can easily use it, without the hassle of going through event.target.value to get changed value.

So, when should you use onChange and when onChangeText?

If you have simple form with few textinputs, or simple logic, you can go straight away and use onChangeText

```<code><TextInput value={this.state.name} onChangeText={(text) => this.setState({name: text})}>
</code>```

If you have more complicated forms and/or you have more logic in handling data (like handling text differently from number) when user changes input, then you are better of with onChange, because it gives you more flexibility. For example:

```<code>handleChange(event) {
    const {name, type, value} = event.nativeEvent;
    let processedData = value;
    if(type==='text') {
        processedData = value.toUpperCase();
    } else if (type==='number') {
        processedData = value * 2;
    }
    this.setState({[name]: processedData})
}

<TextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<TextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>
</code>```

Body:
UPDATE 26.08.2019

Since the initial version of the answer, TextInput's API has changed, and answer below is no longer valid. I haven't worked with react-native for more than 2 years now, so I can't really tell which version had these changes.

Regarding the answer, onChangeText is still a simple prop, that gives whatever is the value of the input field on every change.

onChange on the other hand, passes an event with { nativeEvent: { eventCount, target, text} } (as mentioned in the comment to this answer). Now, I cannot tell with confidence, why do you need eventCount and target. I can only state, that eventCount is increased every time you interact with TextInput component (character added, removed, all deleted, value pasted) and target is a unique integer for that TextInput field. And text is the same value as in onChangeText

So basically, I would suggest to use onChangeText, as a more straight forward prop.

If you want to accomplish functionality like in the old answer(below), you can create custom component, that wraps TextInput and receives custom properties and passes them to the onChange prop later. Example below:

const MyTextInput = ({ value, name, type, onChange }) => {
  return (
    <TextInput
      value={value}
      onChangeText={text => onChange({ name, type, text })}
    />
  );
};

And then use it whenever you need to use TextInput

handleChange(event) {
    const {name, type, text} = event;
    let processedData = text;
    if(type==='text') {
        processedData = value.toUpperCase();
    } else if (type==='number') {
        processedData = value * 2;
    }
    this.setState({[name]: processedData})
}

<MyTextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<MyTextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>

OLD ANSWER

onChangeText is basically a simplified version of onChange, so you can easily use it, without the hassle of going through event.target.value to get changed value.

So, when should you use onChange and when onChangeText?

If you have simple form with few textinputs, or simple logic, you can go straight away and use onChangeText

<TextInput value={this.state.name} onChangeText={(text) => this.setState({name: text})}>

If you have more complicated forms and/or you have more logic in handling data (like handling text differently from number) when user changes input, then you are better of with onChange, because it gives you more flexibility. For example:

handleChange(event) {
    const {name, type, value} = event.nativeEvent;
    let processedData = value;
    if(type==='text') {
        processedData = value.toUpperCase();
    } else if (type==='number') {
        processedData = value * 2;
    }
    this.setState({[name]: processedData})
}

<TextInput name="username" type="text" value={this.state.username} onChange={this.handleChange}}>
<TextInput name="password" type="number" value={this.state.password} onChange={this.handleChange}}>


问:
How to run node.js ES6 file on mac
Can someone help me run a node.js file that has ES6 features? This is my current workflow:

Save change in file

npm run build --- builds file to my src/dist folder

cd into my dist directory

node

var file = require('./index.js')

file.someMethod()

Then when I make a change to my method, I need to repeat all the steps above again.

Does anyone know of a more efficient way to do this?

Thanks in advance!

答:
It really depends on what npm run build actually does in your app. Does it run gulp/grunt? Webpack? Etc. If it's webpack there is a webpack-dev-server that you should look into.

If it's grunt or gulp then you have a custom build chain that you're working with. If all you need is to support es6 features without having to build the project then you could use something simple like babel-cli and run your file from outside the dist directory.

```<code>$ npm i -g babel-cli
$ babel-node
> var file = require('./index.js');
> file.someMethod()
</code>```

By running babel-node you're running the normal node repl but with babel required. Es6 features should now be supported in the repl without needing to be compiled to es5.

You may also want to try simply updating to the latest version of node because node 8 has pretty extensive es6 support.

Title: How to run node.js ES6 file on mac

Body:
It really depends on what npm run build actually does in your app. Does it run gulp/grunt? Webpack? Etc. If it's webpack there is a webpack-dev-server that you should look into.

If it's grunt or gulp then you have a custom build chain that you're working with. If all you need is to support es6 features without having to build the project then you could use something simple like babel-cli and run your file from outside the dist directory.

$ npm i -g babel-cli
$ babel-node
> var file = require('./index.js');
> file.someMethod()

By running babel-node you're running the normal node repl but with babel required. Es6 features should now be supported in the repl without needing to be compiled to es5.

You may also want to try simply updating to the latest version of node because node 8 has pretty extensive es6 support.


问:
Change styling of If Statements in Emacs?
My company has recently added some new code styling rules, and I would was wondering if there is an easy way via emacs to change a couple things w/ a regex replace.

if statements now have to look like the following:

```<code>if (expression) {
</code>```

where I have many that look like so:

```<code>if(expression){
</code>```

lacking the spaces. Is there an easy way to fix this?

答:
You might be able to regexp replace it if expression is always on one line, but I'd use a throw-away function just to be safe:

```<code>(defun my-fix-style ()
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "\\_<if(" nil t)
      (backward-char)
      (insert " ")
      (forward-sexp)
      (unless (looking-at "[ \t\n]")
        (insert " ")))))
</code>```

Body:
My company has recently added some new code styling rules, and I would was wondering if there is an easy way via emacs to change a couple things w/ a regex replace.

if statements now have to look like the following:

if (expression) {

where I have many that look like so:

if(expression){

lacking the spaces. Is there an easy way to fix this?

Body:
You might be able to regexp replace it if expression is always on one line, but I'd use a throw-away function just to be safe:

(defun my-fix-style ()
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "\\_<if(" nil t)
      (backward-char)
      (insert " ")
      (forward-sexp)
      (unless (looking-at "[ \t\n]")
        (insert " ")))))


问:
ListHeaderComponent receives object, expected a string or class/function
I am trying to render a FlatList component with a ListHeaderComponent prop,  The FlatList renders fine without that prop, but when I add ListHeaderComponent I get the following error.

Here's the render() function of the Discover class:

```<code>render() {
  renderFlatListItem = (event) => {
    return (
      <Event
        description={event.Description}
        startTime={event.StartTimeToString}
        Location={event.Location ? event.Location : 'TBD' }
        key={event.ID}
      />
    )
  }
  ListHeaderCreate = () => {
    return (
      <DiscoverSearch
        resultDescription={this.state.popularEvents ? 'Popular Events':
        'Search Results'}
        categories={this.state.categories}
        passCategory={this.handleSelectedCategory}
        passInitialPosition={this.handleInitialPosition}
        passLastPosition={this.handleLastPosition}
        passSearch={this.handleSearch}
      />
    );
  }
  return (
    <View>
      <FlatList
      ListHeaderComponent={ListHeaderCreate()}
        data={this.state.events}
        renderItem={({ item }) => (
          renderFlatListItem(item)
        )}
      />
    </View>
  );
}
</code>```

Here is the render() function of the DiscoverSearch class:

```<code>render () {
  const pickerItems = this.props.categories.map((category) => {
  <Picker.Item key={category.ID} label={category.Name} value={category.ID}/>
  });
  return (
    <View>
      <View>
        <TextInput
          style={{height: 40}}
          placeholder="Search Events"
          onChangeText={(text) => this.setState({searchText: text})}
        />
        <TextInput
          style={{height: 40}}
          placeholder="Location"
          onChangeText={(text) => this.setState({LocationText: text})}
        />
      </View>
      <View>
      <Picker
        onValueChange={(category) => this.props.passCategory}
      >
      {pickerItems}
      </Picker>
      <Button
       title='Search'
       onPress={console.log(this.state)}
      />
      </View>
    </View>
   )
 }
</code>```

I assume that the VirtualizedList must be a child of the flatList that I am importing from react-native, Should I be directing this question to the react-native repo on github? I can't find where my mistake is. Any help here would be greatly appreciated.

答:
So the issue here was with a mismatch in React Prop-Types. React Docs

The VirtualizedList component is expecting a class or a function, so passing it a function that evaluates a React Class will give it an object, and this throws an error.

The solution is to pass in the function itself like so:

```<code>ListHeaderComponent={ ListHeaderCreate }
</code>```

Body:
I am trying to render a FlatList component with a ListHeaderComponent prop,  The FlatList renders fine without that prop, but when I add ListHeaderComponent I get the following error.

Here's the render() function of the Discover class:

render() {
  renderFlatListItem = (event) => {
    return (
      <Event
        description={event.Description}
        startTime={event.StartTimeToString}
        Location={event.Location ? event.Location : 'TBD' }
        key={event.ID}
      />
    )
  }
  ListHeaderCreate = () => {
    return (
      <DiscoverSearch
        resultDescription={this.state.popularEvents ? 'Popular Events':
        'Search Results'}
        categories={this.state.categories}
        passCategory={this.handleSelectedCategory}
        passInitialPosition={this.handleInitialPosition}
        passLastPosition={this.handleLastPosition}
        passSearch={this.handleSearch}
      />
    );
  }
  return (
    <View>
      <FlatList
      ListHeaderComponent={ListHeaderCreate()}
        data={this.state.events}
        renderItem={({ item }) => (
          renderFlatListItem(item)
        )}
      />
    </View>
  );
}

Here is the render() function of the DiscoverSearch class:

render () {
  const pickerItems = this.props.categories.map((category) => {
  <Picker.Item key={category.ID} label={category.Name} value={category.ID}/>
  });
  return (
    <View>
      <View>
        <TextInput
          style={{height: 40}}
          placeholder="Search Events"
          onChangeText={(text) => this.setState({searchText: text})}
        />
        <TextInput
          style={{height: 40}}
          placeholder="Location"
          onChangeText={(text) => this.setState({LocationText: text})}
        />
      </View>
      <View>
      <Picker
        onValueChange={(category) => this.props.passCategory}
      >
      {pickerItems}
      </Picker>
      <Button
       title='Search'
       onPress={console.log(this.state)}
      />
      </View>
    </View>
   )
 }

I assume that the VirtualizedList must be a child of the flatList that I am importing from react-native, Should I be directing this question to the react-native repo on github? I can't find where my mistake is. Any help here would be greatly appreciated.

Body:
So the issue here was with a mismatch in React Prop-Types. React Docs

The VirtualizedList component is expecting a class or a function, so passing it a function that evaluates a React Class will give it an object, and this throws an error.

The solution is to pass in the function itself like so:

ListHeaderComponent={ ListHeaderCreate }


问:
iOS - image attachment for the text view changes attributes
I've a UITextView described as follows with the given attributes:

```<code>lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.backgroundColor = .white
    tv.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12) // Posicionamento do texto

    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16),        NSForegroundColorAttributeName: UIColor.blue]
    tv.typingAttributes = attr
    return tv
}()
</code>```

Everything works as expected until I attach an image to the UITextView.

The image gets inserted in the desired position but after its inserted it overrides my textView attributes.

The text becomes small and in a different color than the attributes I've implemented in its declaration.

I'm attaching the image as follows:

```<code>    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)
</code>```

What's causing this issue?

I've even tried to reenforce its attributes whenever I insert an UIImage to its content.

I've tried the following when adding the image:

```<code>    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)

    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.blue]
    self.inputTextView.typingAttributes = attr
</code>```

And it still doesn't change its attributes.

Whats causing this issue? Any tip?

Thanks

Edit

As suggested here's how I'm setting the cursor position

```<code>func textViewDidChange(_ textView: UITextView) {
    currentCursorLocation = textView.selectedRange.location
}
</code>```

I do this to insert the image at the current location of the text blinking cursor

答:
[Edit: Unfortunately this does not solve Ivan's problem - I leave the answer because it is interesting detail for those who do not understand Unicode character encoding].

String range specification is non-intuitive due to the subtleties of Unicode. I expect your issue is that the cursor position at which you are inserting your image is not where you think it is relative to the text and you are inserting the image at a Unicode scalar position that is not between Unicode code points, such that you are corrupting a unicode code. To understand why this can happen, see this Apple article.

Strings in Swift 2

I would suggest using the following notation when specifying string ranges (taken from this Stack Overflow answer: NSAttributedString and emojis: issue with positions and lengths).

```<code>// Convert to NSRange by computing the integer distances:
let nsRange = NSRange(location: text.utf16.distance(from: text.utf16.startIndex, to: from16),
                      length: text.utf16.distance(from: from16, to: to16))
</code>```

However without seeing how you set your cursor position, it is not possible for me to be sure this is the source of your problem. [Update: thanks for updating the question to show the cursor position - we got there in the end but for others, note, after setting the cursor position this way (which would have been fine), he was incrementing it by 1, which meant the issue I have referred to about Unicode scalars versus code points was in fact the issue].

Body:
I've a UITextView described as follows with the given attributes:

lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.backgroundColor = .white
    tv.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12) // Posicionamento do texto

    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16),        NSForegroundColorAttributeName: UIColor.blue]
    tv.typingAttributes = attr
    return tv
}()

Everything works as expected until I attach an image to the UITextView.

The image gets inserted in the desired position but after its inserted it overrides my textView attributes.

The text becomes small and in a different color than the attributes I've implemented in its declaration.

I'm attaching the image as follows:

    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)

What's causing this issue?

I've even tried to reenforce its attributes whenever I insert an UIImage to its content.

I've tried the following when adding the image:

    let att = NSTextAttachment()
    att.image = image
    let attrString = NSAttributedString(attachment: att)
    self.inputTextView.textStorage.insert(attrString, at: self.currentCursorLocation)

    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing, NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.blue]
    self.inputTextView.typingAttributes = attr

And it still doesn't change its attributes.

Whats causing this issue? Any tip?

Thanks

Edit

As suggested here's how I'm setting the cursor position

func textViewDidChange(_ textView: UITextView) {
    currentCursorLocation = textView.selectedRange.location
}

I do this to insert the image at the current location of the text blinking cursor

Body:
[Edit: Unfortunately this does not solve Ivan's problem - I leave the answer because it is interesting detail for those who do not understand Unicode character encoding].

String range specification is non-intuitive due to the subtleties of Unicode. I expect your issue is that the cursor position at which you are inserting your image is not where you think it is relative to the text and you are inserting the image at a Unicode scalar position that is not between Unicode code points, such that you are corrupting a unicode code. To understand why this can happen, see this Apple article.

Strings in Swift 2

I would suggest using the following notation when specifying string ranges (taken from this Stack Overflow answer: NSAttributedString and emojis: issue with positions and lengths).

// Convert to NSRange by computing the integer distances:
let nsRange = NSRange(location: text.utf16.distance(from: text.utf16.startIndex, to: from16),
                      length: text.utf16.distance(from: from16, to: to16))

However without seeing how you set your cursor position, it is not possible for me to be sure this is the source of your problem. [Update: thanks for updating the question to show the cursor position - we got there in the end but for others, note, after setting the cursor position this way (which would have been fine), he was incrementing it by 1, which meant the issue I have referred to about Unicode scalars versus code points was in fact the issue].


问:
Tensor Object is not Iterable with BasicLSTMCell
I have the following code:

```<code>def dense_layers(pool3):
    with tf.variable_scope('local1') as scope:
        # Move everything into depth so we can perform a single matrix multiply.
        shape_d = pool3.get_shape()
        shape = shape_d[1] * shape_d[2] * shape_d[3]
        # tf_shape = tf.stack(shape)
        tf_shape = 1024

        print("shape:", shape, shape_d[1], shape_d[2], shape_d[3])

        # So note that tf_shape = 1024, this means that we have 1024 features are fed into the network. And
        # the batch size = 1024. Therefore, the aim is to divide the batch_size into num_steps so that
        reshape = tf.reshape(pool3, [-1, tf_shape])
        # Now we need to reshape/divide the batch_size into num_steps so that we would be feeding a sequence
        # And note that most importantly is to have batch_partition_length followed by step_size in the parameter list.
        lstm_inputs = tf.reshape(reshape, [batch_partition_length, step_size, tf_shape])

        # print('RNN inputs shape: ', lstm_inputs.get_shape()) # -> (128, 8, 1024).

        # Note that the state_size is the number of neurons.
        lstm = tf.contrib.rnn.BasicLSTMCell(state_size)
        lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)
        tf.assign(init_state, final_state)
</code>```

So, I am taking the output of the pool layer and try to feed it into the LSTM in the network.

Initially I have declared the following:

```<code>state_size = 16
step_size = 8

batch_partition_length = int(batch_size / step_size)

init_state = tf.Variable(tf.zeros([batch_partition_length, state_size]))    # -> [128, 16].
</code>```

Therefore, I am getting an error on:

```<code>lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)
</code>```

As follows:

```<code>Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/AffectiveComputing/Brady_with_LSTM.py", line 197, in <module>
    predictions = dense_layers(conv_nets_output)
  File "C:/Users/user/PycharmProjects/AffectiveComputing/Brady_with_LSTM.py", line 162, in dense_layers
    lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 553, in dynamic_rnn
    dtype=dtype)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 720, in _dynamic_rnn_loop
    swap_memory=swap_memory)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2623, in while_loop
    result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2456, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2406, in _BuildLoop
    body_result = body(*packed_vars_for_body)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 705, in _time_step
    (output, new_state) = call_cell()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 691, in <lambda>
    call_cell = lambda: cell(input_t, state)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\contrib\rnn\python\ops\core_rnn_cell_impl.py", line 238, in __call__
    c, h = state
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 504, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.
</code>```

Any help is much appreciated!!

答:
The state for LSTMs really consists of two parts

State for the cell(s)

Previous outputs

This is alluded to in the docs for BasicLSTMCell. This paper has a good explanation of how LSTMs work which will help you understand why you need to keep two sets of states in an LSTM implementation. The reason an error is being thrown is because you need to supply a tuple of tensors for the initial state.

That said you have two options:

Supply an initial state that consists of two tensors.

Let the RNN cell generate its own initial state.

You would usually only do 1. if you wanted to override default behavior. In this case you are using the default (zero) initial state so you can do 2.

```<code>lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, dtype=tf.float32)
</code>```

Body:
I have the following code:

def dense_layers(pool3):
    with tf.variable_scope('local1') as scope:
        # Move everything into depth so we can perform a single matrix multiply.
        shape_d = pool3.get_shape()
        shape = shape_d[1] * shape_d[2] * shape_d[3]
        # tf_shape = tf.stack(shape)
        tf_shape = 1024

        print("shape:", shape, shape_d[1], shape_d[2], shape_d[3])

        # So note that tf_shape = 1024, this means that we have 1024 features are fed into the network. And
        # the batch size = 1024. Therefore, the aim is to divide the batch_size into num_steps so that
        reshape = tf.reshape(pool3, [-1, tf_shape])
        # Now we need to reshape/divide the batch_size into num_steps so that we would be feeding a sequence
        # And note that most importantly is to have batch_partition_length followed by step_size in the parameter list.
        lstm_inputs = tf.reshape(reshape, [batch_partition_length, step_size, tf_shape])

        # print('RNN inputs shape: ', lstm_inputs.get_shape()) # -> (128, 8, 1024).

        # Note that the state_size is the number of neurons.
        lstm = tf.contrib.rnn.BasicLSTMCell(state_size)
        lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)
        tf.assign(init_state, final_state)

So, I am taking the output of the pool layer and try to feed it into the LSTM in the network.

Initially I have declared the following:

state_size = 16
step_size = 8

batch_partition_length = int(batch_size / step_size)

init_state = tf.Variable(tf.zeros([batch_partition_length, state_size]))    # -> [128, 16].

Therefore, I am getting an error on:

lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)

As follows:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/AffectiveComputing/Brady_with_LSTM.py", line 197, in <module>
    predictions = dense_layers(conv_nets_output)
  File "C:/Users/user/PycharmProjects/AffectiveComputing/Brady_with_LSTM.py", line 162, in dense_layers
    lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, initial_state=init_state)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 553, in dynamic_rnn
    dtype=dtype)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 720, in _dynamic_rnn_loop
    swap_memory=swap_memory)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2623, in while_loop
    result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2456, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2406, in _BuildLoop
    body_result = body(*packed_vars_for_body)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 705, in _time_step
    (output, new_state) = call_cell()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\rnn.py", line 691, in <lambda>
    call_cell = lambda: cell(input_t, state)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\contrib\rnn\python\ops\core_rnn_cell_impl.py", line 238, in __call__
    c, h = state
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 504, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.

Any help is much appreciated!!

Body:
The state for LSTMs really consists of two parts

State for the cell(s)

Previous outputs

This is alluded to in the docs for BasicLSTMCell. This paper has a good explanation of how LSTMs work which will help you understand why you need to keep two sets of states in an LSTM implementation. The reason an error is being thrown is because you need to supply a tuple of tensors for the initial state.

That said you have two options:

Supply an initial state that consists of two tensors.

Let the RNN cell generate its own initial state.

You would usually only do 1. if you wanted to override default behavior. In this case you are using the default (zero) initial state so you can do 2.

lstm_outputs, final_state = tf.nn.dynamic_rnn(cell=lstm, inputs=lstm_inputs, dtype=tf.float32)


问:
Postgres equivalent to Oracle's "DIRECTORY" objects
Is it possible to create "DIRECTORY" object in Postgres?

If not can some help me with a solution how implement it on PostgreSQL.

答:
Not the best option, but you could use:

```<code>COPY (select 1) TO PROGRAM 'mkdir --mode=777 -p /path/to/your/directory/'
</code>```

Note that only the last part of directory get the permissions set in mode.

Body:
Not the best option, but you could use:

COPY (select 1) TO PROGRAM 'mkdir --mode=777 -p /path/to/your/directory/'

Note that only the last part of directory get the permissions set in mode.


问:
ASP.NET WebForm Hide

on my page I'am showing some items from database.

How can I hide some div if some value of my Item is < 0

Here's div which I want to hide when Item.quantity == 0

```<code><div class="campaign__offer-buybox" >
 <a href="/DodajDoKoszyka.aspx?id_produkt=<%#:Item.id_produkt %>" style="text-decoration: none;">
  <span class="campaign__offer-buybox--button js-add-to-cart">
  <span><i class="fa fa-shopping-cart" aria-hidden="true" style="margin-right: 5px;"></i>Kup Teraz</span>
  </span>
 </a>
</div>
</code>```

How can I do it?

答:
not a lot of info in your post but here is the basic way you would do it

```<code>  <script>
if(item.quantity =< 0){
var x = document.getElementsByClassName("campaign__offer-buybox");
x.style.display = "none"; }else{
var x = document.getElementsByClassName("campaign__offer-buybox");
x.style.display = "block";
 }
</script>
</code>```

good luck

Title: ASP.NET WebForm Hide <div>

Body:
on my page I'am showing some items from database.

How can I hide some div if some value of my Item is < 0

Here's div which I want to hide when Item.quantity == 0

 <a href="/DodajDoKoszyka.aspx?id_produkt=<%#:Item.id_produkt %>" style="text-decoration: none;">

  Kup Teraz

How can I do it?

Body:
not a lot of info in your post but here is the basic way you would do it

  <script>
if(item.quantity =< 0){
var x = document.getElementsByClassName("campaign__offer-buybox");
x.style.display = "none"; }else{
var x = document.getElementsByClassName("campaign__offer-buybox");
x.style.display = "block";
 }
</script>

good luck


问:
How to generate access token for IBM bluemix federated (corporate) user
I have a federated (corporate) id for IBM bluemix. I want non-browser access to a Bluemix client / API. I am trying to use this POST command (using curl) - POST http://iam.ng.bluemix.net/oidc/token ; but I get following error and message:
"errorCode":"BXNIM0608E"
"errorMessage":"You cannot authenticate with username and password, as you are a federated user"

Then I came across this post: https://developer.ibm.com/devops-services/2016/06/23/whats-federated-authentication-and-how-does-it-affect-me/

As mentioned at beginning of it, I need to use "IBM Bluemix Continuous Delivery" website (IBM Bluemix DevOps) to get the access token.

Can you please let me know where exactly on that website I can get the access token?

Regards,
Amit

答:
It seems you need to follow the instructions for IAM at https://console.ng.bluemix.net/docs/iam/apikeys.html#manapikey

That's where you can generate your API keys. I then found instructions to use the key to login as mentioned in https://console.ng.bluemix.net/docs/cli/reference/cfcommands/index.html#cf_login

bash$ cf login -u apikey -p $API_TOKEN


问:
Service `http` get method doesn't return success or error
I am writing a service that returns array of cars. My service method dont return sucess or error. The folder assets is in the same directory as `app folder.

This is my service method:

```<code>import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Car} from '../../../domain/car';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class CarService {

  constructor(private http: Http) {
  }
    getCarsMedium(): Promise<Car[]> {
       console.log("call1");
       return this.http.get('assets/data/cars-medium.json')
       .toPromise()
       .then(res => {
          console.log("sucess1" + res);
          console.log("sucess2" + res.json());
          return res.json().data as Car[]
          })
       .catch(error => {
          console.log("error");
          console.error(error);
       });
   }
</code>```

}

I call it as:

```<code>import {Component, OnInit} from '@angular/core';
import {Car} from "../../../domain/car";
import {CarService} from "./car.service";

@Component({
  moduleId: module.id,
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})

export class CarComponent implements OnInit {
  cars: Car[];

  constructor(private carService: CarService) {
  }

  ngOnInit() {
    console.log("call2");
    this.carService.getCarsMedium().then(function (cars) {
      cars => this.cars = cars;
      console.log(cars)
    });
  }
}
</code>```

This is how my json looks like:

```<code>{"data":[
    {"vin":"a1653d4d","year":1998, "brand":"VW","color":"White"},
    {"vin":"a1653d4w","year":1999, "brand":"VV","color":"White"}
]}
</code>```

Entity class:

```<code>export interface Car {
  vin?;
  year?;
  brand?;
  color?;
}
</code>```

EDIT:
getCarsMedium() dont return sucess or error.
console output:
    call2
    call1

答:
```<code>return this.http.get('assets/data/cars-medium.json')
    .toPromise()
    .then(res => res.json().data as Car[],
          res => console.log(res));
</code>```

Obviously, that won't print anything, since you're printing  the response from a second callback passed to then(), which is executed in case the promise is rejected (which it is not).

Do that instead:

```<code>return this.http.get('assets/data/cars-medium.json')
    .toPromise()
    .then(res => {
        console.log(res);
        console.log(res.json());
        return res.json().data as Car[]
    });
</code>```

Body:
I am writing a service that returns array of cars. My service method dont return sucess or error. The folder assets is in the same directory as `app folder.

This is my service method:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Car} from '../../../domain/car';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class CarService {

  constructor(private http: Http) {
  }
    getCarsMedium(): Promise<Car[]> {
       console.log("call1");
       return this.http.get('assets/data/cars-medium.json')
       .toPromise()
       .then(res => {
          console.log("sucess1" + res);
          console.log("sucess2" + res.json());
          return res.json().data as Car[]
          })
       .catch(error => {
          console.log("error");
          console.error(error);
       });
   }

}

I call it as:

import {Component, OnInit} from '@angular/core';
import {Car} from "../../../domain/car";
import {CarService} from "./car.service";

@Component({
  moduleId: module.id,
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})

export class CarComponent implements OnInit {
  cars: Car[];

  constructor(private carService: CarService) {
  }

  ngOnInit() {
    console.log("call2");
    this.carService.getCarsMedium().then(function (cars) {
      cars => this.cars = cars;
      console.log(cars)
    });
  }
}

This is how my json looks like:

{"data":[
    {"vin":"a1653d4d","year":1998, "brand":"VW","color":"White"},
    {"vin":"a1653d4w","year":1999, "brand":"VV","color":"White"}
]}

Entity class:

export interface Car {
  vin?;
  year?;
  brand?;
  color?;
}

EDIT:
getCarsMedium() dont return sucess or error.
console output:
    call2
    call1

Body:
return this.http.get('assets/data/cars-medium.json')
    .toPromise()
    .then(res => res.json().data as Car[],
          res => console.log(res));

Obviously, that won't print anything, since you're printing  the response from a second callback passed to then(), which is executed in case the promise is rejected (which it is not).

Do that instead:

return this.http.get('assets/data/cars-medium.json')
    .toPromise()
    .then(res => {
        console.log(res);
        console.log(res.json());
        return res.json().data as Car[]
    });


问:
Converting an ArrayList<someObjects> to an HTML table
I have a couple of ArrayLists with variable length and sometimes null. This ArrayList contains a bunch of objects.
The table should have columns based on (some) attributes of the object. And the table should be displayed on a jsp.

I have two ideas, one is to use a JSTL tag the other is to use JavaScript. And library suggestions are welcome.

答:
JSTL is better,

Javascript you should avoid as much as possible ,

I am not sure how you are going to render datatable using java script and Collection

How to use jstl with collection that has been demonstrated by Bozho in the same thread.


问:
GStreamer encountered a general stream error in Qt5 raspberry pi
I'm trying to play a video using QtMediaPlayer in Raspberry pi 2 B. The source code is as follows:

```<code>QMediaPlayer *media;
QVideoWidget *video;
...
...
media = new QMediaPlayer(parent);
video = new QVideoWidget(parent);
media->setVideoOutput(video);
media->setMedia(QUrl::fromLocalFile("/home/pi/Desktop/test3.mp4"));
media->play();
</code>```

But the result is a blank video screen and the following error:

```<code>** (Bus:2148): WARNING **: ffmpegcolorspace-vo: size 1105920 is not a
multiple of unit size 829440
Error: "GStreamer encountered a general stream error."
</code>```

System Information

Running latest raspbian Jessie OS,
Installed Qt5.3,
Installed gstreamer0.10-plugins-good/bad/ugly/ffmpeg and
Installed Mpeg-2 License

Here is the video test3.mp4

I ran this code in Windows with Qt5 installed; it is working there. But it's not working in the Raspberry pi. Please tell me what I'm missing here.

Trying Pipe from Shell

答:
Video playback on the Raspberry Pi is actually a bit of a tricky thing. The most common solution is to use OMXPlayer to play videos. It's a command line program, but there are lots of flags and repeated calls can control playback. All in all, it works pretty dang well for most smallish projects.

As far as actually using Qt, QMediaPlayer, and etc. I don't think you'll be able to make it work right out of the box. However, I  found a blog that discusses this issue and has some Raspberry Pi firmware that fixes QtMultimedia support on the Raspberry Pi.

Body:
I'm trying to play a video using QtMediaPlayer in Raspberry pi 2 B. The source code is as follows:

QMediaPlayer *media;
QVideoWidget *video;
...
...
media = new QMediaPlayer(parent);
video = new QVideoWidget(parent);
media->setVideoOutput(video);
media->setMedia(QUrl::fromLocalFile("/home/pi/Desktop/test3.mp4"));
media->play();

But the result is a blank video screen and the following error:

** (Bus:2148): WARNING **: ffmpegcolorspace-vo: size 1105920 is not a
multiple of unit size 829440
Error: "GStreamer encountered a general stream error."

System Information

Running latest raspbian Jessie OS,
Installed Qt5.3,
Installed gstreamer0.10-plugins-good/bad/ugly/ffmpeg and
Installed Mpeg-2 License

Here is the video test3.mp4

I ran this code in Windows with Qt5 installed; it is working there. But it's not working in the Raspberry pi. Please tell me what I'm missing here.

Trying Pipe from Shell


问:
Get SQL Query Data into HTML via PHP
I'm having a hard time pushing a ton of data from SQL into an HTML table.

I have a chartbuilder.php file which has this code in it:

```<code>$pieQueryCreates = "SELECT Count(Action) FROM dbo.File_System_Profiles WHERE Action like '%create%' AND (DATEDIFF(day,TimeOccurred,getdate()) between 0 and 30)";
$pieQueryResult  = sqlsrv_query($conn, $sQuery);

if ($pieResultCreates === false) {
    die(sqlsrv_errors(SQLSRV_ERR_ERRORS));
}
$pieQueryCreateCount = sqlsrv_fetch_array($pieQueryResult);
</code>```

This is my HTML:

```<code><?php require '/php/chartbuilder.php'; ?>
<?php echo $pieQueryCreateCount; ?>
</code>```

And I get nothing from the echo. If I echo $pieQuerCreateCount[0] I still get nothing from the echo. If I echo $pieQueryResult I get a Resource ID #4 which isn't a surprise but leads me to believe the query is being completed. Copy/pasting my SELECT statement into SQL returns the count as expected in a single row/column with no name.

I just need to be able to access that one value and nothing I am doing seems to work, I've read through the documentation for sqlsrv_fetch_array this multiple times and tried a variety of changes based on their examples to find no success.

答:
In your chartbuilder.php file generate an array with query results.

```<code>$pieQueryCreates = "SELECT Count(Action) FROM dbo.File_System_Profiles WHERE Action like '%create%' AND (DATEDIFF(day,TimeOccurred,getdate()) between 0 and 30)";
$pieQueryResult = sqlsrv_query($conn, $pieQueryCreates );
if($pieQueryResult === false){
    die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array($pieQueryResult,SQLSRV_FETCH_NUMERIC) ) {
      $results[] = $row;
}
</code>```

print_r($results); // check the array

Now in html display $results array in the way you like.
echo $results[0][0];

Title: Get SQL Query Data into HTML via PHP

Body:
I'm having a hard time pushing a ton of data from SQL into an HTML table.

I have a chartbuilder.php file which has this code in it:

$pieQueryCreates = "SELECT Count(Action) FROM dbo.File_System_Profiles WHERE Action like '%create%' AND (DATEDIFF(day,TimeOccurred,getdate()) between 0 and 30)";
$pieQueryResult  = sqlsrv_query($conn, $sQuery);

if ($pieResultCreates === false) {
    die(sqlsrv_errors(SQLSRV_ERR_ERRORS));
}
$pieQueryCreateCount = sqlsrv_fetch_array($pieQueryResult);

This is my HTML:

<?php require '/php/chartbuilder.php'; ?>
<?php echo $pieQueryCreateCount; ?>

And I get nothing from the echo. If I echo $pieQuerCreateCount[0] I still get nothing from the echo. If I echo $pieQueryResult I get a Resource ID #4 which isn't a surprise but leads me to believe the query is being completed. Copy/pasting my SELECT statement into SQL returns the count as expected in a single row/column with no name.

I just need to be able to access that one value and nothing I am doing seems to work, I've read through the documentation for sqlsrv_fetch_array this multiple times and tried a variety of changes based on their examples to find no success.

Body:
In your chartbuilder.php file generate an array with query results.

$pieQueryCreates = "SELECT Count(Action) FROM dbo.File_System_Profiles WHERE Action like '%create%' AND (DATEDIFF(day,TimeOccurred,getdate()) between 0 and 30)";
$pieQueryResult = sqlsrv_query($conn, $pieQueryCreates );
if($pieQueryResult === false){
    die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array($pieQueryResult,SQLSRV_FETCH_NUMERIC) ) {
      $results[] = $row;
}

print_r($results); // check the array

Now in html display $results array in the way you like.
echo $results[0][0];


问:
twbsPagination totalPage value always changing?
```<code> $('#pagination').twbsPagination({
                totalPages: "5",
                visiblePages: "5",
                onPageClick: function (event, page) {
}
</code>```

I have a list that can be filtered by 10, 100 and 1000. If the database has 12 document and the user uses the 10 filter, the totalPages would essentially be 2: 10 on the first page, and 2 documents on the second page.

答:
It depends on how do you retrieve information. In the case of AJAX-call you could do this way, after receving result:

```<code>  var $pagination = $('#pagination');
  var totalValue = 25; //for example
  var toShow = 20; //show 20 items
  var numOfPage = Math.ceil(totalValue / toShow);
  if (numOfPage > 1) {
      var totalPages = numOfPage;
      var currentPage = $pagination.twbsPagination('getCurrentPage');
      $pagination.twbsPagination('destroy');
      $pagination.twbsPagination($.extend({}, defaultOpts, {
                startPage: currentPage,
                totalPages: totalPages
      }));
   } else {
      $pagination.twbsPagination('destroy'); //don't show pagination
                                             //if all item on the 1st page
   }
</code>```

UPDATE on that onPageClick: function (event, page) {} event you should assign next ajax call and in success put provided code. Something like this.

```<code>  onPageClick: function (event, page) {
      loadNextValues(page); //function to retrieve information.
      //most probably you need this assignment -> page = page -/+ 1
      //I don't remember exactly
  }
</code>```

This pagination is lazy-loading. At least provided algorithm.

Body:
 $('#pagination').twbsPagination({
                totalPages: "5",
                visiblePages: "5",
                onPageClick: function (event, page) {
}

I have a list that can be filtered by 10, 100 and 1000. If the database has 12 document and the user uses the 10 filter, the totalPages would essentially be 2: 10 on the first page, and 2 documents on the second page.

Body:
It depends on how do you retrieve information. In the case of AJAX-call you could do this way, after receving result:

  var $pagination = $('#pagination');
  var totalValue = 25; //for example
  var toShow = 20; //show 20 items
  var numOfPage = Math.ceil(totalValue / toShow);
  if (numOfPage > 1) {
      var totalPages = numOfPage;
      var currentPage = $pagination.twbsPagination('getCurrentPage');
      $pagination.twbsPagination('destroy');
      $pagination.twbsPagination($.extend({}, defaultOpts, {
                startPage: currentPage,
                totalPages: totalPages
      }));
   } else {
      $pagination.twbsPagination('destroy'); //don't show pagination
                                             //if all item on the 1st page
   }

UPDATE on that onPageClick: function (event, page) {} event you should assign next ajax call and in success put provided code. Something like this.

  onPageClick: function (event, page) {
      loadNextValues(page); //function to retrieve information.
      //most probably you need this assignment -> page = page -/+ 1
      //I don't remember exactly
  }

This pagination is lazy-loading. At least provided algorithm.


问:
Django model field with default value from another model
I have a model like this:

```<code>class ModelA(models.Model):
    foo = models.CharField(max_length=255)
    bar = models.CharField(max_length=255)
</code>```

Now i wanna have something like this:

```<code>class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255, default=???)
</code>```

where i want fo2 to take a value from ModelA unless other is provided.

How should i do that?

答:
Do you want the default value of fo2 to equal to something related with the specific instance of aaa at creation?

The way to do that would be to override the save method

```<code>class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        if self.fo2 is None:
            self.fo2 = self.aaa._value_taken_from_Model_A
        super(ModelB, self).save(*args, **kwargs)
</code>```

Body:
I have a model like this:

class ModelA(models.Model):
    foo = models.CharField(max_length=255)
    bar = models.CharField(max_length=255)

Now i wanna have something like this:

class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255, default=???)

where i want fo2 to take a value from ModelA unless other is provided.

How should i do that?

Body:
Do you want the default value of fo2 to equal to something related with the specific instance of aaa at creation?

The way to do that would be to override the save method

class ModelB(models.Model):
    aaa = models.ForeignKey(ModelA)
    tar = models.Char(Field(max_length=255, default="")
    fo2 = models.CharField(max_length=255)

    def save(self, *args, **kwargs):
        if self.fo2 is None:
            self.fo2 = self.aaa._value_taken_from_Model_A
        super(ModelB, self).save(*args, **kwargs)


问:
Posted objects in RequestTemplate end up having null fields once they reach the RestController
I am trying to save a domain object via my REST api from within another Spring MVC application using RestTemplate. It successfully makes the call to the api, but the foo and bar fields of TheThing object end up being null once it reaches the rest controller

from TheThingController in the MVC app

```<code>@RequestMapping(path = "/", method = RequestMethod.POST)
public String save(Model model) {
    TheThing theThing = new TheThing();
    theThing.setFoo("foo");
    theThing.setBar("bar");

    RestTemplate restTemplate = new RestTemplate();
    TheThing savedThing = restTemplate.postForObject("http://localhost:8090/theThing", theThing, TheThing.class);
    return "thingForm";
}
</code>```

TheThingRestController

```<code>@RestController
public class TheThingRestController {

    @Autowired
    private TheThingMapper theThingMapper;

    @RequestMapping(path = "/theThing", method = RequestMethod.POST)
    public void create(TheThing theThing) {
        theThingMapper.createTheThing(theThing); // theThing isn't null, but all of its fields are
    }
}
</code>```

Somehow the fields of TheThing object are getting lost in translation.

答: I figured it out. Just needed to Add the @RequestBody annotation to TheThing method parameter in the RestController

Body:
I am trying to save a domain object via my REST api from within another Spring MVC application using RestTemplate. It successfully makes the call to the api, but the foo and bar fields of TheThing object end up being null once it reaches the rest controller

from TheThingController in the MVC app

@RequestMapping(path = "/", method = RequestMethod.POST)
public String save(Model model) {
    TheThing theThing = new TheThing();
    theThing.setFoo("foo");
    theThing.setBar("bar");

    RestTemplate restTemplate = new RestTemplate();
    TheThing savedThing = restTemplate.postForObject("http://localhost:8090/theThing", theThing, TheThing.class);
    return "thingForm";
}

TheThingRestController

@RestController
public class TheThingRestController {

    @Autowired
    private TheThingMapper theThingMapper;

    @RequestMapping(path = "/theThing", method = RequestMethod.POST)
    public void create(TheThing theThing) {
        theThingMapper.createTheThing(theThing); // theThing isn't null, but all of its fields are
    }
}

Somehow the fields of TheThing object are getting lost in translation.


问:
Signalr Calling Hub Method from Code Behind Ajax Call
I am running the stock signalr example and trying to modify the code and try something differnt. What I am wanting is on a front end button press to call an ajax call and from there call a hub method. When I do this I am not hitting my breakpoint in my hub method

Front end code change:

```<code>$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
$.ajax({

url: '/home/MyTest/',
type: "POST",
success: function () {
alert("done");
}, error: function (jqXHR, exception) {
alert("failed");
}

});
//chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
</code>```

In HomeController.cs

```<code>[HttpPost]
public void MyTest()
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.send("a","b");
}
</code>```

ChatHub.cs

```<code>public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}
</code>```

答:
The Hub method on the server doesn't get executed... What

var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.send("a","b");

is saying is : On every client that has an open/active connection to the Hub, I'm invoking a send function on the client. Not on the Hub on the server.

Body:
I am running the stock signalr example and trying to modify the code and try something differnt. What I am wanting is on a front end button press to call an ajax call and from there call a hub method. When I do this I am not hitting my breakpoint in my hub method

Front end code change:

$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
$.ajax({

url: '/home/MyTest/',
type: "POST",
success: function () {
alert("done");
}, error: function (jqXHR, exception) {
alert("failed");
}

});
//chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});

In HomeController.cs

[HttpPost]
public void MyTest()
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.send("a","b");
}

ChatHub.cs

public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}


问:
How to run a repetitive task in parallel in Spark instead of looping sequentially?
I have just started with Spark, and I know that non-functional way of sequential looping should be avoided for Spark to give me maximum performance.

I have a function makeData. I need to create a dataframe with the return value of this function by calling this function n times. Currently, my code looks like this:

var myNewDF = sqlContext.createDataFrame(sc.emptyRDD[Row],  minority_set.schema)

for ( i <- 1 to n ) {
  myNewDF = myNewDF.unionAll(sqlContext.createDataFrame(sc.parallelize(makeData()),minority_set.schema))
}
```

Is there a way of doing this where each iteration happens in parallel?
Here the problem is that n can be large, and this loop is taking a lot of time. Is there a more scala/spark friendly way of achieving the same thing?

答:
Since all your dataset is in memory already (guessing by sc.parallelize(makeData())) there's no point of using Spark SQL's unionAll to do the unioning which is also local (yet partitioned!).

I'd use Scala alone and only when you merged all the records I'd build a Dataset from it.

With that, I'd do something as follows:

```<code>val dataset = (1 to n).par.map { _ => makeData() }.reduce (_ ++ _)
val df = sc.parallelize(dataset, minority_set.schema)
</code>```

Body:
I have just started with Spark, and I know that non-functional way of sequential looping should be avoided for Spark to give me maximum performance.

I have a function makeData. I need to create a dataframe with the return value of this function by calling this function n times. Currently, my code looks like this:

var myNewDF = sqlContext.createDataFrame(sc.emptyRDD[Row],  minority_set.schema)

for ( i <- 1 to n ) {
  myNewDF = myNewDF.unionAll(sqlContext.createDataFrame(sc.parallelize(makeData()),minority_set.schema))
}

Is there a way of doing this where each iteration happens in parallel?
Here the problem is that n can be large, and this loop is taking a lot of time. Is there a more scala/spark friendly way of achieving the same thing?

Body:
Since all your dataset is in memory already (guessing by sc.parallelize(makeData())) there's no point of using Spark SQL's unionAll to do the unioning which is also local (yet partitioned!).

I'd use Scala alone and only when you merged all the records I'd build a Dataset from it.

With that, I'd do something as follows:

val dataset = (1 to n).par.map { _ => makeData() }.reduce (_ ++ _)
val df = sc.parallelize(dataset, minority_set.schema)


问:
how to join two arrays with linq
i am trying to combine two arrays with their relations but cant do exatly.
I have a Posts Table on my database and in Posts table there are questions and answers records. answers are related with question on "relatedPostId" column.
ex:

```<code>Posts (Table)
-------------
int Id (Field)
string Text (Field)
int RelatedPostId (Field)

question(record) : relatedPostId column is null
answer(record) : relatedPostId column is the value of question id
</code>```

My code is like below

```<code>    var posts = DBConnection.GetComments(_post.TopicId).ToArray().OrderByDescending(p => p.CreateDate);

    var questions = posts.Where(p => p.RelatedPostId == null);
    var answers = posts.Where(p => p.RelatedPostId != null);

    var result = from q in questions
                 join a in answers
                 on q.Id equals a.RelatedPostId
                 select  new { q = q, a = a };
</code>```

I want to list posts on a ListBox (lstCurrentTopic.Items.AddRange(...))
Also i want to display answers at the end of each question like

```<code>Question1
 -> Answer1 (relatedPostId is Qustion1.Id)
 -> Answer2 (relatedPostId is Qustion1.Id)
Qestion2
 ->Answer3 (relatedPostId is Qustion2.Id)
 ->Anser4 (relatedPostId is Qustion2.Id)
</code>```

how can i add with this order to listbox

答:
Something like this should work:

```<code>var result = from q in questions
             select new {
                q,
                answers =
                    from a in answers
                    where q.Id == a.RelatedPostId
                    select a;
              }
</code>```

The above approach would work great for something like LINQ to Entities, where it gets translated to a SQL statement that the database can optimize. Since you're using LINQ to objects, you'll get better performance if you take advantage of data structures:

```<code>var answersByQuestionId = answers.ToLookup(a => a.RelatedPostId);
var result = from q in questions
             select new {
                q,
                answers = answersByQuestionId.Contains(q.Id)
                          ? answersByQuestionId[q.Id].AsEnumerable()
                          : Enumerable.Empty<Answer>()
              }
</code>```

Title: how to join two arrays with linq

Body:
i am trying to combine two arrays with their relations but cant do exatly.
I have a Posts Table on my database and in Posts table there are questions and answers records. answers are related with question on "relatedPostId" column.
ex:

Posts (Table)
-------------
int Id (Field)
string Text (Field)
int RelatedPostId (Field)

question(record) : relatedPostId column is null
answer(record) : relatedPostId column is the value of question id

My code is like below

    var posts = DBConnection.GetComments(_post.TopicId).ToArray().OrderByDescending(p => p.CreateDate);

    var questions = posts.Where(p => p.RelatedPostId == null);
    var answers = posts.Where(p => p.RelatedPostId != null);

    var result = from q in questions
                 join a in answers
                 on q.Id equals a.RelatedPostId
                 select  new { q = q, a = a };

I want to list posts on a ListBox (lstCurrentTopic.Items.AddRange(...))
Also i want to display answers at the end of each question like

Question1
 -> Answer1 (relatedPostId is Qustion1.Id)
 -> Answer2 (relatedPostId is Qustion1.Id)
Qestion2
 ->Answer3 (relatedPostId is Qustion2.Id)
 ->Anser4 (relatedPostId is Qustion2.Id)

how can i add with this order to listbox

Body:
Something like this should work:

var result = from q in questions
             select new {
                q,
                answers =
                    from a in answers
                    where q.Id == a.RelatedPostId
                    select a;
              }

The above approach would work great for something like LINQ to Entities, where it gets translated to a SQL statement that the database can optimize. Since you're using LINQ to objects, you'll get better performance if you take advantage of data structures:

var answersByQuestionId = answers.ToLookup(a => a.RelatedPostId);
var result = from q in questions
             select new {
                q,
                answers = answersByQuestionId.Contains(q.Id)
                          ? answersByQuestionId[q.Id].AsEnumerable()
                          : Enumerable.Empty<Answer>()
              }


问:
Is it possible to set up Facebook webhook for new page posts using Graph API?
I am trying to build an application with Ruby on Rails that gets the most recent Facebook posts from a public page and displays them in a certain way.

Currently, I am planning to get the posts using the Koala gem and Graph API's get_connection

```<code>client = Koala::Facebook::API.new(oauth_token)
client.get_connection('someuser', 'posts',
                    {limit: @options[:max_items],
                      fields: ['message', 'id', 'from', 'type',
                                'picture', 'link', 'created_time', 'updated_time'
                        ]})
</code>```

However, I believe this would require me to update the feed manually be re-running this every X hours. It would be much more convenient if it was possible to setup a webhook that listens for a new post and updates it accordingly. I found the link below, but can't quite make sense of it/whether this possible or if there is a better way than I am currently doing it.

https://developers.facebook.com/docs/graph-api/webhooks

If it is possible, how might I achieve it, or is there another better way?

答:
There is two steps to achieve it, first you need suscribe your app to the webhook for pages you can do it with the Facebook app panel control or using Koala Real-time Updates (webhook references), then you need to add your app to the subscribed apps of the page. Here is the code that I use for these steps:

#subscribe app
   @updates = Koala::Facebook::RealtimeUpdates.new(app_id:
       facebook_app_id,secret: facebook_app_secret)
   @updates.subscribe("page", "feed", callback_url, verify_token)

#subscribe page
   api = Koala::Facebook::API.new(page["access_token"])
   api.graph_call("#{page["id"]}/subscribed_apps",{},"post",{})

If you don't know the page access_token see the
Koala wiki

Important: You need use the protocol "https" for the callback_url and the verify_token size can't be longer than 64

Body:
I am trying to build an application with Ruby on Rails that gets the most recent Facebook posts from a public page and displays them in a certain way.

Currently, I am planning to get the posts using the Koala gem and Graph API's get_connection

client = Koala::Facebook::API.new(oauth_token)
client.get_connection('someuser', 'posts',
                    {limit: @options[:max_items],
                      fields: ['message', 'id', 'from', 'type',
                                'picture', 'link', 'created_time', 'updated_time'
                        ]})

However, I believe this would require me to update the feed manually be re-running this every X hours. It would be much more convenient if it was possible to setup a webhook that listens for a new post and updates it accordingly. I found the link below, but can't quite make sense of it/whether this possible or if there is a better way than I am currently doing it.

https://developers.facebook.com/docs/graph-api/webhooks

If it is possible, how might I achieve it, or is there another better way?


问:
How to sort a vector using sort() in c++
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

```<code>//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);
</code>```

答:
```<code>std::sort(g1.begin(), g1.end());
</code>```

Should do the trick.

Alternatively, if you want to be able to switch out the vectorness of g1 with, say, a plain array, without having to modify this code, or if this was in template code where you want to work with multiple container types, then the form

```<code>std::sort(std::begin(g1), std::end(g1));
</code>```

may hold more appeal.

In any case; Please, do read the documentation.

Body:
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);

Body:
std::sort(g1.begin(), g1.end());

Should do the trick.

Alternatively, if you want to be able to switch out the vectorness of g1 with, say, a plain array, without having to modify this code, or if this was in template code where you want to work with multiple container types, then the form

std::sort(std::begin(g1), std::end(g1));

may hold more appeal.

In any case; Please, do read the documentation.