问:
How to make optionally read-only fields in django forms?
I have a read-only field in a django form that I sometimes want to edit.

I only want the right user with the right permissions to edit the field.  In most cases the field is locked, but an admin could edit this.

Using the init function, I am able to make the field read-only or not, but not optionally read-only.  I also tried passing an optional argument to StudentForm.init but that turned much more difficult that I expected.

Is there a proper way to do accomplish this?

models.py

```<code> class Student():
   # is already assigned, but needs to be unique
   # only privelidged user should change.
   student_id = models.CharField(max_length=20, primary_key=True)
   last_name = models.CharField(max_length=30)
   first_name = models.CharField(max_length=30)
   # ... other fields ...
</code>```

forms.py

```<code> class StudentForm(forms.ModelForm):
   class Meta:
     model = Student
     fields = ('student_id', 'last_name', 'first_name',
     # ... other fields ...

   def __init__(self, *args, **kwargs):
       super(StudentForm, self).__init__(*args, **kwargs)
       instance = getattr(self, 'instance', None)
       if instance:
          self.fields['student_id'].widget.attrs['readonly'] = True
</code>```

views.py

```<code> def new_student_view(request):
   form = StudentForm()
   # Test for user privelige, and disable
   form.fields['student_id'].widget.attrs['readonly'] = False
   c = {'form':form}
   return render_to_response('app/edit_student.html', c, context_instance=RequestContext(request))
</code>```

答:
Is that what you are looking for? By modifying your code a little bit:

forms.py

```<code>class StudentForm(forms.ModelForm):

    READONLY_FIELDS = ('student_id', 'last_name')

    class Meta:
        model = Student
        fields = ('student_id', 'last_name', 'first_name')

    def __init__(self, readonly_form=False, *args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        if readonly_form:
            for field in self.READONLY_FIELDS:
                self.fields[field].widget.attrs['readonly'] = True
</code>```

views.py

```<code>def new_student_view(request):

    if request.user.is_staff:
        form = StudentForm()
    else:
        form = StudentForm(readonly_form=True)

    extra_context = {'form': form}
    return render_to_response('forms_cases/edit_student.html', extra_context, context_instance=RequestContext(request))
</code>```

So the thing is to check permissions on the views level, and then to pass argument to your form when it is initialized. Now if staff/admin is logged in, fields will be writeable. If not, only fields from class constant will be changed to read only.

Body:
I have a read-only field in a django form that I sometimes want to edit.

I only want the right user with the right permissions to edit the field.  In most cases the field is locked, but an admin could edit this.

Using the init function, I am able to make the field read-only or not, but not optionally read-only.  I also tried passing an optional argument to StudentForm.init but that turned much more difficult that I expected.

Is there a proper way to do accomplish this?

models.py

 class Student():
   # is already assigned, but needs to be unique
   # only privelidged user should change.
   student_id = models.CharField(max_length=20, primary_key=True)
   last_name = models.CharField(max_length=30)
   first_name = models.CharField(max_length=30)
   # ... other fields ...

forms.py

 class StudentForm(forms.ModelForm):
   class Meta:
     model = Student
     fields = ('student_id', 'last_name', 'first_name',
     # ... other fields ...

   def __init__(self, *args, **kwargs):
       super(StudentForm, self).__init__(*args, **kwargs)
       instance = getattr(self, 'instance', None)
       if instance:
          self.fields['student_id'].widget.attrs['readonly'] = True

views.py

 def new_student_view(request):
   form = StudentForm()
   # Test for user privelige, and disable
   form.fields['student_id'].widget.attrs['readonly'] = False
   c = {'form':form}
   return render_to_response('app/edit_student.html', c, context_instance=RequestContext(request))

Body:
Is that what you are looking for? By modifying your code a little bit:

forms.py

class StudentForm(forms.ModelForm):

    READONLY_FIELDS = ('student_id', 'last_name')

    class Meta:
        model = Student
        fields = ('student_id', 'last_name', 'first_name')

    def __init__(self, readonly_form=False, *args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        if readonly_form:
            for field in self.READONLY_FIELDS:
                self.fields[field].widget.attrs['readonly'] = True

views.py

def new_student_view(request):

    if request.user.is_staff:
        form = StudentForm()
    else:
        form = StudentForm(readonly_form=True)

    extra_context = {'form': form}
    return render_to_response('forms_cases/edit_student.html', extra_context, context_instance=RequestContext(request))

So the thing is to check permissions on the views level, and then to pass argument to your form when it is initialized. Now if staff/admin is logged in, fields will be writeable. If not, only fields from class constant will be changed to read only.


来源: stackexchange

问:
Long-running operations in web-application
Web application operations are generally meant to be quick to avoid long wait times to users.  However, some operations the web application may perform may be computationally-intensive and take a fair bit of time.  What is the best practice in REST to deal with such operations that may be take several minutes yet require an immediate response to users?  Is it okay for the web application to take several minutes to return the response of the HTTP request, or is it better to return a 202 response, process in the background somewhere else, and then provide some form of notification to the user?   </p>

答:
Is it okay for the web application to take several minutes to return the response of the HTTP request

No.  Part of the problem with this approach is that if the server doesn't acknowledge the request in a timely fashion, the client won't know that it reached its intended destination.

is it better to return a 202 response, process in the background somewhere else, and then provide some form of notification to the user?

Yes.  That's exactly what 202 Accepted is designed for

The 202 response is intentionally noncommittal.  Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed.  The representation sent with this response ought to describe the request's current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled.

It can help, I think, to remember that we're talking about your integration domain; the client isn't talking to your app.  It's instead talking to your API, which pretends to be a web site that the client can integrate with.  So your client sends the request to the API, and the API responds with an accepted message accompanied by a bunch of links that will help the client continue with the protocol and eventually reach its goal.

ContentLicense: CC BY-SA 3.0


问:
Why is the concept of immutability is embraced in React and its ecosystem?
in ES6, there are additional ways to declare a variable such as let and const

A variable declared with const cannot be re-assigned or re-declared.

Why are there so many const declarations in React application and what are the distinctive benefits from using const over var and let?

答:
First answer by @Carcigenicate explains the usage of const correctly.
But const keyword alone is not sufficient to achieve immutability.
e.g. You can mutate a const array :

```<code>const a = [12,14,15];
a[0] = 13; // allowed. but mutate a value.
</code>```

To achieve immutability to object at property level, new JS provide using Object.freeze(), .assign() etc or you can also utilize new library like immutableJS (there are few more good one to check out).

About Immutability in React, React components are pure functions. They accept props and return view.
Pure functions are foundation of Functional Programming. They lead to all sort of benefits (enable composition, simple to comprehend the unit of code which is function, easy to test and many more). Pure function does not have any side effect. It must not modify argument object also, and treat it as immutable.

DOM created by React components forms virtual DOM, and detects the data change called via setState only. On call of setState, it reacts and trigger its real DOM update algorithm. If a developer updates props, this won't happen. This post explain this: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html

React encourages one way data flow, Updated State flow down from top to bottom as props, and reaction to user action flow up as method call. One way data flow make it easy to debug/understand the react apps.

I created following diagram to understand the example illustrated in official React docs

Body:
First answer by @Carcigenicate explains the usage of const correctly.
But const keyword alone is not sufficient to achieve immutability.
e.g. You can mutate a const array :

const a = [12,14,15];
a[0] = 13; // allowed. but mutate a value.

To achieve immutability to object at property level, new JS provide using Object.freeze(), .assign() etc or you can also utilize new library like immutableJS (there are few more good one to check out).

About Immutability in React, React components are pure functions. They accept props and return view.
Pure functions are foundation of Functional Programming. They lead to all sort of benefits (enable composition, simple to comprehend the unit of code which is function, easy to test and many more). Pure function does not have any side effect. It must not modify argument object also, and treat it as immutable.

DOM created by React components forms virtual DOM, and detects the data change called via setState only. On call of setState, it reacts and trigger its real DOM update algorithm. If a developer updates props, this won't happen. This post explain this: http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html

React encourages one way data flow, Updated State flow down from top to bottom as props, and reaction to user action flow up as method call. One way data flow make it easy to debug/understand the react apps.

I created following diagram to understand the example illustrated in official React docs

ContentLicense: CC BY-SA 4.0


问:
How to place a button next to a text?
Hey guys I need to place these two buttons next to a name. How can I do that? They always appear below the word.

<ion-list>
    <ion-item *ngFor="let service of services">

{{service.name}}

        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>```

答:
Here is what you need:

```<code><h2 style="display: inline;">{{service.name}}</h2>
</code>```

<ion-list>
    <ion-item *ngFor="let service of services">

{{service.name}}

        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>```

Title: How to place a button next to a text?

Body:
Here is what you need:

<h2 style="display: inline;">{{service.name}}</h2>

<ion-list>
    <ion-item *ngFor="let service of services">
        <h2 style="display:inline;">{{service.name}}</h2>
        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>


问:
Is python is a good choice as language used to implementing my first 3D model?
I am C/C  /Java programmer, but lately I have started learn Python.

Moreover I have 3D Graphics on my studies. I have to create 3D model of my apartment, with dynamic camera. I am wondering if this is a good idea to merge this two issues, by writing this 3D model in python.

However as I said, I am a python beginner, so I don't know possibilities, which python can give me in this area. Which libraries/engine will be the best for a start?

答:
There are a lot of options and libraries regardless of the language you choose.  But if you need a quick and dirty model you might want to check out VPython, which is python plus a simple 3D library (http://vpython.org/index.html.  There are video tutorials at: http://www.youtube.com/vpythonvideos

The programming part would likely be very easy using VPython.

The hard part is creating the object for your apartment, which you might have to do by hand, with hand coding of the coordinates to define each object.  The VPython site has a utility for importing .stl files, and many 3D programs, e.g., Blender, will export .stl files.  (I've never used this, so I can't speak to how well it works).

If you just need to model the walls, floor, and ceiling, and maybe a simple object or two, it wouldn't be hard to hand-code the coordinates.  Sketch it out on graph paper and make notes of the z axis values.

ContentLicense: CC BY-SA 2.5


问:
How to use indirect formula to show value AND formatting?
I have attached the example file just in case my explanation is not clear.
Excel Case 01.xlsx

So everyday I need to e-mail to my customers their daily delivery order based on their request and contract. Usually, they only order what they requested and leave out their required take of daily order.
So, I usually mark the "forced" order using orange color.

Each file is based on each month. And each sheet is based on each day so I have July file with 01,02,03 etc as sheet name. Each sheet has company and products details and the amount kgs of their order.

Each day I have to email them the "forced" order only to notify them what's coming to them.

Now, I have separate sheet for e-mail like this:
Excel Case 01 - E-mail.jpeg

My formula for cell D6:D10 is:

```<code>{=IFERROR(INDEX(INDIRECT("'"&$K$4&"'!$A$2:$H$6"),(MATCH(1,(INDIRECT("'"&$K$4&"'!$A$2:$A$6")=$B6)*(INDIRECT("'"&$K$4&"'!$B$2:$B$6")=$C6),0)),$K$7),0)}
</code>```

The problem is that the orange color is not shown in that column and I need the color so I can use the filter by color option. I also want to keep the "Sheet Name" function so that I only have to change the sheet name to get the datas that I want since I will have up to 31 sheets.

Is there a way to keep the indirect formula to show not only values but also the format of the referred cell?

Thought of using paste link VBA but when I searched for the codes, it seems that I only find codes that refer to specific cells.
But I don't mind using VBA if I can still use the "Sheet Name" function.

Thank you in advance.

答:
Add a VBA function called Function SumByColor(CellColor As Range, SumRange As Range, Condition1 As Range, Condition2 As Range, ColOffset As Integer) as shown below

change the formula in D6 to =SumByColor($K$9,OFFSET(INDIRECT("'"&$K$4&"'!$A$2"),0,$K$7,6,1),B6,C6,$K$7)
and copy down

amend the lookup table on the RHS slightly (subract 1 from each value) to make everything tidier

change the cell color of K9 to match your 'forced' orange

This worked in a modified version of your file I edited.

```<code>Function SumByColor(CellColor As Range, SumRange As Range, Condition1 As Range, Condition2 As Range, ColOffset As Integer)
Application.Volatile
Dim ICol As Integer
Dim TCell As Range

ICol = CellColor.Interior.ColorIndex

For Each TCell In SumRange
    If ICol = TCell.Interior.ColorIndex And TCell.Offset(0, -ColOffset).Value = Condition1.Value And TCell.Offset(0, -ColOffset + 1).Value = Condition2.Value Then
        SumByColor = SumByColor + TCell.Value
    End If
Next TCell
End Function
</code>```

BTW:  I just modified the SumByColor function I found somewhere else so I can't claim credit for its basic operation.

Body:
I have attached the example file just in case my explanation is not clear.
Excel Case 01.xlsx

So everyday I need to e-mail to my customers their daily delivery order based on their request and contract. Usually, they only order what they requested and leave out their required take of daily order.
So, I usually mark the "forced" order using orange color.

Each file is based on each month. And each sheet is based on each day so I have July file with 01,02,03 etc as sheet name. Each sheet has company and products details and the amount kgs of their order.

Each day I have to email them the "forced" order only to notify them what's coming to them.

Now, I have separate sheet for e-mail like this:
Excel Case 01 - E-mail.jpeg

My formula for cell D6:D10 is:

{=IFERROR(INDEX(INDIRECT("'"&$K$4&"'!$A$2:$H$6"),(MATCH(1,(INDIRECT("'"&$K$4&"'!$A$2:$A$6")=$B6)*(INDIRECT("'"&$K$4&"'!$B$2:$B$6")=$C6),0)),$K$7),0)}

The problem is that the orange color is not shown in that column and I need the color so I can use the filter by color option. I also want to keep the "Sheet Name" function so that I only have to change the sheet name to get the datas that I want since I will have up to 31 sheets.

Is there a way to keep the indirect formula to show not only values but also the format of the referred cell?

Thought of using paste link VBA but when I searched for the codes, it seems that I only find codes that refer to specific cells.
But I don't mind using VBA if I can still use the "Sheet Name" function.

Thank you in advance.

Body:
Add a VBA function called Function SumByColor(CellColor As Range, SumRange As Range, Condition1 As Range, Condition2 As Range, ColOffset As Integer) as shown below

change the formula in D6 to =SumByColor($K$9,OFFSET(INDIRECT("'"&$K$4&"'!$A$2"),0,$K$7,6,1),B6,C6,$K$7)
and copy down

amend the lookup table on the RHS slightly (subract 1 from each value) to make everything tidier

change the cell color of K9 to match your 'forced' orange

This worked in a modified version of your file I edited.

Function SumByColor(CellColor As Range, SumRange As Range, Condition1 As Range, Condition2 As Range, ColOffset As Integer)
Application.Volatile
Dim ICol As Integer
Dim TCell As Range

ICol = CellColor.Interior.ColorIndex

For Each TCell In SumRange
    If ICol = TCell.Interior.ColorIndex And TCell.Offset(0, -ColOffset).Value = Condition1.Value And TCell.Offset(0, -ColOffset + 1).Value = Condition2.Value Then
        SumByColor = SumByColor + TCell.Value
    End If
Next TCell
End Function

BTW:  I just modified the SumByColor function I found somewhere else so I can't claim credit for its basic operation.


问:
Synchronized section in async map
I have a big IO function that will continuesly load data from a folder, perform pure calculations on the data, and write it back.

I am running this function over multiple folders in parallel using

```<code>mapConcurrently_ iofun folderList
</code>```

from http://hackage.haskell.org/package/async-2.1.1.1/docs/Control-Concurrent-Async.html#v%3amapConcurrently

This works perfecty... but a little bit too well. Now even the character output of the putStrLn calls are async, which leads to an unreadable console log.

Is there a way to make IO Actions synchronized or even better a synchronized version of putStrLn?

答:
The way you coordinate threads is via MVars or TVars if you want to use STM. You can read all about them in "Parallel and Concurrent Haskell". You could do something like:

```<code>do mutex <- newMVar ()
   let putStrLn' = withMVar mutex . const . putStrLn
   mapConcurrently_ (iofunPrintingWith putStrLn') folderList
</code>```

Title: Synchronized section in async map

Body:
I have a big IO function that will continuesly load data from a folder, perform pure calculations on the data, and write it back.

I am running this function over multiple folders in parallel using

mapConcurrently_ iofun folderList

from http://hackage.haskell.org/package/async-2.1.1.1/docs/Control-Concurrent-Async.html#v%3amapConcurrently

This works perfecty... but a little bit too well. Now even the character output of the putStrLn calls are async, which leads to an unreadable console log.

Is there a way to make IO Actions synchronized or even better a synchronized version of putStrLn?

Body:
The way you coordinate threads is via MVars or TVars if you want to use STM. You can read all about them in "Parallel and Concurrent Haskell". You could do something like:

do mutex <- newMVar ()
   let putStrLn' = withMVar mutex . const . putStrLn
   mapConcurrently_ (iofunPrintingWith putStrLn') folderList


问:
how to use NodeJS pop up a alert window in browser
I'm totally new to Javascript and I'm wondering how to use node js to pop up a alert window in browser, after sever(Nodejs) received post message from front end?
Do I need to use Ajax?</p>

答:
"after sever(Nodejs) received post message from front end?" show a pop up in the browser. This can not be done. I assume you want to show a popup in if the post request is success. Because you mention about Ajax, This is how it is done.

in your post router definition in the server do it as follows

```<code>router.post('/path', function(req, res){
   //do something
   res.jsonp({success : true})
});
</code>```

something like this. finally you want to send something form the server to the client. after in the client side javascript file send the post request as follows.

```<code>$.ajax({
    url:"/url/is/here",
    method: "POST",
    data : {
        data : "what you want to send",
        put : "them here"
    },
    cache : false,
    success : function (data) {
        // data is the object that you send form the server by
        // res.jsonp();
        // here data = {success : true}
        // validate it
        if(data['success']){
            alert("message you want to show");
        }
    },
    error : function () {
        // some error handling part
        alert("Oops! Something went wrong.");
    }
});
</code>```

Body:
"after sever(Nodejs) received post message from front end?" show a pop up in the browser. This can not be done. I assume you want to show a popup in if the post request is success. Because you mention about Ajax, This is how it is done.

in your post router definition in the server do it as follows

router.post('/path', function(req, res){
   //do something
   res.jsonp({success : true})
});

something like this. finally you want to send something form the server to the client. after in the client side javascript file send the post request as follows.

$.ajax({
    url:"/url/is/here",
    method: "POST",
    data : {
        data : "what you want to send",
        put : "them here"
    },
    cache : false,
    success : function (data) {
        // data is the object that you send form the server by
        // res.jsonp();
        // here data = {success : true}
        // validate it
        if(data['success']){
            alert("message you want to show");
        }
    },
    error : function () {
        // some error handling part
        alert("Oops! Something went wrong.");
    }
});


问:
X close button only using css
How to make a cross (X) only in CSS3, to use as a close button?

I've been searching for a long time, and cannot found how....
When I look at source code on a website using it, there's always something weird which makes the code I take unusable.

The X button I want: http://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/

When you click an image, this is the cross on the right:

I think this would be great if somebody can post a simple universal CSS code to make a simple X cross in CSS3.

答:
You can use svg.

<svg viewPort="0 0 12 12" version="1.1"
     xmlns="http://www.w3.org/2000/svg">
    <line x1="1" y1="11"
          x2="11" y2="1"
          stroke="black"
          stroke-width="2"/>
    <line x1="1" y1="1"
          x2="11" y2="11"
          stroke="black"
          stroke-width="2"/>
</svg>```

Title: X close button only using css


问:
Firebase Database Unity differentiating between old and new data
I am building a chat engine using firebase in unity. I want to differentiate between the existing data and all the new data that gets added into the database. There is method once in web sdk of firebase which helps in differentiating between old and new data, is anyone aware if we have something similar on unity

答:
There is no direct way to do this, one way that is a workaround is to add a timestamp value in all the entries maintained in the database and each time one subscribes for the new data we make use of the OrderByValue|OrderByKey and StartAt to do the same.

In the beginning value for StartAt will be 0 but post that whenever a child gets added we can update the StartAt value to that so that the next time client subscribes for the childAdded, it will only receive data post the last child.


问:
How to extract all text under the same tag using XPath?
```<code><span rel="v:addr">
<span property="v:region">
  <a href="https://tabelog.com/en/tokyo/">
    123
  </a>
</span>
<span property="v:locality">
  <a href="https://tabelog.com/en/tokyo/A1317/A131710/rstLst/">
    456
  </a>
    <a href="https://tabelog.com/en/rstLst/">
      789
    </a>
  10
</span>
<span property="v:street-address">

</span>
</span>
</code>```

I want to extract the text inside the span tag without any space and make it as a one single string at the end.

I want this result:

```<code>12345678910
</code>```

This is my code below:

```<code>'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())
</code>```

答:
You can get all spans by //span/span. And get text in each span use text_content(). And substitute all whitespace characters use regex.

```<code>import re
from lxml import html

tree = html.fromstring(html_source)

span = tree.xpath("//span/span", smart_strings=0)

text = ''.join([re.sub(r"\s+", '', item.text_content()) for item in span])
</code>```

Body:
    123

    456

      789

  10

I want to extract the text inside the span tag without any space and make it as a one single string at the end.

I want this result:

12345678910

This is my code below:

'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())

Body:
You can get all spans by //span/span. And get text in each span use text_content(). And substitute all whitespace characters use regex.

import re
from lxml import html

tree = html.fromstring(html_source)

span = tree.xpath("//span/span", smart_strings=0)

text = ''.join([re.sub(r"\s+", '', item.text_content()) for item in span])


答:
h2 is a block tag, which means it always tries to take up its own line. You can circumvent this by overriding its display style.

<ion-list>
    <ion-item *ngFor="let service of services">

{{service.name}}

        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>```
</div>
</div>
</p>

<p>But that's a very ad hoc solution. You really want to think, stylistically, about <em>why</em> you want it on the same line. Because using <code>h2</code> as an inline tag is akin to telling the HTML engine "I want a header, but I don't want it to be a header". Perhaps consider setting up some text in a <code>span</code> and using CSS to make it bigger, if you're just going for enlarged text.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-list>
    <ion-item *ngFor="let service of services">
        <span style="font-size:1.5em;font-weight:bold;">{{service.name}}</span>
        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list></code>```

That gives you basically the same visual effect, but now you're not fighting against HTML to get it.

Title: How to place a button next to a text?

Body:
Hey guys I need to place these two buttons next to a name. How can I do that? They always appear below the word.

<ion-list>
    <ion-item *ngFor="let service of services">

{{service.name}}

        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>

Body:
h2 is a block tag, which means it always tries to take up its own line. You can circumvent this by overriding its display style.

<ion-list>
    <ion-item *ngFor="let service of services">
        <h2 style="display:inline;">{{service.name}}</h2>
        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>

But that's a very ad hoc solution. You really want to think, stylistically, about why you want it on the same line. Because using h2 as an inline tag is akin to telling the HTML engine "I want a header, but I don't want it to be a header". Perhaps consider setting up some text in a span and using CSS to make it bigger, if you're just going for enlarged text.

<ion-list>
    <ion-item *ngFor="let service of services">
        <span style="font-size:1.5em;font-weight:bold;">{{service.name}}</span>
        <button ion-fab mini color="danger"><ion-icon name="trash"></ion-icon></button>
        <button ion-fab mini color="secondary"><ion-icon name="create"></ion-icon></button>
    </ion-item>
</ion-list>

That gives you basically the same visual effect, but now you're not fighting against HTML to get it.


问:
Error using Android Design Support Library: attr backgroundTint not found
Trying to use the new Design Support Library in my project, AAPT throws the following error:

```<code>Description: Error: No resource found that matches the given name: attr 'backgroundTint'.
Resource:    /design/res/values/styles.xml
Location:    line 21
</code>```

This is the affected entry in styles.xml:

```<code><style name="Widget.Design.FloatingActionButton" parent="android:Widget">
    <item name="android:background">@drawable/fab_background</item>
    <item name="backgroundTint">?attr/colorAccent</item>
    <item name="fabSize">normal</item>
    <item name="elevation">@dimen/fab_elevation</item>
    <item name="pressedTranslationZ">@dimen/fab_translation_z_pressed</item>
    <item name="rippleColor">?attr/colorControlHighlight</item>
    <item name="borderWidth">@dimen/fab_border_width</item>
</style>
</code>```

I'm targeting my project to use SDK 21, with min SDK set to 17.

Edit: I have all SDK tools up to date.

答:
I wanted to add this as comment under third answer, but code was not formatted properly. I have to add both dependencies below to resolve the issue:</p>

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
</code>```

Body:
Trying to use the new Design Support Library in my project, AAPT throws the following error:

Description: Error: No resource found that matches the given name: attr 'backgroundTint'.
Resource:    /design/res/values/styles.xml
Location:    line 21

This is the affected entry in styles.xml:

I'm targeting my project to use SDK 21, with min SDK set to 17.

Edit: I have all SDK tools up to date.

Body:
I wanted to add this as comment under third answer, but code was not formatted properly. I have to add both dependencies below to resolve the issue:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'


问:
Browser maximum screen size
I am planning an advertisement display solution that might use a browser with multiple monitors. One of the questions is: is there a limit in the maximum screen size of a browser?</p>

答: No, there isn't. You're generally safe deeming 2,000 pixels or so to be the 99.999%-of-users limit, but there's no hard technological limit preventing some nutter from having a 100,000 pixel browser window displaying on a Times Square-style billboard or something.</p>

Title: Browser maximum screen size


问:
"java.lang.ArrayIndexOutOfBoundsException" with the right size checked
I'am very confused on why I am getting java.lang.ArrayIndexOutOfBoundsException in my code (using JavaFx), the following method saves the information entered on a local TXT file, splitting it in 3:

```<code>public void saveToFile() throws IOException {
    Path path = Paths.get(ticketFileName);      //C:\\temp\\ticketlog.txt
    BufferedWriter bw = Files.newBufferedWriter(path);
    try {
        Iterator<Ticket> iter = ticketList.iterator();
        while (iter.hasNext()) {
            Ticket item = iter.next();
            bw.write(String.format("%s->\t%s->\t%s", item.getCa(), item.getSummary(), item.getNotes()));
            bw.newLine();
        }

    } finally {
        if (bw != null) {
            bw.flush();
        }
    }
}
</code>```

on the initialize method the read method is:

```<code>Path path = Paths.get(ticketFileName);
try {
        // read file and put on the listview
        BufferedReader br = Files.newBufferedReader(path);   //C:\\temp\\ticketlog.txt
        while ((input = br.readLine()) != null) {
            String[] itemPieces = input.split("->\t");
                String ca = itemPieces[0];
                String summary = itemPieces[1];
                String notes = itemPieces[2];
                Ticket ticket = new Ticket(ca, summary, notes);
                ticketList.add(ticket);

        }

    } catch (IOException e) {

        e.printStackTrace();
    }
</code>```

and normally I have no problem with this, however, I have a Combobox which inserts text into the TextArea (which is the itemPieces[2]):

```<code>comboKb.getSelectionModel().selectedIndexProperty().addListener((v, oldValue, newValue) -> {
        txtKb.setText(comboKb.getValue().getLink());
        txtKb.setTooltip(new Tooltip(txtKb.getText()));

        txtaGetInfo.setText(txtaComplete + "\n\n\n" + comboKb.getValue().getLink());
    });
</code>```

Selecting any item it gives me the exception:

```<code>    javafx.fxml.LoadException:
/D:/Arquivo%20micro/alisson/FACUL/Facul/Orienta%c3%a7%c3%a3o%20a%20objetos/Eclipse/JavaFxTicketGenerator/bin/application/mainwindows.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at application.Main.start(Main.java:19)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 2
    at application.Controller.initialize(Controller.java:270)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    ... 17 more
</code>```

even through it gives me the exception, it looks normal on the Txt file.

If I delete the "\n" spaces it normally works, tried then to change the split case to anything else, still doesn't work.

This is driving me crazy, can someone please shed me some light?

Thanks a lot!

答:
You should test to make sure that this code

```<code>String[] itemPieces = input.split("->\t");
</code>```

actually returns an array of 3 or more Strings

```<code> if (itemPieces.length >= 3) {
   String ca = itemPieces[0];
   String summary = itemPieces[1];
   String notes = itemPieces[2];
   ...
 }
</code>```

Consider that you may have blanks lines or other invalid data

see bw.newLine();

Body:
I'am very confused on why I am getting java.lang.ArrayIndexOutOfBoundsException in my code (using JavaFx), the following method saves the information entered on a local TXT file, splitting it in 3:

public void saveToFile() throws IOException {
    Path path = Paths.get(ticketFileName);      //C:\\temp\\ticketlog.txt
    BufferedWriter bw = Files.newBufferedWriter(path);
    try {
        Iterator<Ticket> iter = ticketList.iterator();
        while (iter.hasNext()) {
            Ticket item = iter.next();
            bw.write(String.format("%s->\t%s->\t%s", item.getCa(), item.getSummary(), item.getNotes()));
            bw.newLine();
        }

    } finally {
        if (bw != null) {
            bw.flush();
        }
    }
}

on the initialize method the read method is:

Path path = Paths.get(ticketFileName);
try {
        // read file and put on the listview
        BufferedReader br = Files.newBufferedReader(path);   //C:\\temp\\ticketlog.txt
        while ((input = br.readLine()) != null) {
            String[] itemPieces = input.split("->\t");
                String ca = itemPieces[0];
                String summary = itemPieces[1];
                String notes = itemPieces[2];
                Ticket ticket = new Ticket(ca, summary, notes);
                ticketList.add(ticket);

        }

    } catch (IOException e) {

        e.printStackTrace();
    }

and normally I have no problem with this, however, I have a Combobox which inserts text into the TextArea (which is the itemPieces[2]):

comboKb.getSelectionModel().selectedIndexProperty().addListener((v, oldValue, newValue) -> {
        txtKb.setText(comboKb.getValue().getLink());
        txtKb.setTooltip(new Tooltip(txtKb.getText()));

        txtaGetInfo.setText(txtaComplete + "\n\n\n" + comboKb.getValue().getLink());
    });

Selecting any item it gives me the exception:

    javafx.fxml.LoadException:
/D:/Arquivo%20micro/alisson/FACUL/Facul/Orienta%c3%a7%c3%a3o%20a%20objetos/Eclipse/JavaFxTicketGenerator/bin/application/mainwindows.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at application.Main.start(Main.java:19)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 2
    at application.Controller.initialize(Controller.java:270)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
    ... 17 more

even through it gives me the exception, it looks normal on the Txt file.

If I delete the "\n" spaces it normally works, tried then to change the split case to anything else, still doesn't work.

This is driving me crazy, can someone please shed me some light?

Thanks a lot!

Body:
You should test to make sure that this code

String[] itemPieces = input.split("->\t");

actually returns an array of 3 or more Strings

 if (itemPieces.length >= 3) {
   String ca = itemPieces[0];
   String summary = itemPieces[1];
   String notes = itemPieces[2];
   ...
 }

Consider that you may have blanks lines or other invalid data

see bw.newLine();


问:
What is file scope in javascript
What is variable declared within file scope in javascript?

Is there anything file scope, considering multiple files are used in an app.

答:
In JavaScript, there are only 3 types of scope:

Global Scope (i.e. every variable/function defined outside functions in a file or multiple files)

Functional Scope (i.e. every variable/function defined within the function)

Closure Scope (i.e. code block/function having access to its surrounding lexical scope)

Title: What is file scope in javascript


问:
Approach to peek at next item (not just one char) in whitespace separated file using fstream
While trying to implement a program to process a series of white-space separated values from a file, I came across the problem that I can not peek at the output that the >> operator returns while leaving it in the ifstream to be the next thing returned.

The peek operator exists, but it only reads one character and my values are numbers of uncertain number of digits. Hence, it is not a solution to my particular problem. The >> operator however is more flexible, allowing for retrieval of the next "item", but does not give any peek functionality that leaves the file stream unchanged.

I did find another way to solve my particular problem, but I would appreciate if someone could tell me if there is a way to simulate peeking at the fstream contents. A bidirectional stream seems difficult to use and my impression was that it might require resetting a buffer, which I though might be time intensive (so I rejected that approach as I knew that was not something I knew how to easily implement and I did not know how efficient that is for processing long data sets (> 20,000 white-space separated entries).

This question relates to finding consecutive duplicates in a long stream of file contents, so that I can adjust my processing of entries accordingly. In my case, the question involves numbers, but it could just as easily apply to a white-space seperated list of words.

For example, file1 may contain 23 45 67 67 823 ...

In other words, before I process the first 67, I want to know how many I have in a row, so I can adjust accordingly. In my case, numbers are in ascending order.
The >> operator can retrieve the next value but then it is no longer in the input file stream (ifstream) reading from that file.

I have a solution, but want to expand my knowledge, and may decide if the solution is elegant enough to revise mine. Thanks.

答:
The easiest way to process your data would be to load them in memory first, and then perform all the processing. According to your examples, 20.000 numbers of 2-5 digits does not seem like a memory killer, and I would go for this.

If you cannot afford memory consumption, you can resort to managing the file offsets by yourself. If you want to read the files in an arbitrary fashion (fast-forward + normal reading), you should resort to manipulating the file offsets through seek*() functions.

Basically you save the current file offset, you perform all the reads you need, you restore the offset.

If you are absolutely requiring the best algorithm (performance) to find your next "\n" or next-number you might want to "minimize your maximum regret" while performing your seeks. Take a look at : http://datagenetics.com/blog/july22012/index.html


问:
How can I get Processing IDE to exit gracefully on runtime Java errors?
...other than wrapping everything in try..catch blocks?

I'm running Processing 3 on OSX Sierra. Every single time there's a silly runtime error, you get the spinning beachball and have to force-quit the applet (CMD+Opt+Esc). This is nuts: is there no more convenient way to have the Processing IDE handle these kinds of errors (eg: just shutdown the running applet and display the error message in the console log?)

Here's an example of such code:

```<code>import java.awt.Color;
import java.awt.color.*;

void setup(){
  Color A = new Color(255, 0, 0);
  ColorSpace CIELab = ColorSpace.getInstance(ColorSpace.TYPE_Lab);
  println(A);
  println(A.getComponents(CIELab, null));
  noLoop();
}
</code>```

It's just a test of some colour conversion, and (in case you didn't know), Java hasn't actually implemented ColorSpace.TYPE_Lab and it throws an "Unknown ColorSpace" error. Should be pretty harmless. No race condition here, nothing untoward, just an unimplemented abstract class. Shouldn't really warrant crashing the app and making me force-quit...

Maybe I'm just using the wrong mode, or there's a Preference I need to set?

Or does everyone who uses Processing play the CMD-Opt-Esc game all the time and just sucks it up?

答:
In situations such as these, you can usually just hit the "Stop" button on your Processing IDE, and you should be able to go on your way happily.

The big exception to this is if you're in fullScreen() mode, in which case you have no choice but to apply the Vulcan Death Grip and CMD+Opt+Esc.

Body:
...other than wrapping everything in try..catch blocks?

I'm running Processing 3 on OSX Sierra. Every single time there's a silly runtime error, you get the spinning beachball and have to force-quit the applet (CMD+Opt+Esc). This is nuts: is there no more convenient way to have the Processing IDE handle these kinds of errors (eg: just shutdown the running applet and display the error message in the console log?)

Here's an example of such code:

import java.awt.Color;
import java.awt.color.*;

void setup(){
  Color A = new Color(255, 0, 0);
  ColorSpace CIELab = ColorSpace.getInstance(ColorSpace.TYPE_Lab);
  println(A);
  println(A.getComponents(CIELab, null));
  noLoop();
}

It's just a test of some colour conversion, and (in case you didn't know), Java hasn't actually implemented ColorSpace.TYPE_Lab and it throws an "Unknown ColorSpace" error. Should be pretty harmless. No race condition here, nothing untoward, just an unimplemented abstract class. Shouldn't really warrant crashing the app and making me force-quit...

Maybe I'm just using the wrong mode, or there's a Preference I need to set?

Or does everyone who uses Processing play the CMD-Opt-Esc game all the time and just sucks it up?


问:
Git switch master and project branch
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

```<code>----------- master
    \______ project
</code>```

What I want:

```<code>-------------------- project (new master branch)
    \______ master (old)
</code>```

答:
You just need to exchanges the branch names for the two branches by below way:

```<code>git branch -m master project1   #change master branch name as project1
git branch -m project master    #change project branch name as master
git branch -m project1 project  #change project1 branch name as project
</code>```

Now your branch structure will looks like:

```<code>-------------------- project (new master branch)
    \______ master (old)
</code>```

Title: Git switch master and project branch

Body:
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

----------- master
    \______ project

What I want:

-------------------- project (new master branch)
    \______ master (old)

Body:
You just need to exchanges the branch names for the two branches by below way:

git branch -m master project1   #change master branch name as project1
git branch -m project master    #change project branch name as master
git branch -m project1 project  #change project1 branch name as project

Now your branch structure will looks like:

-------------------- project (new master branch)
    \______ master (old)


问:
How sum rows and get result permount mysql php
I want SUM my rows in table to SUM per month, example i
have table, like this :

```<code>no total_a total_b date
1    2        3    2017-06-12
2    1        2    2017-06-13
3    4        8    2017-07-04
</code>```

and i tried to use query like this

```<code>SELECT    SUM(total_a) as a, SUM(total_b) as b
FROM      table_visit
WHERE     YEAR(date) = '2017'
GROUP BY  MONTH(date)
</code>```

but the result just get for 1 month.

```<code>{ ["a"]=> string(1) "1" ["b"]=> string(1) "6" }
</code>```

how, if i want the result give result like this

```<code>{
      /*jan*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*feb*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*mar*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*apr*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*mei*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*jun*/ ["a"]=> string(1) "3" ["b"]=> string(1) "5"
      /*jul*/ ["a"]=> string(1) "4" ["b"]=> string(1) "8"
      /*aug*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*sep*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*okt*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*nov*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*des*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
}
</code>```

/*month*/ just note the result is permonth. can this done by use /*when case*/ query?

thanks

答:
The problem would seem to be that you don't have data for all months.  You can use left join to get the data . . . here is a way:

```<code>SELECT  m.mon, SUM(tv.total_a) as a, SUM(tv.total_b) as b
FROM (SELECT 1 as mon UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
      SELECT 5 as mon UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL
      SELECT 9 as mon UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
     ) m LEFT JOIN
     table_visit tv
     ON MONTH(tv.date) = m.mon
WHERE YEAR(date) = 2017
GROUP BY m.mon;
</code>```

Note that I included the month in the result set.  I just think that is a really good practice.

Also. YEAR() returns a number.  No need for single quotes around 2017.

Body:
I want SUM my rows in table to SUM per month, example i
have table, like this :

no total_a total_b date
1    2        3    2017-06-12
2    1        2    2017-06-13
3    4        8    2017-07-04

and i tried to use query like this

SELECT    SUM(total_a) as a, SUM(total_b) as b
FROM      table_visit
WHERE     YEAR(date) = '2017'
GROUP BY  MONTH(date)

but the result just get for 1 month.

{ ["a"]=> string(1) "1" ["b"]=> string(1) "6" }

how, if i want the result give result like this

{
      /*jan*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*feb*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*mar*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*apr*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*mei*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*jun*/ ["a"]=> string(1) "3" ["b"]=> string(1) "5"
      /*jul*/ ["a"]=> string(1) "4" ["b"]=> string(1) "8"
      /*aug*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*sep*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*okt*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*nov*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
      /*des*/ ["a"]=> string(1) "0" ["b"]=> string(1) "0"
}

/*month*/ just note the result is permonth. can this done by use /*when case*/ query?

thanks

Body:
The problem would seem to be that you don't have data for all months.  You can use left join to get the data . . . here is a way:

SELECT  m.mon, SUM(tv.total_a) as a, SUM(tv.total_b) as b
FROM (SELECT 1 as mon UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
      SELECT 5 as mon UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL
      SELECT 9 as mon UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
     ) m LEFT JOIN
     table_visit tv
     ON MONTH(tv.date) = m.mon
WHERE YEAR(date) = 2017
GROUP BY m.mon;

Note that I included the month in the result set.  I just think that is a really good practice.

Also. YEAR() returns a number.  No need for single quotes around 2017.


问:
R plotly add_trace to a chart with color groups
For data set mtcars, I want to plot a scatter plot (wt v.s. mpg) with am as the color group.

Then I want to add a trace from (2,15) to (3,25).

```<code>mtcars$am = as.character(mtcars$am)
plot_ly(mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
    add_trace(x = c(2,15), y = c(3,25), mode="lines")
</code>```

The code without add_trace works fine. How to add this line?

答:
Option 1:

```<code>library(plotly)
library(ggplot2)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y =  mpg, col = am)) + geom_segment(aes(x = 2, y = 3, xend = 15, yend = 25))
ggplotly(p)
</code>```

Option 2:

```<code>plot_ly() %>%
add_trace(data = mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
add_trace( x = c(2,15, rep(NA,nrow(mtcars))), y = c(3,25,rep(NA,nrow(mtcars))), mode="lines")
</code>```

Body:
For data set mtcars, I want to plot a scatter plot (wt v.s. mpg) with am as the color group.

Then I want to add a trace from (2,15) to (3,25).

mtcars$am = as.character(mtcars$am)
plot_ly(mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
    add_trace(x = c(2,15), y = c(3,25), mode="lines")

The code without add_trace works fine. How to add this line?

Body:
Option 1:

library(plotly)
library(ggplot2)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y =  mpg, col = am)) + geom_segment(aes(x = 2, y = 3, xend = 15, yend = 25))
ggplotly(p)

Option 2:

plot_ly() %>%
add_trace(data = mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
add_trace( x = c(2,15, rep(NA,nrow(mtcars))), y = c(3,25,rep(NA,nrow(mtcars))), mode="lines")


问:
HTML POST method correction
```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function test(){
 var name = document.getElementById('name').value;
 var snumber = document.getElementById('snumber').value;
 document.write("<h2>name="+name+"");
 document.write("&snumber="+snumber+"</h2><br />");
}
</script>
</head>
<body>
<form method = "post">
<h2>Example of sending data using POST</h2>
Name :
<input type="text" id="name"><br/>
Student number:
<input type="text" id="snumber"><br/><br/>
<input type="button" value="submit" onclick="test();">
</body>
</html>
</code>```

I wrote a HTML code, I have to use HTML post method to send the data about name and number!! When I send this data, I can see properly but I cannot see POST message on my linux. When I use get method, I can see the GET message form linux like this.

Is my code not POST method? or how can I change it to the POST method without changing any outputs?

Thank you so much for your attention.!!

答:
While the method attribute denotes whether a request will either be GET or POST, a form typically also requires an action attribute in order to be submitted. The action attribute can only be omitted in an HTML5 <!DOCTYPE> where the form is also intended to submit to the same page.

Your form was crashing for a few reasons:

because you missed the closing </form> tag, causing invalid HTML

your inputs were missing a name attribute, so their data wouldn't be sent through

you had no button with a type of submit

A form is typically submitted with an <input type='submit'>. Instead of this, you were attempting to hook a custom submit button up to a JavaScript function. <input type='submit'> automatically creates a button for you, which can be styled with the CSS selector input[type=submit].

Note that while your JavaScript is wholly unnecessary, document.write() is vulnerable to XSS injection, and should definitely not be used.

I've corrected your missing </form> tag, added the missing name attributes and added the missing form submission to the following example:

```<code><!DOCTYPE html>
<html>
  <form action="target.php" method="post">
    <h2>Example of sending data using POST</h2>
    Name :
    <input type="text" id="name" name="name"><br/> Student number:
    <input type="text" id="snumber" name="snumber"><br/><br/>
    <input type="submit">
  </form>
</html>
</code>```

The data will get submitted with POST to the location specified in the form's action. In my example, that's target.php. If you want the form to post to itself, you can use action="#", or simply omit the action attribute as you're using HTML5.

Obviously, you can point the form to any back-end script. Assuming you use PHP though, in your file target.php, you can output the data with:

```<code>echo $_POST['name'] . "<br />" . PHP_EOL;
echo $_POST['snumber'] . PHP_EOL;
</code>```

For further information on forms, check out the basics at MSDN.

Hope this helps! :)

Title: HTML POST method correction

Body:
<!DOCTYPE html>

<meta charset="utf-8">

<form method = "post">

Example of sending data using POST

Name :
<input type="text" id="name">

Student number:
<input type="text" id="snumber">

<input type="button" value="submit" onclick="test();">

I wrote a HTML code, I have to use HTML post method to send the data about name and number!! When I send this data, I can see properly but I cannot see POST message on my linux. When I use get method, I can see the GET message form linux like this.

Is my code not POST method? or how can I change it to the POST method without changing any outputs?

Thank you so much for your attention.!!

Body:
While the method attribute denotes whether a request will either be GET or POST, a form typically also requires an action attribute in order to be submitted. The action attribute can only be omitted in an HTML5 <!DOCTYPE> where the form is also intended to submit to the same page.

Your form was crashing for a few reasons:

because you missed the closing </form> tag, causing invalid HTML

your inputs were missing a name attribute, so their data wouldn't be sent through

you had no button with a type of submit

A form is typically submitted with an <input type='submit'>. Instead of this, you were attempting to hook a custom submit button up to a JavaScript function. <input type='submit'> automatically creates a button for you, which can be styled with the CSS selector input[type=submit].

Note that while your JavaScript is wholly unnecessary, document.write() is vulnerable to XSS injection, and should definitely not be used.

I've corrected your missing </form> tag, added the missing name attributes and added the missing form submission to the following example:

<!DOCTYPE html>
<html>
  <form action="target.php" method="post">
    <h2>Example of sending data using POST</h2>
    Name :
    <input type="text" id="name" name="name"><br/> Student number:
    <input type="text" id="snumber" name="snumber"><br/><br/>
    <input type="submit">
  </form>
</html>

The data will get submitted with POST to the location specified in the form's action. In my example, that's target.php. If you want the form to post to itself, you can use action="#", or simply omit the action attribute as you're using HTML5.

Obviously, you can point the form to any back-end script. Assuming you use PHP though, in your file target.php, you can output the data with:

echo $_POST['name'] . "<br />" . PHP_EOL;
echo $_POST['snumber'] . PHP_EOL;

For further information on forms, check out the basics at MSDN.

Hope this helps! :)


问:
How to not skew data after a reduceByKey?
The result of our reduceByKey operation results in an RDD that is quite skewed, with lots of data in one or two partitions.  To increase the parallelism of the processing after the reduceByKey we do a repartition, which forces a shuffle.

```<code>rdd.reduceByKey(_+_).repartition(64)
</code>```

I know that it is possible to pass a Partitioner into the reduceByKey opertion.  But (other than creating a Custom one) I think the options are the HashPartioner and the RangePartitioner.  And I think both of these will result in the data being skewed after they partition, since the keys are quite unique.

Is it possible to shuffle the output RDD in a reduceByKey evenly, without the additional repartition call?

答:
I am assuming you are having keys after reduceByKey clustering in some regions. For example, 1,2,3,4,5, 45,46,47,48,49, 356, 789.

So you will have skew data when you rangePartitioner. But HashPartitioner depends on the hash function used to calculate the hash of the keys.

(Scala RDD may use hashCode, DataSets uses MurmurHash 3, PySpark, portable_hash).

Now if the default hashPartitioner is also giving you data skew, then you will have to use Custom Partitioner and apply hash using some good hash partitioner that will surely generate a sparse hash, e.g. md5.

To implement custom Partitioner in spark you will have to extend Partitioner and implement 3 methods:

numPartitions

equals

getPartition

In getPartition method you can calculate md5 hash of the key and distribute them according to numPartitions parameter.

You can also check Zero323's answer for more on this.

Body:
The result of our reduceByKey operation results in an RDD that is quite skewed, with lots of data in one or two partitions.  To increase the parallelism of the processing after the reduceByKey we do a repartition, which forces a shuffle.

rdd.reduceByKey(_+_).repartition(64)

I know that it is possible to pass a Partitioner into the reduceByKey opertion.  But (other than creating a Custom one) I think the options are the HashPartioner and the RangePartitioner.  And I think both of these will result in the data being skewed after they partition, since the keys are quite unique.

Is it possible to shuffle the output RDD in a reduceByKey evenly, without the additional repartition call?


问:
Can I develop the regular chrome-optimized websites in Windows 10 Embedded OS?
I'm currently developing a web-based POS, and I'm looking to purchase a touchscreen POS machine which comes with Windows 10 Embedded.

I have read somewhere that it cannot just download any software, Chrome included, so I fear that even if I optimize for IE instead, it might not also be able to use the usual technologies utilized in most websites such as: SQLite, Node.JS, Sockets.IO, etc.

Anyone who had tried using Win 10 Embedded before, is it the same as your regular PC Windows?

Thanks

答:
Currently, there is no browser(Chrome,IE...) included in Windows 10 IoT Core and also you can't install it.

You may need develop a UWP-style browser by yourself. If you like do this you can reference IoT Browser Sample.

As for your user case(POS machine), Windows 10 IoT Enterprise is the best choice because:

Windows 10 IoT Enterprise brings the capabilities of Windows 10
  Enterprise to a wide range of industry devices across retail,
  manufacturing, health, finance and other industries. Windows 10 IoT
  Enterprise supports both Universal Windows apps and Classic Windows
  applications...

For more information about different Windows 10 IoT Editions you can reference  here.


Title: Python: How to bin a set of data by a repeated value in one column

Body:
Say, I have a numpy array like this:

import numpy as np

x= np.array(
    [[100, 14, 12, 15],
    [100, 21, 16, 11],
    [100, 19, 10, 13],
    [160, 24, 15, 12],
    [160, 43, 12, 65],
    [160, 17, 53, 23],
    [300, 15, 17, 11],
    [300, 66, 23, 12],
    [300, 44, 70, 19]])

The original array is much bigger, so my question is if there's a way to bin or group rows based on the value on column 1?
for example:

{'100': [[14, 12, 15], [21, 16, 11], [19, 10, 13]],
,'160': [[24, 15, 12], [43, 12, 65], [17, 53, 23]],
,'300': [[15, 17, 11], [66, 23, 12], [44, 70, 19]]}

Body:
You can group your data with the collections.defaultdict and a loop.

from collections import defaultdict

data = defaultdict(list)
for l in x:
    data[l[0]].append(l[1:])

print(dict(data))

Output:

{100: [[14, 12, 15], [21, 16, 11], [19, 10, 13]],
 160: [[24, 15, 12], [43, 12, 65], [17, 53, 23]],
 300: [[15, 17, 11], [66, 23, 12], [44, 70, 19]]}


问:
Filter words in a sentence that begin with a certain range of letters
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

```<code>famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""
</code>```

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

```<code>Wheresoever you go, go with all your heart
</code>```

Sample output:

```<code>WHERESOEVER
YOU
WITH
YOUR
HEART
</code>```

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()
```

答:
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.

The two issues you've highlighted is that you are comparing the whole word instead of just the first character.

Simply change:

```<code>if word > "g":
</code>```

To:

```<code>if word and word[0] > "g":
</code>```

And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:

```<code>if word:
     print(word)
</code>```

You may note the output is all uppercase, so  .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:

```<code>famous_quote = input("Enter a one sentence quote: ")
...
    if word and word[0].lower() > "g":
</code>```

Note: You can simplify your else: condition:

```<code>else:
    if word and word[0] > "g":
        print(word)
    word = ""
</code>```

Body:
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

Wheresoever you go, go with all your heart

Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()

Body:
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.

The two issues you've highlighted is that you are comparing the whole word instead of just the first character.

Simply change:

if word > "g":

To:

if word and word[0] > "g":

And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:

if word:
     print(word)

You may note the output is all uppercase, so  .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:

famous_quote = input("Enter a one sentence quote: ")
...
    if word and word[0].lower() > "g":

Note: You can simplify your else: condition:

else:
    if word and word[0] > "g":
        print(word)
    word = ""


问:
Select Clause using System.Linq.Dynamic is returning "'(' expected" fault
I'm trying to use linq dynamic to create a selec that returns me a specific object. But I'm always getting the same error message: '(' expected

My select code:

```<code>var resultCollection = manyPartEntireCollection
                .Select("new MyNamespace.OneToManyViewModel(@0 as OnePartId, Id as ManyPartId, Name as Name, @1.Contains(outerIt.Id) as Enable)", onePartId, manyParIds)
                .Cast<OneToManyViewModel>()
                .ToList()
                ;
</code>```

Thanks!

答:
The main question from your example is "what is outerIt?" (@1.Contains(outerIt.Id)) This looks to be just a piece of a larger query. You may want to post up the complete set of expressions.

Based on an assumption of what it looks like you are after: It may be possible within a single Linq statement, but often I hit weird-isms around Linq2Entities/Linq2SQL when it comes to view models and native .Net methods/structures so I tend to default to selecting the data separately to the end formatting.

```<code>var resultCollection = manyPartEntireCollection
  .Select( x => new { ManyPartId = x.Id, x.Name })
  .ToList()
  .Select( x => new OneToManyViewModel
    {
      OnePartId = onePartId,
      ManyPartId = x.ManyPartId,
      Name = x.Name,
      IsEnabled = manyPartIds.Contains(x.ManyPartId)
    }).ToList();
</code>```

A word of caution about code like this: Initially you may have a reasonable amount of data, but down the road you will encounter potential performance and resource issues with the .ToList() expressions. (No upper limit on # of items.)

update: if DynamicLinq is required, then you can implement the solution offered by dahlbyk on this thread: System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

the source for System.Linq.Dynamic can be found here: https://github.com/meatGUY/System.Linq.Dynamic  (Updated to meatGUY fork as it looks to be more up to date)

I've created a fork with this implementation available here: https://github.com/StevePy/System.Linq.Dynamic   I'll flick over a pull request to meatGUY to see if it's worth incorporating.

I made the modifications and it appears to do what you would expect. No idea why this hasn't been officially incorporated because it makes quite a bit of sense.  :)

His instructions are easy enough to follow and you will end up with a call that looks like:

```<code>var resultCollection = manyPartEntireCollection
  .Select<OneToManyViewModel>("new (@0 as OnePartId, Id as ManyPartId, Name as Name, @1.Contains(outerIt.Id) as Enable)", onePartId, manyParIds)
  .ToList();
</code>```

I tested it with a similar object model with the Contains to set a Boolean        flag in the view model and it worked a treat. Caveat though is on what that "outerIt" reference goes to.

Body:
I'm trying to use linq dynamic to create a selec that returns me a specific object. But I'm always getting the same error message: '(' expected

My select code:

var resultCollection = manyPartEntireCollection
                .Select("new MyNamespace.OneToManyViewModel(@0 as OnePartId, Id as ManyPartId, Name as Name, @1.Contains(outerIt.Id) as Enable)", onePartId, manyParIds)
                .Cast<OneToManyViewModel>()
                .ToList()
                ;

Thanks!

Body:
The main question from your example is "what is outerIt?" (@1.Contains(outerIt.Id)) This looks to be just a piece of a larger query. You may want to post up the complete set of expressions.

Based on an assumption of what it looks like you are after: It may be possible within a single Linq statement, but often I hit weird-isms around Linq2Entities/Linq2SQL when it comes to view models and native .Net methods/structures so I tend to default to selecting the data separately to the end formatting.

var resultCollection = manyPartEntireCollection
  .Select( x => new { ManyPartId = x.Id, x.Name })
  .ToList()
  .Select( x => new OneToManyViewModel
    {
      OnePartId = onePartId,
      ManyPartId = x.ManyPartId,
      Name = x.Name,
      IsEnabled = manyPartIds.Contains(x.ManyPartId)
    }).ToList();

A word of caution about code like this: Initially you may have a reasonable amount of data, but down the road you will encounter potential performance and resource issues with the .ToList() expressions. (No upper limit on # of items.)

update: if DynamicLinq is required, then you can implement the solution offered by dahlbyk on this thread: System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)

the source for System.Linq.Dynamic can be found here: https://github.com/meatGUY/System.Linq.Dynamic  (Updated to meatGUY fork as it looks to be more up to date)

I've created a fork with this implementation available here: https://github.com/StevePy/System.Linq.Dynamic   I'll flick over a pull request to meatGUY to see if it's worth incorporating.

I made the modifications and it appears to do what you would expect. No idea why this hasn't been officially incorporated because it makes quite a bit of sense.  :)

His instructions are easy enough to follow and you will end up with a call that looks like:

var resultCollection = manyPartEntireCollection
  .Select<OneToManyViewModel>("new (@0 as OnePartId, Id as ManyPartId, Name as Name, @1.Contains(outerIt.Id) as Enable)", onePartId, manyParIds)
  .ToList();

I tested it with a similar object model with the Contains to set a Boolean        flag in the view model and it worked a treat. Caveat though is on what that "outerIt" reference goes to.


问:
gsutil will not download files to my windows machine from powershell
```<code>gsutil -m cp -R 'gs://[BUCKET]/' 'C:/Users/[USER]/[FOLDER]'
</code>```

will display the following error

```<code>[Errno 22] invalid mode ('ab') or filename: u'C:\\Users\\[USER]\\[FOLDER]\\\\[BUCKET]\\[FILE].gstmp'
</code>```

I've tried changing the '/'s to '//' to '\' and '\' with no results whatsoever

答: So, after hours trying to find out this was happening.. it happened that the filenames had a character that can't be used in filenames in windows.. hope this helps if anybody else runs into this error.</p>

Body:
gsutil -m cp -R 'gs://[BUCKET]/' 'C:/Users/[USER]/[FOLDER]'

will display the following error

[Errno 22] invalid mode ('ab') or filename: u'C:\\Users\\[USER]\\[FOLDER]\\\\[BUCKET]\\[FILE].gstmp'

I've tried changing the '/'s to '//' to '\' and '\' with no results whatsoever


问:
What is NoOp in TensorFlow when Profiling?
I'm profiling ops on a GPU. What is going on behind the long NoOp?

It seems like NoOp might represent the time between transferring data from GPU to CPU, since the final operation, TopKV2, executes on the CPU (does not have a GPU kernel) in TF 0.11.0.

答:
I am not completely sure but it seems to be related to some initialization mechanism for the placeholder node in the graph.

No-op description from Tensorflow documentation


问:
How to use MAMP's version of PHP instead of the default on OSX
I would like to use MAMP's version of PHP instead of the default installed on my mac.  I tried using

ln -s /Applications/MAMP/bin/php5.3/bin/php php

but I get a "File exists" error.  What's the best way to work around this so I can just type php instead of the full path?

答:
Well none of this was working for me with OSX10.12.5

i have mac ports php70 installed at /opt/local/bin

which php showed:

```<code>/usr/bin/php
</code>```

I set up the aliases and local paths etc, which mostly worked for me, but other programs were failing (like composer)  so the solution for me was to prepend:

```<code>/opt/local/bin
/opt/local/sbin
</code>```

to the file /etc/paths

then it all worked a charm!

Body:
Well none of this was working for me with OSX10.12.5

i have mac ports php70 installed at /opt/local/bin

which php showed:

/usr/bin/php

I set up the aliases and local paths etc, which mostly worked for me, but other programs were failing (like composer)  so the solution for me was to prepend:

/opt/local/bin
/opt/local/sbin

to the file /etc/paths

then it all worked a charm!


问:
Spring Integration - handlers vs interceptors
In Spring Integration, handlers and interceptors look like they basically achieve the same thing.  There are even some 'duped' implementations, such as MessageTransformingChannelInterceptor and MessageTransformingHandler, which as far as I can tell provide the same functionality with different semantics.

Is there a time when one is appropriate and not another?  If it's a matter of preference then I'm guessing that there'd be some sort of convention?

Thanks,
Roy

答:
Handlers

Handler means a Class which handles with certain thing.

A handler is typically a component in a web application that processes incoming HTTP requests and generates corresponding responses using the Servlet API.

For example, in the Spring framework, a HandlerMapping is used to map requests to specific controllers or handlers based on the URL pattern or request method.

Handler is responsible for processing(i.e. executing the core functionality) a request and generating a response while a Filter is responsible for modifying or inspecting a request or response

Interceptors

Interceptors share a common API for the server and the client side.

Interceptors are often used to implement cross-cutting concerns such as transaction management, security, or logging.

Interceptors are part of Spring's AOP framework and are used to intercept method calls to Spring beans. They allow you to add behaviour to a method call before or after it is executed. Interceptors can be configured using annotations or XML configuration. Interceptors are used to intercept method calls to Spring beans.


问:
does not contain definition for Content.ReadAsStringAsync() when using web client call
this is my service

```<code>public Task<NewsModel> GetNews(string query,string count)
{
    var task = Task<NewsModel>.Factory
        .StartNew(() => {
            var responseData = "";
            NewsModel list = new NewsModel();
            var client = new HttpClient();
            var uri = "Some URL";
            using (var response = client.GetAsync(uri)) {
                responseData =  response.Content.ReadAsStringAsync();
                list = JsonConvert.DeserializeObject<NewsModel>(responseData);
                list.value.RemoveAll(item => item.image == null);
            }
            return list;

        });

    task.ContinueWith(t => {
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    task.ContinueWith(t => {
        if (t.Exception == null)
            return;

        var ex = t.Exception.Flatten();

    }, TaskContinuationOptions.OnlyOnFaulted);

    return task;
}
</code>```

compilation error

i am getting the above error when i try to compile
can you please tell me how can i use Content.ReadAsStringAsync() in the above functionality

答:
Those methods return Tasks so they should be awaited.

```<code>using (var response = await client.GetAsync(uri)) {
    responseData = await response.Content.ReadAsStringAsync();
    list = JsonConvert.DeserializeObject<NewsModel>(responseData);
    list.value.RemoveAll(item => item.image == null);
}
</code>```

In fact that entire method should be refactored to use async/await

```<code>HttpClient client = new HttpClient();
public async Task<NewsModel> GetNews(string query, string count) {
    NewsModel list = new NewsModel();
    var uri = "Some URL";
    using (var response = await client.GetAsync(uri)) {
        var responseData = await response.Content.ReadAsStringAsync();
        list = JsonConvert.DeserializeObject<NewsModel>(responseData);
        list.value.RemoveAll(item => item.image == null);
    }
    return list;
}
</code>```

Body:
this is my service

public Task<NewsModel> GetNews(string query,string count)
{
    var task = Task<NewsModel>.Factory
        .StartNew(() => {
            var responseData = "";
            NewsModel list = new NewsModel();
            var client = new HttpClient();
            var uri = "Some URL";
            using (var response = client.GetAsync(uri)) {
                responseData =  response.Content.ReadAsStringAsync();
                list = JsonConvert.DeserializeObject<NewsModel>(responseData);
                list.value.RemoveAll(item => item.image == null);
            }
            return list;

        });

    task.ContinueWith(t => {
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    task.ContinueWith(t => {
        if (t.Exception == null)
            return;

        var ex = t.Exception.Flatten();

    }, TaskContinuationOptions.OnlyOnFaulted);

    return task;
}

compilation error

i am getting the above error when i try to compile
can you please tell me how can i use Content.ReadAsStringAsync() in the above functionality

Body:
Those methods return Tasks so they should be awaited.

using (var response = await client.GetAsync(uri)) {
    responseData = await response.Content.ReadAsStringAsync();
    list = JsonConvert.DeserializeObject<NewsModel>(responseData);
    list.value.RemoveAll(item => item.image == null);
}

In fact that entire method should be refactored to use async/await

HttpClient client = new HttpClient();
public async Task<NewsModel> GetNews(string query, string count) {
    NewsModel list = new NewsModel();
    var uri = "Some URL";
    using (var response = await client.GetAsync(uri)) {
        var responseData = await response.Content.ReadAsStringAsync();
        list = JsonConvert.DeserializeObject<NewsModel>(responseData);
        list.value.RemoveAll(item => item.image == null);
    }
    return list;
}


问:
Install Node in ubuntu
I want to install node to run Angular2 program, but while installing I am getting this error:

```<code>npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN using --force I sure hope you know what you are doing.

/usr/local/lib/node_modules/npm/lib/cache.js:3
const BB = require('bluebird')
^^^^^
npm ERR! Use of const in strict mode.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-04T10_51_42_147Z-debug.log
</code>```

I've already tried this solution:

```<code>sudo npm cache clean -f
sudo npm install -g n
sudo n stable
</code>```

but even for first command "sudo npm cache clean -f" I am getting same issue. Please let me know if anyone aware about same.

答:
I suggest you download the Node archive from official site（https://nodejs.org/en/）

After that, you need the create a soft link to the bin file you just download from the site, the command line words may like this:

```<code>ln -s /opt/node-v6.10.2-linux-x64/bin/node /usr/bin/node
</code>```

Same for npm

Title: Install Node in ubuntu

Body:
I want to install node to run Angular2 program, but while installing I am getting this error:

npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN using --force I sure hope you know what you are doing.

/usr/local/lib/node_modules/npm/lib/cache.js:3
const BB = require('bluebird')
^^^^^
npm ERR! Use of const in strict mode.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-04T10_51_42_147Z-debug.log

I've already tried this solution:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

but even for first command "sudo npm cache clean -f" I am getting same issue. Please let me know if anyone aware about same.

Body:
I suggest you download the Node archive from official site（https://nodejs.org/en/）

After that, you need the create a soft link to the bin file you just download from the site, the command line words may like this:

ln -s /opt/node-v6.10.2-linux-x64/bin/node /usr/bin/node

Same for npm


问:
An uncaught Exception was encountered, Call to undefined method
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

```<code><?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}
</code>```

And this is what's on line 25

```<code>'id'=> $this->post('id'),
</code>```

答:
You are missing input in 'id' => $this->post('id')

So, the right code is as follow:

```<code>'id' => $this->input->post('id')
</code>```

You have to use input on all other places also.

Body:
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

<?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}

And this is what's on line 25

'id'=> $this->post('id'),

Body:
You are missing input in 'id' => $this->post('id')

So, the right code is as follow:

'id' => $this->input->post('id')

You have to use input on all other places also.


问:
How do I create an installer for Visual Studio 2008 addin?
I have done an addin (in C#) for visual studio, (almost) ready to deploy it. But I don't know how to do an installer for that.

I saw the link here but I don't know where to go from there...

This seemed to be useful, but I don't understand where to start, put which code snippet where...

Can someone guide me from the basics? Can't find the resources online I want :(

答:
Hope this helps, led me down the right path.

This is a real in depth from concept to implementation:

http://www.codeproject.com/KB/macros/LineCounterAddin.aspx

Found this also interesting:

http://social.msdn.microsoft.com/Forums/en/vsx/thread/cb5958f4-b503-456b-af24-ebfdde8ec6ad

http://www.mztools.com/articles/2008/MZ2008011.aspx

Wix is a great tool to deploy:

http://wix.sourceforge.net/votive.html

Any questions let me know.


Body:
I think you want like this

After Edit

ls_dict={}
for ls in x:
    key=ls[0]
    value=[ls[1:]]
    if key in ls_dict:
        value = ls[1:]
        ls_dict[key].append(value)
    else:
        value = [ls[1:]]
        ls_dict[key]=value
print(ls_dict)

output

{100: [[14, 12, 15], [21, 16, 11], [19, 10, 13]], 160: [[24, 15, 12], [43, 12, 65], [17, 53, 23]], 300: [[15, 17, 11], [66, 23, 12], [44, 70, 19]]}


问:
How to search same fiile and compare in pandas
I have some directory and files

```<code>Directory1

file1
file2
file3

Directory2

file1
file2
file3
</code>```

I would like to compare each file in each directory.

I tried

```<code>'glob.glob'
</code>```

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?

答:
Can you elaborate on what you mean by compare?

In order to get the list of files in your directory, you can use os.listdir('directory_path'), then you can iterate through the list and compare it with your reference file.
Also, this link tells you how to compare the content of two dataframes in pandas.

Body:
I have some directory and files

Directory1

file1
file2
file3

Directory2

file1
file2
file3

I would like to compare each file in each directory.

I tried

'glob.glob'

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?


问:
How to hide the BottomNavigationView below keyboard with adjustResize set
According to the material design spec, when the keyboard appears, the BottomNavigationView should hide underneath it. However, if I set android:windowSoftInputMode="adjustResize" in the Activity's manifest then the BottomNavigationView moves above the keyboard.

I need to set adjustResize to enable scrolling to the bottom of the screen while the keyboard is open. However, I do not want the BottomNavigationView to be visible. Can this be done?

How it currently looks:

The layout XML (in reality there would be a FrameLayout where the EditText is and the EditText would be inside it):

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input"
        android:layout_gravity="center"
        android:layout_centerVertical="true"/>

    <android.support.design.widget.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:menu="@menu/menu_bottom_navigation"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"/>

</RelativeLayout>
</code>```

答:
Add this to your activity in the manifest

```<code>android:windowSoftInputMode="adjustPan"
</code>```

So like

```<code><activity android:name=".feature.home.HomeActivity"
 android:windowSoftInputMode="adjustPan"/>
</code>```

Body:
According to the material design spec, when the keyboard appears, the BottomNavigationView should hide underneath it. However, if I set android:windowSoftInputMode="adjustResize" in the Activity's manifest then the BottomNavigationView moves above the keyboard.

I need to set adjustResize to enable scrolling to the bottom of the screen while the keyboard is open. However, I do not want the BottomNavigationView to be visible. Can this be done?

How it currently looks:

The layout XML (in reality there would be a FrameLayout where the EditText is and the EditText would be inside it):

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input"
        android:layout_gravity="center"
        android:layout_centerVertical="true"/>

    <android.support.design.widget.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:menu="@menu/menu_bottom_navigation"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"/>

</RelativeLayout>

Body:
Add this to your activity in the manifest

android:windowSoftInputMode="adjustPan"

So like

<activity android:name=".feature.home.HomeActivity"
 android:windowSoftInputMode="adjustPan"/>